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