altos: Support staging by going back to boost as needed
[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() throws InterruptedException {
191                 flush_output();
192                 boolean got_some;
193
194                 int timeout = 100;
195                 if (remote)
196                         timeout = 500;
197                 do {
198                         Thread.sleep(timeout);
199                         got_some = !reply_queue.isEmpty();
200                         synchronized(this) {
201                                 if (!"VERSION".startsWith(line) &&
202                                     !line.startsWith("VERSION"))
203                                         line = "";
204                                 reply_queue.clear();
205                         }
206                 } while (got_some);
207         }
208
209         int     in_reply;
210
211         public String get_reply(int timeout) throws InterruptedException {
212                 boolean can_cancel = true;
213                 String  reply = null;
214
215                 try {
216                         ++in_reply;
217
218                         if (SwingUtilities.isEventDispatchThread()) {
219                                 can_cancel = false;
220                                 if (remote)
221                                         System.out.printf("Uh-oh, reading remote serial device from swing thread\n");
222                         }
223                         flush_output();
224                         if (remote && can_cancel) {
225                                 timeout = 500;
226                         }
227                         abort = false;
228                         timeout_started = false;
229                         for (;;) {
230                                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
231                                 if (line != null) {
232                                         stop_timeout_dialog();
233                                         reply = line.line;
234                                         break;
235                                 }
236                                 if (!remote || !can_cancel || check_timeout()) {
237                                         reply = null;
238                                         break;
239                                 }
240                         }
241                 } finally {
242                         --in_reply;
243                 }
244                 return reply;
245         }
246
247         public String get_reply() throws InterruptedException {
248                 return get_reply(5000);
249         }
250
251         public String get_reply_no_dialog(int timeout) throws InterruptedException, TimeoutException {
252                 flush_output();
253                 AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
254                 if (line != null)
255                         return line.line;
256                 return null;
257         }
258
259         public void add_monitor(LinkedBlockingQueue<AltosLine> q) {
260                 set_monitor(true);
261                 monitors.add(q);
262         }
263
264         public void remove_monitor(LinkedBlockingQueue<AltosLine> q) {
265                 monitors.remove(q);
266                 if (monitors.isEmpty())
267                         set_monitor(false);
268         }
269
270         public void close() {
271                 if (remote) {
272                         try {
273                                 stop_remote();
274                         } catch (InterruptedException ie) {
275                         }
276                 }
277                 if (in_reply != 0)
278                         System.out.printf("Uh-oh. Closing active serial device\n");
279
280                 if (altos != null) {
281                         libaltos.altos_close(altos);
282                 }
283                 if (input_thread != null) {
284                         try {
285                                 input_thread.interrupt();
286                                 input_thread.join();
287                         } catch (InterruptedException e) {
288                         }
289                         input_thread = null;
290                 }
291                 if (altos != null) {
292                         libaltos.altos_free(altos);
293                         altos = null;
294                 }
295                 synchronized (devices_opened) {
296                         devices_opened.remove(device.getPath());
297                 }
298                 if (debug)
299                         System.out.printf("Closing %s\n", device.getPath());
300         }
301
302         private void putc(char c) {
303                 if (altos != null)
304                         libaltos.altos_putchar(altos, c);
305         }
306
307         public void print(String data) {
308                 if (debug)
309                         pending_output.add(data);
310                 for (int i = 0; i < data.length(); i++)
311                         putc(data.charAt(i));
312         }
313
314         public void printf(String format, Object ... arguments) {
315                 print(String.format(format, arguments));
316         }
317
318         private void open() throws FileNotFoundException, AltosSerialInUseException {
319                 synchronized (devices_opened) {
320                         if (devices_opened.contains(device.getPath()))
321                                 throw new AltosSerialInUseException(device);
322                         devices_opened.add(device.getPath());
323                 }
324                 altos = device.open();
325                 if (altos == null) {
326                         final String    message = device.getErrorString();
327                         close();
328                         throw new FileNotFoundException(String.format("%s (%s)",
329                                                                       device.toShortString(), message));
330                 }
331                 if (debug)
332                         System.out.printf("Open %s\n", device.getPath());
333                 input_thread = new Thread(this);
334                 input_thread.start();
335                 print("~\nE 0\n");
336                 set_monitor(false);
337                 flush_output();
338         }
339
340         private int telemetry_len() {
341                 return Altos.telemetry_len(telemetry);
342         }
343
344         private void set_channel(int channel) {
345                 if (altos != null) {
346                         if (monitor_mode)
347                                 printf("m 0\nc r %d\nm %x\n",
348                                        channel, telemetry_len());
349                         else
350                                 printf("c r %d\n", channel);
351                         flush_output();
352                 }
353         }
354
355         private void set_radio_setting(int setting) {
356                 if (altos != null) {
357                         if (monitor_mode)
358                                 printf("m 0\nc R %d\nm %x\n",
359                                        setting, telemetry_len());
360                         else
361                                 printf("c R %d\n", setting);
362                         flush_output();
363                 }
364         }
365
366         public void set_radio_frequency(double frequency,
367                                         boolean has_setting,
368                                         int cal) {
369                 if (debug)
370                         System.out.printf("set_radio_frequency %7.3f %b %d\n", frequency, has_setting, cal);
371                 if (has_setting)
372                         set_radio_setting(AltosConvert.radio_frequency_to_setting(frequency, cal));
373                 else
374                         set_channel(AltosConvert.radio_frequency_to_channel(frequency));
375         }
376
377         public void set_radio_frequency(double in_frequency) throws InterruptedException, TimeoutException {
378                 frequency = in_frequency;
379                 config_data();
380                 set_radio_frequency(frequency,
381                                     config_data.radio_setting != 0,
382                                     config_data.radio_calibration);
383         }
384
385         public void set_telemetry(int in_telemetry) {
386                 telemetry = in_telemetry;
387                 if (altos != null) {
388                         if (monitor_mode)
389                                 printf("m 0\nm %x\n", telemetry_len());
390                         flush_output();
391                 }
392         }
393
394         void set_monitor(boolean monitor) {
395                 monitor_mode = monitor;
396                 if (altos != null) {
397                         if (monitor)
398                                 printf("m %x\n", telemetry_len());
399                         else
400                                 printf("m 0\n");
401                         flush_output();
402                 }
403         }
404
405         public void set_callsign(String callsign) {
406                 if (altos != null) {
407                         printf ("c c %s\n", callsign);
408                         flush_output();
409                 }
410         }
411
412         public AltosConfigData config_data() throws InterruptedException, TimeoutException {
413                 if (config_data == null)
414                         config_data = new AltosConfigData(this);
415                 return config_data;
416         }
417
418         public void start_remote() throws TimeoutException, InterruptedException {
419                 if (debug)
420                         System.out.printf("start remote %7.3f\n", frequency);
421                 if (frequency == 0.0)
422                         frequency = AltosPreferences.frequency(device.getSerial());
423                 set_radio_frequency(frequency);
424                 set_callsign(AltosPreferences.callsign());
425                 printf("p\nE 0\n");
426                 flush_input();
427                 remote = true;
428         }
429
430         public void stop_remote() throws InterruptedException {
431                 if (debug)
432                         System.out.printf("stop remote\n");
433                 try {
434                         flush_input();
435                 } finally {
436                         printf ("~\n");
437                         flush_output();
438                 }
439                 remote = false;
440         }
441
442         public void set_frame(Frame in_frame) {
443                 frame = in_frame;
444         }
445
446         public AltosSerial(AltosDevice in_device) throws FileNotFoundException, AltosSerialInUseException {
447                 device = in_device;
448                 line = "";
449                 monitor_mode = false;
450                 frame = null;
451                 telemetry = Altos.ao_telemetry_standard;
452                 monitors = new LinkedList<LinkedBlockingQueue<AltosLine>> ();
453                 reply_queue = new LinkedBlockingQueue<AltosLine> ();
454                 open();
455         }
456 }