altoslib: Flush settings restoration commands after accel cal
[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         private AltosConfigData config_data_local;
359         private AltosConfigData config_data_remote;
360
361         private Object config_data_lock = new Object();
362
363         private int telemetry_len() {
364                 return AltosLib.telemetry_len(telemetry);
365         }
366
367         private void set_radio_freq(int frequency) {
368                 if (monitor_mode)
369                         printf("m 0\nc F %d\nm %x\n",
370                                frequency, telemetry_len());
371                 else
372                         printf("c F %d\n", frequency);
373                 flush_output();
374         }
375
376         public void set_radio_frequency(double frequency,
377                                         boolean has_frequency,
378                                         boolean has_setting,
379                                         int cal) {
380                 if (debug)
381                         System.out.printf("set_radio_frequency %7.3f (freq %b) (set %b) %d\n", frequency, has_frequency, has_setting, cal);
382                 if (frequency == 0)
383                         return;
384                 if (has_frequency)
385                         set_radio_freq((int) Math.floor (frequency * 1000 + 0.5));
386                 else if (has_setting)
387                         set_radio_setting(AltosConvert.radio_frequency_to_setting(frequency, cal));
388                 else
389                         set_channel(AltosConvert.radio_frequency_to_channel(frequency));
390         }
391
392         public void set_radio_frequency(double in_frequency) throws InterruptedException, TimeoutException {
393                 frequency = in_frequency;
394                 AltosConfigData config_data = config_data();
395                 set_radio_frequency(frequency,
396                                     config_data.radio_frequency > 0,
397                                     config_data.radio_setting > 0,
398                                     config_data.radio_calibration);
399         }
400
401         public void set_telemetry(int in_telemetry) {
402                 telemetry = in_telemetry;
403                 if (monitor_mode)
404                         printf("m 0\nm %x\n", telemetry_len());
405                 flush_output();
406         }
407
408         public void set_telemetry_rate(int in_telemetry_rate) {
409                 telemetry_rate = in_telemetry_rate;
410                 if (monitor_mode)
411                         printf("m 0\nc T %d\nm %x\n", telemetry_rate, telemetry_len());
412                 else
413                         printf("c T %d\n", telemetry_rate);
414                 flush_output();
415         }
416
417         public synchronized void set_monitor(boolean monitor) {
418                 monitor_mode = monitor;
419                 if (monitor)
420                         printf("m %x\n", telemetry_len());
421                 else
422                         printf("m 0\n");
423                 flush_output();
424         }
425
426         public synchronized boolean get_monitor() {
427                 return monitor_mode;
428         }
429
430         private void set_channel(int channel) {
431                 if (monitor_mode)
432                         printf("m 0\nc r %d\nm %x\n",
433                                channel, telemetry_len());
434                 else
435                         printf("c r %d\n", channel);
436                 flush_output();
437         }
438
439         private void set_radio_setting(int setting) {
440                 if (monitor_mode)
441                         printf("m 0\nc R %d\nm %x\n",
442                                setting, telemetry_len());
443                 else
444                         printf("c R %d\n", setting);
445                 flush_output();
446         }
447
448         public AltosConfigData config_data() throws InterruptedException, TimeoutException {
449                 synchronized(config_data_lock) {
450                         AltosConfigData config_data;
451
452                         if (remote) {
453                                 if (config_data_remote == null) {
454                                         printf("m 0\n");
455                                         config_data_remote = new AltosConfigData(this);
456                                         if (monitor_mode)
457                                                 set_monitor(true);
458                                 }
459                                 config_data = config_data_remote;
460                         } else {
461                                 if (config_data_local == null) {
462                                         printf("m 0\n");
463                                         config_data_local = new AltosConfigData(this);
464                                         if (monitor_mode)
465                                                 set_monitor(true);
466                                 }
467                                 config_data = config_data_local;
468                         }
469                         return config_data;
470                 }
471         }
472
473         public void set_callsign(String callsign) {
474                 this.callsign = callsign;
475                 if (callsign != null) {
476                         printf ("c c %s\n", callsign);
477                         flush_output();
478                 }
479         }
480
481         public boolean is_loader() throws InterruptedException {
482                 boolean ret = false;
483                 printf("v\n");
484                 for (;;) {
485                         String line = get_reply();
486
487                         if (line == null)
488                                 return false;
489                         if (line.startsWith("software-version"))
490                                 break;
491                         if (line.startsWith("altos-loader"))
492                                 ret = true;
493                 }
494                 return ret;
495         }
496
497         public void to_loader() throws InterruptedException {
498                 printf("X\n");
499                 flush_output();
500                 close();
501                 Thread.sleep(1000);
502         }
503
504         public boolean remote;
505         public int serial;
506         public String name;
507
508         public void start_remote() throws TimeoutException, InterruptedException {
509                 if (frequency == 0.0)
510                         frequency = AltosPreferences.frequency(serial);
511                 if (debug)
512                         System.out.printf("start remote %7.3f\n", frequency);
513                 set_radio_frequency(frequency);
514                 if (telemetry_rate < 0)
515                         telemetry_rate = AltosPreferences.telemetry_rate(serial);
516                 set_telemetry_rate(telemetry_rate);
517                 if (callsign == null || callsign.equals(""))
518                         callsign = AltosPreferences.callsign();
519                 set_callsign(callsign);
520                 printf("p\nE 0\n");
521                 flush_input();
522                 remote = true;
523         }
524
525         public void stop_remote() throws InterruptedException {
526                 if (debug)
527                         System.out.printf("stop remote\n");
528                 try {
529                         flush_input();
530                 } finally {
531                         printf ("~\n");
532                         flush_output();
533                 }
534                 remote = false;
535         }
536
537         public int rssi() throws TimeoutException, InterruptedException {
538                 if (remote)
539                         return 0;
540                 printf("s\n");
541                 String line = get_reply_no_dialog(5000);
542                 if (line == null)
543                         throw new TimeoutException();
544                 String[] items = line.split("\\s+");
545                 if (items.length < 2)
546                         return 0;
547                 if (!items[0].equals("RSSI:"))
548                         return 0;
549                 int rssi = Integer.parseInt(items[1]);
550                 return rssi;
551         }
552
553         public String[] adc() throws TimeoutException, InterruptedException {
554                 printf("a\n");
555                 for (;;) {
556                         String line = get_reply_no_dialog(5000);
557                         if (line == null) {
558                                 throw new TimeoutException();
559                         }
560                         if (!line.startsWith("tick:"))
561                                 continue;
562                         String[] items = line.split("\\s+");
563                         return items;
564                 }
565         }
566
567         public boolean has_monitor_battery() {
568                 try {
569                         return config_data().has_monitor_battery();
570                 } catch (InterruptedException ie) {
571                         return false;
572                 } catch (TimeoutException te) {
573                         return false;
574                 }
575         }
576
577         public double monitor_battery() throws InterruptedException {
578                 double  volts = AltosLib.MISSING;
579
580                 try {
581                         AltosConfigData config_data = config_data();
582                         int monitor_batt = AltosLib.MISSING;
583
584                         if (config_data.has_monitor_battery()) {
585                                 String[] items = adc();
586                                 for (int i = 0; i < items.length;) {
587                                         if (items[i].equals("batt")) {
588                                                 monitor_batt = Integer.parseInt(items[i+1]);
589                                                 i += 2;
590                                                 continue;
591                                         }
592                                         i++;
593                                 }
594                         }
595                         if (monitor_batt != AltosLib.MISSING) {
596                                 if (config_data.product.startsWith("TeleBT-v3") || config_data.product.startsWith("TeleBT-v4")) {
597                                         volts = AltosConvert.tele_bt_3_battery(monitor_batt);
598                                 } else {
599                                         volts = AltosConvert.cc_battery_to_voltage(monitor_batt);
600                                 }
601                         }
602
603                 } catch (TimeoutException te) {
604                 }
605                 return volts;
606         }
607
608         public AltosLink() {
609                 callsign = "";
610                 has_error = false;
611         }
612 }