altosui: Clean up packet link connecting dialog
[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.awt.*;
29 import java.awt.event.*;
30 import javax.swing.*;
31 import javax.swing.filechooser.FileNameExtensionFilter;
32 import javax.swing.table.*;
33
34 import libaltosJNI.*;
35
36 /*
37  * This class reads from the serial port and places each received
38  * line in a queue. Dealing with that queue is left up to other
39  * threads.
40  */
41
42 public class AltosSerial implements Runnable {
43
44         static java.util.List<String> devices_opened = Collections.synchronizedList(new LinkedList<String>());
45
46         AltosDevice device;
47         SWIGTYPE_p_altos_file altos;
48         LinkedList<LinkedBlockingQueue<AltosLine>> monitors;
49         LinkedBlockingQueue<AltosLine> reply_queue;
50         Thread input_thread;
51         String line;
52         byte[] line_bytes;
53         int line_count;
54         boolean monitor_mode;
55         int telemetry;
56         int channel;
57         static boolean debug;
58         boolean remote;
59         LinkedList<String> pending_output = new LinkedList<String>();
60         Frame frame;
61
62         static void set_debug(boolean new_debug) {
63                 debug = new_debug;
64         }
65
66         public void run () {
67                 int c;
68
69                 try {
70                         for (;;) {
71                                 c = libaltos.altos_getchar(altos, 0);
72                                 if (Thread.interrupted())
73                                         break;
74                                 if (c == libaltosConstants.LIBALTOS_ERROR) {
75                                         for (int e = 0; e < monitors.size(); e++) {
76                                                 LinkedBlockingQueue<AltosLine> q = monitors.get(e);
77                                                 q.put(new AltosLine());
78                                         }
79                                         reply_queue.put (new AltosLine());
80                                         break;
81                                 }
82                                 if (c == libaltosConstants.LIBALTOS_TIMEOUT)
83                                         continue;
84                                 if (c == '\r')
85                                         continue;
86                                 synchronized(this) {
87                                         if (c == '\n') {
88                                                 if (line_count != 0) {
89                                                         try {
90                                                                 line = new String(line_bytes, 0, line_count, "UTF-8");
91                                                         } catch (UnsupportedEncodingException ue) {
92                                                                 line = "";
93                                                                 for (int i = 0; i < line_count; i++)
94                                                                         line = line + line_bytes[i];
95                                                         }
96                                                         if (debug)
97                                                                 System.out.printf("\t\t\t\t\t%s\n", line);
98                                                         if (line.startsWith("VERSION") || line.startsWith("CRC")) {
99                                                                 for (int e = 0; e < monitors.size(); e++) {
100                                                                         LinkedBlockingQueue<AltosLine> q = monitors.get(e);
101                                                                         q.put(new AltosLine (line));
102                                                                 }
103                                                         } else {
104                                                                 reply_queue.put(new AltosLine (line));
105                                                         }
106                                                         line_count = 0;
107                                                         line = "";
108                                                 }
109                                         } else {
110                                                 if (line_bytes == null) {
111                                                         line_bytes = new byte[256];
112                                                 } else if (line_count == line_bytes.length) {
113                                                         byte[] new_line_bytes = new byte[line_count * 2];
114                                                         System.arraycopy(line_bytes, 0, new_line_bytes, 0, line_count);
115                                                         line_bytes = new_line_bytes;
116                                                 }
117                                                 line_bytes[line_count] = (byte) c;
118                                                 line_count++;
119                                         }
120                                 }
121                         }
122                 } catch (InterruptedException e) {
123                 }
124         }
125
126         public void flush_output() {
127                 if (altos != null) {
128                         for (String s : pending_output)
129                                 System.out.print(s);
130                         pending_output.clear();
131                         libaltos.altos_flush(altos);
132                 }
133         }
134
135         boolean         abort;
136         JDialog         timeout_dialog;
137         boolean timeout_started = false;
138
139         private void stop_timeout_dialog() {
140                 if (timeout_started) {
141                         timeout_started = false;
142                         Runnable r = new Runnable() {
143                                         public void run() {
144                                                 timeout_dialog.setVisible(false);
145                                         }
146                                 };
147                         SwingUtilities.invokeLater(r);
148                 }
149         }
150
151         private void start_timeout_dialog_internal() {
152
153                 Object[] options = { "Cancel" };
154
155                 JOptionPane     pane = new JOptionPane();
156                 pane.setMessage(String.format("Connecting to %s", device.getPath()));
157                 pane.setOptions(options);
158                 pane.setInitialValue(null);
159
160                 timeout_dialog = pane.createDialog(frame, "Connecting...");
161
162                 timeout_dialog.setVisible(true);
163
164                 Object o = pane.getValue();
165                 if (o == null)
166                         return;
167                 if (options[0].equals(o))
168                         abort = true;
169                 timeout_dialog.dispose();
170                 timeout_dialog = null;
171         }
172
173         private boolean check_timeout() {
174                 if (!timeout_started && frame != null) {
175                         if (!SwingUtilities.isEventDispatchThread()) {
176                                 timeout_started = true;
177                                 Runnable r = new Runnable() {
178                                                 public void run() {
179                                                         start_timeout_dialog_internal();
180                                                 }
181                                         };
182                                 SwingUtilities.invokeLater(r);
183                         }
184                 }
185                 return abort;
186         }
187
188         public void flush_input() {
189                 flush_output();
190                 boolean got_some;
191
192                 int timeout = 100;
193                 if (remote)
194                         timeout = 500;
195                 do {
196                         try {
197                                 Thread.sleep(timeout);
198                         } catch (InterruptedException ie) {
199                         }
200                         got_some = !reply_queue.isEmpty();
201                         synchronized(this) {
202                                 if (!"VERSION".startsWith(line) &&
203                                     !line.startsWith("VERSION"))
204                                         line = "";
205                                 reply_queue.clear();
206                         }
207                 } while (got_some);
208         }
209
210         public String get_reply() throws InterruptedException {
211                 if (SwingUtilities.isEventDispatchThread())
212                         System.out.printf("Uh-oh, reading serial device from swing thread\n");
213                 flush_output();
214                 AltosLine line = reply_queue.take();
215                 return line.line;
216         }
217
218         int     in_reply;
219
220         public String get_reply(int timeout) throws InterruptedException {
221                 boolean can_cancel = true;
222                 ++in_reply;
223
224                 if (SwingUtilities.isEventDispatchThread()) {
225                         can_cancel = false;
226                         System.out.printf("Uh-oh, reading serial device from swing thread\n");
227                 }
228                 flush_output();
229                 if (remote && can_cancel) {
230                         timeout = 500;
231                 }
232                 abort = false;
233                 timeout_started = false;
234                 for (;;) {
235                         AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
236                         if (line != null) {
237                                 stop_timeout_dialog();
238                                 --in_reply;
239                                 return line.line;
240                         }
241                         if (!remote || !can_cancel || check_timeout()) {
242                                 --in_reply;
243                                 return null;
244                         }
245                 }
246         }
247
248         public void add_monitor(LinkedBlockingQueue<AltosLine> q) {
249                 set_monitor(true);
250                 monitors.add(q);
251         }
252
253         public void remove_monitor(LinkedBlockingQueue<AltosLine> q) {
254                 monitors.remove(q);
255                 if (monitors.isEmpty())
256                         set_monitor(false);
257         }
258
259         public void close() {
260                 if (in_reply != 0)
261                         System.out.printf("Uh-oh. Closing active serial device\n");
262
263                 if (altos != null) {
264                         libaltos.altos_close(altos);
265                 }
266                 if (input_thread != null) {
267                         try {
268                                 input_thread.interrupt();
269                                 input_thread.join();
270                         } catch (InterruptedException e) {
271                         }
272                         input_thread = null;
273                 }
274                 if (altos != null) {
275                         libaltos.altos_free(altos);
276                         altos = null;
277                 }
278                 synchronized (devices_opened) {
279                         devices_opened.remove(device.getPath());
280                 }
281                 if (debug)
282                         System.out.printf("Closing %s\n", device.getPath());
283         }
284
285         private void putc(char c) {
286                 if (altos != null)
287                         libaltos.altos_putchar(altos, c);
288         }
289
290         public void print(String data) {
291                 if (debug)
292                         pending_output.add(data);
293                 for (int i = 0; i < data.length(); i++)
294                         putc(data.charAt(i));
295         }
296
297         public void printf(String format, Object ... arguments) {
298                 print(String.format(format, arguments));
299         }
300
301         private void open() throws FileNotFoundException, AltosSerialInUseException {
302                 synchronized (devices_opened) {
303                         if (devices_opened.contains(device.getPath()))
304                                 throw new AltosSerialInUseException(device);
305                         devices_opened.add(device.getPath());
306                 }
307                 altos = libaltos.altos_open(device);
308                 if (altos == null) {
309                         close();
310                         throw new FileNotFoundException(device.toShortString());
311                 }
312                 if (debug)
313                         System.out.printf("Open %s\n", device.getPath());
314                 input_thread = new Thread(this);
315                 input_thread.start();
316                 print("~\nE 0\n");
317                 set_monitor(false);
318                 flush_output();
319         }
320
321         public void set_radio() {
322                 telemetry = AltosPreferences.telemetry(device.getSerial());
323                 channel = AltosPreferences.channel(device.getSerial());
324                 set_channel(channel);
325                 set_callsign(AltosPreferences.callsign());
326         }
327
328         public void set_channel(int in_channel) {
329                 channel = in_channel;
330                 if (altos != null) {
331                         if (monitor_mode)
332                                 printf("m 0\nc r %d\nm %d\n", channel, telemetry);
333                         else
334                                 printf("c r %d\n", channel);
335                         flush_output();
336                 }
337         }
338
339         public void set_telemetry(int in_telemetry) {
340                 telemetry = in_telemetry;
341                 if (altos != null) {
342                         if (monitor_mode)
343                                 printf("m 0\nm %d\n", telemetry);
344                         flush_output();
345                 }
346         }
347
348         void set_monitor(boolean monitor) {
349                 monitor_mode = monitor;
350                 if (altos != null) {
351                         if (monitor)
352                                 printf("m %d\n", telemetry);
353                         else
354                                 printf("m 0\n");
355                         flush_output();
356                 }
357         }
358
359         public void set_callsign(String callsign) {
360                 if (altos != null) {
361                         printf ("c c %s\n", callsign);
362                         flush_output();
363                 }
364         }
365
366         public void start_remote() {
367                 if (debug)
368                         System.out.printf("start remote\n");
369                 set_radio();
370                 printf("p\nE 0\n");
371                 flush_input();
372                 remote = true;
373         }
374
375         public void stop_remote() {
376                 if (debug)
377                         System.out.printf("stop remote\n");
378                 try {
379                         flush_input();
380                 } finally {
381                         printf ("~\n");
382                         flush_output();
383                 }
384                 remote = false;
385         }
386
387         public void set_frame(Frame in_frame) {
388                 frame = in_frame;
389         }
390
391         public AltosSerial(AltosDevice in_device) throws FileNotFoundException, AltosSerialInUseException {
392                 device = in_device;
393                 line = "";
394                 monitor_mode = false;
395                 frame = null;
396                 telemetry = Altos.ao_telemetry_full;
397                 monitors = new LinkedList<LinkedBlockingQueue<AltosLine>> ();
398                 reply_queue = new LinkedBlockingQueue<AltosLine> ();
399                 open();
400         }
401 }