altoslib: Correctly parse IMU cal data
[fw/altos] / altoslib / AltosLink.java
1 /*
2  * Copyright © 2011 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.altoslib_12;
20
21 import java.io.*;
22 import java.util.concurrent.*;
23 import java.util.*;
24
25 public abstract class AltosLink implements Runnable {
26
27         public final static int ERROR = -1;
28         public final static int TIMEOUT = -2;
29
30         public abstract int getchar() throws InterruptedException;
31         public abstract void print(String data) throws InterruptedException;
32         public abstract void putchar(byte c);
33         public abstract void close() throws InterruptedException;
34
35         public static boolean debug = false;
36         public static void set_debug(boolean in_debug) { debug = in_debug; }
37
38         public boolean has_error;
39
40         LinkedList<String> pending_output = new LinkedList<String>();
41
42         public LinkedList<LinkedBlockingQueue<AltosLine>> monitors = new LinkedList<LinkedBlockingQueue<AltosLine>> ();;
43         public LinkedBlockingQueue<AltosLine> reply_queue = new LinkedBlockingQueue<AltosLine>();
44         public LinkedBlockingQueue<byte[]> binary_queue = new LinkedBlockingQueue<byte[]>();
45
46         private String match_string = null;
47
48         public synchronized void add_monitor(LinkedBlockingQueue<AltosLine> q) {
49                 set_monitor(true);
50                 monitors.add(q);
51         }
52
53         public synchronized void remove_monitor(LinkedBlockingQueue<AltosLine> q) {
54                 monitors.remove(q);
55                 if (monitors.isEmpty())
56                         set_monitor(false);
57         }
58
59         public void printf(String format, Object ... arguments) {
60                 String  line = String.format(format, arguments);
61                 if (debug) {
62                         synchronized (pending_output) {
63                                 pending_output.add(line);
64                         }
65                 }
66                 try {
67                         print(line);
68                 } catch (InterruptedException ie) {
69
70                 }
71         }
72
73         public String get_reply_no_dialog(int timeout) throws InterruptedException, TimeoutException {
74                 flush_output();
75                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
76                 if (line != null)
77                         return line.line;
78                 return null;
79         }
80
81         public String get_reply() throws InterruptedException {
82                 return get_reply(5000);
83         }
84
85
86         public abstract boolean can_cancel_reply();
87         public abstract boolean show_reply_timeout();
88         public abstract void hide_reply_timeout();
89
90         public boolean  reply_abort;
91         public int      in_reply;
92         boolean cancel_enable = true;
93
94         public void set_cancel_enable(boolean e) {
95                 cancel_enable = e;
96         }
97
98         boolean         reply_timeout_shown = false;
99
100         private boolean check_reply_timeout() {
101                 if (!cancel_enable)
102                         return false;
103                 if (!reply_timeout_shown)
104                         reply_timeout_shown = show_reply_timeout();
105                 return reply_abort;
106         }
107
108         private void cleanup_reply_timeout() {
109                 if (reply_timeout_shown) {
110                         reply_timeout_shown = false;
111                         hide_reply_timeout();
112                 }
113         }
114
115         private int     len_read = 0;
116
117         private boolean match_bytes(byte[] bytes, int byte_count, String match) {
118                 if (byte_count < match.length())
119                         return false;
120                 String  line = new String(bytes, 0, byte_count, AltosLib.unicode_set);
121                 if (line == null)
122                         return false;
123                 return line.indexOf(match) >= 0;
124         }
125
126         public void run () {
127                 int c;
128                 byte[] line_bytes = null;
129                 int line_count = 0;
130
131                 try {
132                         for (;;) {
133                                 c = getchar();
134                                 if (Thread.interrupted()) {
135                                         break;
136                                 }
137                                 if (c == ERROR) {
138                                         if (debug)
139                                                 System.out.printf("ERROR\n");
140                                         has_error = true;
141                                         add_telem (new AltosLine());
142                                         add_reply (new AltosLine());
143                                         break;
144                                 }
145                                 if (c == TIMEOUT) {
146                                         if (debug)
147                                                 System.out.printf("TIMEOUT\n");
148                                         continue;
149                                 }
150                                 if (c == '\r' && len_read == 0)
151                                         continue;
152                                 synchronized(this) {
153                                         if (c == '\n' && len_read == 0) {
154                                                 if (line_count != 0) {
155                                                         add_bytes(line_bytes, line_count);
156                                                         line_count = 0;
157                                                 }
158                                         } else {
159                                                 if (line_bytes == null) {
160                                                         line_bytes = new byte[256];
161                                                 } else if (line_count == line_bytes.length) {
162                                                         byte[] new_line_bytes = new byte[line_count * 2];
163                                                         System.arraycopy(line_bytes, 0, new_line_bytes, 0, line_count);
164                                                         line_bytes = new_line_bytes;
165                                                 }
166                                                 line_bytes[line_count] = (byte) c;
167                                                 line_count++;
168                                                 if (len_read !=0 && line_count == len_read) {
169                                                         add_binary(line_bytes, line_count);
170                                                         line_count = 0;
171                                                         len_read = 0;
172                                                 }
173                                                 if (match_string != null && match_bytes(line_bytes, line_count, match_string)) {
174                                                         match_string = null;
175                                                         add_bytes(line_bytes, line_count);
176                                                         line_count = 0;
177                                                 }
178                                         }
179                                 }
180                         }
181                 } catch (InterruptedException e) {
182                 }
183         }
184
185         public void set_match(String match) {
186                 match_string = match;
187         }
188
189         public String get_reply(int timeout) throws InterruptedException {
190                 boolean can_cancel = can_cancel_reply();
191                 String  reply = null;
192
193 //              if (!can_cancel && remote)
194 //                      System.out.printf("Uh-oh, reading remote serial device from swing thread\n");
195
196                 if (remote && can_cancel) {
197                         timeout = 500;
198                         switch (telemetry_rate) {
199                         case AltosLib.ao_telemetry_rate_38400:
200                         default:
201                                 timeout = 500;
202                                 break;
203                         case AltosLib.ao_telemetry_rate_9600:
204                                 timeout = 2000;
205                                 break;
206                         case AltosLib.ao_telemetry_rate_2400:
207                                 timeout = 8000;
208                                 break;
209                         }
210                 }
211                 try {
212                         ++in_reply;
213
214                         flush_output();
215
216                         reply_abort = false;
217                         reply_timeout_shown = false;
218                         for (;;) {
219                                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
220                                 if (line != null) {
221                                         cleanup_reply_timeout();
222                                         reply = line.line;
223                                         break;
224                                 }
225                                 if (!remote || !can_cancel || check_reply_timeout()) {
226                                         reply = null;
227                                         break;
228                                 }
229                         }
230                 } finally {
231                         --in_reply;
232                 }
233                 return reply;
234         }
235
236         public byte[] get_binary_reply(int timeout, int len) throws InterruptedException {
237                 boolean can_cancel = can_cancel_reply();
238                 byte[] bytes = null;
239
240                 synchronized(this) {
241                         len_read = len;
242                 }
243                 try {
244                         ++in_reply;
245
246                         flush_output();
247
248                         reply_abort = false;
249                         reply_timeout_shown = false;
250                         for (;;) {
251                                 bytes = binary_queue.poll(timeout, TimeUnit.MILLISECONDS);
252                                 if (bytes != null) {
253                                         cleanup_reply_timeout();
254                                         break;
255                                 }
256                                 if (!remote || !can_cancel || check_reply_timeout()) {
257                                         bytes = null;
258                                         break;
259                                 }
260                         }
261
262                 } finally {
263                         --in_reply;
264                 }
265                 return bytes;
266         }
267
268         public void add_telem(AltosLine line) throws InterruptedException {
269                 for (int e = 0; e < monitors.size(); e++) {
270                         LinkedBlockingQueue<AltosLine> q = monitors.get(e);
271                         q.put(line);
272                 }
273         }
274
275         public void add_reply(AltosLine line) throws InterruptedException {
276                 reply_queue.put (line);
277         }
278
279         public void abort_reply() {
280                 try {
281                         add_telem (new AltosLine());
282                         add_reply (new AltosLine());
283                 } catch (InterruptedException ie) {
284                 }
285         }
286
287         public void add_string(String line) throws InterruptedException {
288                 if (line.startsWith("TELEM") || line.startsWith("VERSION") || line.startsWith("CRC")) {
289                         add_telem(new AltosLine(line));
290                 } else {
291                         add_reply(new AltosLine(line));
292                 }
293         }
294
295         public void add_bytes(byte[] bytes, int len) throws InterruptedException {
296                 String  line;
297                 line = new String(bytes, 0, len, AltosLib.unicode_set);
298                 if (debug)
299                         System.out.printf("\t\t\t\t\t%s\n", line);
300                 add_string(line);
301         }
302
303         public void add_binary(byte[] bytes, int len) throws InterruptedException {
304                 byte[] dup = new byte[len];
305
306                 if (debug)
307                         System.out.printf ("\t\t\t\t\t%d:", len);
308                 for(int i = 0; i < len; i++) {
309                         dup[i] = bytes[i];
310                         if (debug)
311                                 System.out.printf(" %02x", dup[i]);
312                 }
313                 if (debug)
314                         System.out.printf("\n");
315
316                 binary_queue.put(dup);
317         }
318
319         public synchronized void flush_output() {
320                 if (pending_output == null)
321                         return;
322                 synchronized (pending_output) {
323                         for (String s : pending_output)
324                                 System.out.print(s);
325                         pending_output.clear();
326                 }
327         }
328
329         public void flush_input(int timeout) throws InterruptedException {
330                 flush_output();
331                 boolean got_some;
332
333                 do {
334                         Thread.sleep(timeout);
335                         got_some = !reply_queue.isEmpty();
336                         reply_queue.clear();
337                 } while (got_some);
338         }
339
340
341         public void flush_input() throws InterruptedException {
342                 if (remote)
343                         flush_input(500);
344                 else
345                         flush_input(100);
346         }
347
348
349         /*
350          * Various command-level operations on
351          * the link
352          */
353         public boolean monitor_mode = false;
354         public int telemetry = AltosLib.ao_telemetry_standard;
355         public int telemetry_rate = -1;
356         public double frequency;
357         public String callsign;
358         AltosConfigData config_data;
359
360         private Object config_data_lock = new Object();
361
362         private int telemetry_len() {
363                 return AltosLib.telemetry_len(telemetry);
364         }
365
366         private void set_radio_freq(int frequency) {
367                 if (monitor_mode)
368                         printf("m 0\nc F %d\nm %x\n",
369                                frequency, telemetry_len());
370                 else
371                         printf("c F %d\n", frequency);
372                 flush_output();
373         }
374
375         public void set_radio_frequency(double frequency,
376                                         boolean has_frequency,
377                                         boolean has_setting,
378                                         int cal) {
379                 if (debug)
380                         System.out.printf("set_radio_frequency %7.3f (freq %b) (set %b) %d\n", frequency, has_frequency, has_setting, cal);
381                 if (frequency == 0)
382                         return;
383                 if (has_frequency)
384                         set_radio_freq((int) Math.floor (frequency * 1000 + 0.5));
385                 else if (has_setting)
386                         set_radio_setting(AltosConvert.radio_frequency_to_setting(frequency, cal));
387                 else
388                         set_channel(AltosConvert.radio_frequency_to_channel(frequency));
389         }
390
391         public void set_radio_frequency(double in_frequency) throws InterruptedException, TimeoutException {
392                 frequency = in_frequency;
393                 config_data();
394                 set_radio_frequency(frequency,
395                                     config_data.radio_frequency > 0,
396                                     config_data.radio_setting > 0,
397                                     config_data.radio_calibration);
398         }
399
400         public void set_telemetry(int in_telemetry) {
401                 telemetry = in_telemetry;
402                 if (monitor_mode)
403                         printf("m 0\nm %x\n", telemetry_len());
404                 flush_output();
405         }
406
407         public void set_telemetry_rate(int in_telemetry_rate) {
408                 telemetry_rate = in_telemetry_rate;
409                 if (monitor_mode)
410                         printf("m 0\nc T %d\nm %x\n", telemetry_rate, telemetry_len());
411                 else
412                         printf("c T %d\n", telemetry_rate);
413                 flush_output();
414         }
415
416         public synchronized void set_monitor(boolean monitor) {
417                 monitor_mode = monitor;
418                 if (monitor)
419                         printf("m %x\n", telemetry_len());
420                 else
421                         printf("m 0\n");
422                 flush_output();
423         }
424
425         public synchronized boolean get_monitor() {
426                 return monitor_mode;
427         }
428
429         private void set_channel(int channel) {
430                 if (monitor_mode)
431                         printf("m 0\nc r %d\nm %x\n",
432                                channel, telemetry_len());
433                 else
434                         printf("c r %d\n", channel);
435                 flush_output();
436         }
437
438         private void set_radio_setting(int setting) {
439                 if (monitor_mode)
440                         printf("m 0\nc R %d\nm %x\n",
441                                setting, telemetry_len());
442                 else
443                         printf("c R %d\n", setting);
444                 flush_output();
445         }
446
447         public AltosConfigData config_data() throws InterruptedException, TimeoutException {
448                 synchronized(config_data_lock) {
449                         if (config_data == null) {
450                                 printf("m 0\n");
451                                 config_data = new AltosConfigData(this);
452                                 if (monitor_mode)
453                                         set_monitor(true);
454                         }
455                         return config_data;
456                 }
457         }
458
459         public void set_callsign(String callsign) {
460                 this.callsign = callsign;
461                 if (callsign != null) {
462                         printf ("c c %s\n", callsign);
463                         flush_output();
464                 }
465         }
466
467         public boolean is_loader() throws InterruptedException {
468                 boolean ret = false;
469                 printf("v\n");
470                 for (;;) {
471                         String line = get_reply();
472
473                         if (line == null)
474                                 return false;
475                         if (line.startsWith("software-version"))
476                                 break;
477                         if (line.startsWith("altos-loader"))
478                                 ret = true;
479                 }
480                 return ret;
481         }
482
483         public void to_loader() throws InterruptedException {
484                 printf("X\n");
485                 flush_output();
486                 close();
487                 Thread.sleep(1000);
488         }
489
490         public boolean remote;
491         public int serial;
492         public String name;
493
494         public void start_remote() throws TimeoutException, InterruptedException {
495                 if (frequency == 0.0)
496                         frequency = AltosPreferences.frequency(serial);
497                 if (debug)
498                         System.out.printf("start remote %7.3f\n", frequency);
499                 set_radio_frequency(frequency);
500                 if (telemetry_rate < 0)
501                         telemetry_rate = AltosPreferences.telemetry_rate(serial);
502                 set_telemetry_rate(telemetry_rate);
503                 if (callsign == null || callsign.equals(""))
504                         callsign = AltosPreferences.callsign();
505                 set_callsign(callsign);
506                 printf("p\nE 0\n");
507                 flush_input();
508                 remote = true;
509         }
510
511         public void stop_remote() throws InterruptedException {
512                 if (debug)
513                         System.out.printf("stop remote\n");
514                 try {
515                         flush_input();
516                 } finally {
517                         printf ("~\n");
518                         flush_output();
519                 }
520                 remote = false;
521         }
522
523         public int rssi() throws TimeoutException, InterruptedException {
524                 if (remote)
525                         return 0;
526                 printf("s\n");
527                 String line = get_reply_no_dialog(5000);
528                 if (line == null)
529                         throw new TimeoutException();
530                 String[] items = line.split("\\s+");
531                 if (items.length < 2)
532                         return 0;
533                 if (!items[0].equals("RSSI:"))
534                         return 0;
535                 int rssi = Integer.parseInt(items[1]);
536                 return rssi;
537         }
538
539         public String[] adc() throws TimeoutException, InterruptedException {
540                 printf("a\n");
541                 for (;;) {
542                         String line = get_reply_no_dialog(5000);
543                         if (line == null) {
544                                 throw new TimeoutException();
545                         }
546                         if (!line.startsWith("tick:"))
547                                 continue;
548                         String[] items = line.split("\\s+");
549                         return items;
550                 }
551         }
552
553         public boolean has_monitor_battery() {
554                 return config_data.has_monitor_battery();
555         }
556
557         public double monitor_battery() throws InterruptedException {
558                 int monitor_batt = AltosLib.MISSING;
559
560                 if (config_data.has_monitor_battery()) {
561                         try {
562                                 String[] items = adc();
563                                 for (int i = 0; i < items.length;) {
564                                         if (items[i].equals("batt")) {
565                                                 monitor_batt = Integer.parseInt(items[i+1]);
566                                                 i += 2;
567                                                 continue;
568                                         }
569                                         i++;
570                                 }
571                         } catch (TimeoutException te) {
572                         }
573                 }
574                 if (monitor_batt == AltosLib.MISSING)
575                         return AltosLib.MISSING;
576
577                 double  volts = AltosLib.MISSING;
578                 if (config_data.product.startsWith("TeleBT-v3") || config_data.product.startsWith("TeleBT-v4")) {
579                         volts = AltosConvert.tele_bt_3_battery(monitor_batt);
580                 } else {
581                         volts = AltosConvert.cc_battery_to_voltage(monitor_batt);
582                 }
583
584                 return volts;
585         }
586
587         public AltosLink() {
588                 callsign = "";
589                 has_error = false;
590         }
591 }