altosui: Ensure serial code tracks reply nesting correctly
[fw/altos] / altosui / AltosSerial.java
1 /*
2  * Copyright © 2010 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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 /*
19  * Deal with TeleDongle on a serial port
20  */
21
22 package altosui;
23
24 import java.lang.*;
25 import java.io.*;
26 import java.util.concurrent.*;
27 import java.util.*;
28 import java.text.*;
29 import java.awt.*;
30 import java.awt.event.*;
31 import javax.swing.*;
32 import javax.swing.filechooser.FileNameExtensionFilter;
33 import javax.swing.table.*;
34
35 import libaltosJNI.*;
36
37 /*
38  * This class reads from the serial port and places each received
39  * line in a queue. Dealing with that queue is left up to other
40  * threads.
41  */
42
43 public class AltosSerial implements Runnable {
44
45         static java.util.List<String> devices_opened = Collections.synchronizedList(new LinkedList<String>());
46
47         AltosDevice device;
48         SWIGTYPE_p_altos_file altos;
49         LinkedList<LinkedBlockingQueue<AltosLine>> monitors;
50         LinkedBlockingQueue<AltosLine> reply_queue;
51         Thread input_thread;
52         String line;
53         byte[] line_bytes;
54         int line_count;
55         boolean monitor_mode;
56         int telemetry;
57         double frequency;
58         static boolean debug;
59         boolean remote;
60         LinkedList<String> pending_output = new LinkedList<String>();
61         Frame frame;
62         AltosConfigData config_data;
63
64         static void set_debug(boolean new_debug) {
65                 debug = new_debug;
66         }
67
68         public void run () {
69                 int c;
70
71                 try {
72                         for (;;) {
73                                 c = libaltos.altos_getchar(altos, 0);
74                                 if (Thread.interrupted())
75                                         break;
76                                 if (c == libaltosConstants.LIBALTOS_ERROR) {
77                                         for (int e = 0; e < monitors.size(); e++) {
78                                                 LinkedBlockingQueue<AltosLine> q = monitors.get(e);
79                                                 q.put(new AltosLine());
80                                         }
81                                         reply_queue.put (new AltosLine());
82                                         break;
83                                 }
84                                 if (c == libaltosConstants.LIBALTOS_TIMEOUT)
85                                         continue;
86                                 if (c == '\r')
87                                         continue;
88                                 synchronized(this) {
89                                         if (c == '\n') {
90                                                 if (line_count != 0) {
91                                                         try {
92                                                                 line = new String(line_bytes, 0, line_count, "UTF-8");
93                                                         } catch (UnsupportedEncodingException ue) {
94                                                                 line = "";
95                                                                 for (int i = 0; i < line_count; i++)
96                                                                         line = line + line_bytes[i];
97                                                         }
98                                                         if (debug)
99                                                                 System.out.printf("\t\t\t\t\t%s\n", line);
100                                                         if (line.startsWith("TELEM") || line.startsWith("VERSION") || line.startsWith("CRC")) {
101                                                                 for (int e = 0; e < monitors.size(); e++) {
102                                                                         LinkedBlockingQueue<AltosLine> q = monitors.get(e);
103                                                                         q.put(new AltosLine (line));
104                                                                 }
105                                                         } else {
106                                                                 reply_queue.put(new AltosLine (line));
107                                                         }
108                                                         line_count = 0;
109                                                         line = "";
110                                                 }
111                                         } else {
112                                                 if (line_bytes == null) {
113                                                         line_bytes = new byte[256];
114                                                 } else if (line_count == line_bytes.length) {
115                                                         byte[] new_line_bytes = new byte[line_count * 2];
116                                                         System.arraycopy(line_bytes, 0, new_line_bytes, 0, line_count);
117                                                         line_bytes = new_line_bytes;
118                                                 }
119                                                 line_bytes[line_count] = (byte) c;
120                                                 line_count++;
121                                         }
122                                 }
123                         }
124                 } catch (InterruptedException e) {
125                 }
126         }
127
128         public void flush_output() {
129                 if (altos != null) {
130                         for (String s : pending_output)
131                                 System.out.print(s);
132                         pending_output.clear();
133                         libaltos.altos_flush(altos);
134                 }
135         }
136
137         boolean         abort;
138         JDialog         timeout_dialog;
139         boolean timeout_started = false;
140
141         private void stop_timeout_dialog() {
142                 if (timeout_started) {
143                         timeout_started = false;
144                         Runnable r = new Runnable() {
145                                         public void run() {
146                                                 timeout_dialog.setVisible(false);
147                                         }
148                                 };
149                         SwingUtilities.invokeLater(r);
150                 }
151         }
152
153         private void start_timeout_dialog_internal() {
154
155                 Object[] options = { "Cancel" };
156
157                 JOptionPane     pane = new JOptionPane();
158                 pane.setMessage(String.format("Connecting to %s, %7.3f MHz", device.toShortString(), frequency));
159                 pane.setOptions(options);
160                 pane.setInitialValue(null);
161
162                 timeout_dialog = pane.createDialog(frame, "Connecting...");
163
164                 timeout_dialog.setVisible(true);
165
166                 Object o = pane.getValue();
167                 if (o == null)
168                         return;
169                 if (options[0].equals(o))
170                         abort = true;
171                 timeout_dialog.dispose();
172                 timeout_dialog = null;
173         }
174
175         private boolean check_timeout() {
176                 if (!timeout_started && frame != null) {
177                         if (!SwingUtilities.isEventDispatchThread()) {
178                                 timeout_started = true;
179                                 Runnable r = new Runnable() {
180                                                 public void run() {
181                                                         start_timeout_dialog_internal();
182                                                 }
183                                         };
184                                 SwingUtilities.invokeLater(r);
185                         }
186                 }
187                 return abort;
188         }
189
190         public void flush_input() {
191                 flush_output();
192                 boolean got_some;
193
194                 int timeout = 100;
195                 if (remote)
196                         timeout = 500;
197                 do {
198                         try {
199                                 Thread.sleep(timeout);
200                         } catch (InterruptedException ie) {
201                         }
202                         got_some = !reply_queue.isEmpty();
203                         synchronized(this) {
204                                 if (!"VERSION".startsWith(line) &&
205                                     !line.startsWith("VERSION"))
206                                         line = "";
207                                 reply_queue.clear();
208                         }
209                 } while (got_some);
210         }
211
212         int     in_reply;
213
214         public String get_reply(int timeout) throws InterruptedException {
215                 boolean can_cancel = true;
216                 String  reply = null;
217
218                 try {
219                         ++in_reply;
220
221                         if (SwingUtilities.isEventDispatchThread()) {
222                                 can_cancel = false;
223                                 if (remote)
224                                         System.out.printf("Uh-oh, reading remote serial device from swing thread\n");
225                         }
226                         flush_output();
227                         if (remote && can_cancel) {
228                                 timeout = 500;
229                         }
230                         abort = false;
231                         timeout_started = false;
232                         for (;;) {
233                                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
234                                 if (line != null) {
235                                         stop_timeout_dialog();
236                                         reply = line.line;
237                                         break;
238                                 }
239                                 if (!remote || !can_cancel || check_timeout()) {
240                                         reply = null;
241                                         break;
242                                 }
243                         }
244                 } finally {
245                         --in_reply;
246                 }
247                 return reply;
248         }
249
250         public String get_reply() throws InterruptedException {
251                 return get_reply(5000);
252         }
253
254         public String get_reply_no_dialog(int timeout) throws InterruptedException, TimeoutException {
255                 flush_output();
256                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
257                 if (line != null)
258                         return line.line;
259                 return null;
260         }
261
262         public void add_monitor(LinkedBlockingQueue<AltosLine> q) {
263                 set_monitor(true);
264                 monitors.add(q);
265         }
266
267         public void remove_monitor(LinkedBlockingQueue<AltosLine> q) {
268                 monitors.remove(q);
269                 if (monitors.isEmpty())
270                         set_monitor(false);
271         }
272
273         public void close() {
274                 if (remote)
275                         stop_remote();
276                 if (in_reply != 0)
277                         System.out.printf("Uh-oh. Closing active serial device\n");
278
279                 if (altos != null) {
280                         libaltos.altos_close(altos);
281                 }
282                 if (input_thread != null) {
283                         try {
284                                 input_thread.interrupt();
285                                 input_thread.join();
286                         } catch (InterruptedException e) {
287                         }
288                         input_thread = null;
289                 }
290                 if (altos != null) {
291                         libaltos.altos_free(altos);
292                         altos = null;
293                 }
294                 synchronized (devices_opened) {
295                         devices_opened.remove(device.getPath());
296                 }
297                 if (debug)
298                         System.out.printf("Closing %s\n", device.getPath());
299         }
300
301         private void putc(char c) {
302                 if (altos != null)
303                         libaltos.altos_putchar(altos, c);
304         }
305
306         public void print(String data) {
307                 if (debug)
308                         pending_output.add(data);
309                 for (int i = 0; i < data.length(); i++)
310                         putc(data.charAt(i));
311         }
312
313         public void printf(String format, Object ... arguments) {
314                 print(String.format(format, arguments));
315         }
316
317         private void open() throws FileNotFoundException, AltosSerialInUseException {
318                 synchronized (devices_opened) {
319                         if (devices_opened.contains(device.getPath()))
320                                 throw new AltosSerialInUseException(device);
321                         devices_opened.add(device.getPath());
322                 }
323                 altos = device.open();
324                 if (altos == null) {
325                         close();
326                         throw new FileNotFoundException(device.toShortString());
327                 }
328                 if (debug)
329                         System.out.printf("Open %s\n", device.getPath());
330                 input_thread = new Thread(this);
331                 input_thread.start();
332                 print("~\nE 0\n");
333                 set_monitor(false);
334                 flush_output();
335         }
336
337         private int telemetry_len() {
338                 return Altos.telemetry_len(telemetry);
339         }
340
341         private void set_channel(int channel) {
342                 if (altos != null) {
343                         if (monitor_mode)
344                                 printf("m 0\nc r %d\nm %x\n",
345                                        channel, telemetry_len());
346                         else
347                                 printf("c r %d\n", channel);
348                         flush_output();
349                 }
350         }
351
352         private void set_radio_setting(int setting) {
353                 if (altos != null) {
354                         if (monitor_mode)
355                                 printf("m 0\nc R %d\nc r 0\nm %x\n",
356                                        setting, telemetry_len());
357                         else
358                                 printf("c R %d\nc r 0\n", setting);
359                         flush_output();
360                 }
361         }
362
363         public void set_radio_frequency(double frequency,
364                                         boolean has_setting,
365                                         int cal) {
366                 if (has_setting)
367                         set_radio_setting(AltosConvert.radio_frequency_to_setting(frequency, cal));
368                 else
369                         set_channel(AltosConvert.radio_frequency_to_channel(frequency));
370         }
371
372         public void set_radio_frequency(double in_frequency) throws InterruptedException, TimeoutException {
373                 frequency = in_frequency;
374                 config_data();
375                 set_radio_frequency(frequency,
376                                     config_data.radio_setting != 0,
377                                     config_data.radio_calibration);
378         }
379
380         public void set_telemetry(int in_telemetry) {
381                 telemetry = in_telemetry;
382                 if (altos != null) {
383                         if (monitor_mode)
384                                 printf("m 0\nm %x\n", telemetry_len());
385                         flush_output();
386                 }
387         }
388
389         void set_monitor(boolean monitor) {
390                 monitor_mode = monitor;
391                 if (altos != null) {
392                         if (monitor)
393                                 printf("m %x\n", telemetry_len());
394                         else
395                                 printf("m 0\n");
396                         flush_output();
397                 }
398         }
399
400         public void set_callsign(String callsign) {
401                 if (altos != null) {
402                         printf ("c c %s\n", callsign);
403                         flush_output();
404                 }
405         }
406
407         public AltosConfigData config_data() throws InterruptedException, TimeoutException {
408                 if (config_data == null)
409                         config_data = new AltosConfigData(this);
410                 return config_data;
411         }
412
413         public void start_remote() throws TimeoutException, InterruptedException {
414                 if (debug)
415                         System.out.printf("start remote\n");
416                 if (frequency == 0.0)
417                         frequency = AltosPreferences.frequency(device.getSerial());
418                 set_radio_frequency(frequency);
419                 set_callsign(AltosPreferences.callsign());
420                 printf("p\nE 0\n");
421                 flush_input();
422                 remote = true;
423         }
424
425         public void stop_remote() {
426                 if (debug)
427                         System.out.printf("stop remote\n");
428                 try {
429                         flush_input();
430                 } finally {
431                         printf ("~\n");
432                         flush_output();
433                 }
434                 remote = false;
435         }
436
437         public void set_frame(Frame in_frame) {
438                 frame = in_frame;
439         }
440
441         public AltosSerial(AltosDevice in_device) throws FileNotFoundException, AltosSerialInUseException {
442                 device = in_device;
443                 line = "";
444                 monitor_mode = false;
445                 frame = null;
446                 telemetry = Altos.ao_telemetry_standard;
447                 monitors = new LinkedList<LinkedBlockingQueue<AltosLine>> ();
448                 reply_queue = new LinkedBlockingQueue<AltosLine> ();
449                 open();
450         }
451 }