cb82a574ed4381d5c87862f2d9de23757dad5afb
[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         int channel;
58         static boolean debug;
59         boolean remote;
60         LinkedList<String> pending_output = new LinkedList<String>();
61         Frame frame;
62
63         static void set_debug(boolean new_debug) {
64                 debug = new_debug;
65         }
66
67         public void run () {
68                 int c;
69
70                 try {
71                         for (;;) {
72                                 c = libaltos.altos_getchar(altos, 0);
73                                 if (Thread.interrupted())
74                                         break;
75                                 if (c == libaltosConstants.LIBALTOS_ERROR) {
76                                         for (int e = 0; e < monitors.size(); e++) {
77                                                 LinkedBlockingQueue<AltosLine> q = monitors.get(e);
78                                                 q.put(new AltosLine());
79                                         }
80                                         reply_queue.put (new AltosLine());
81                                         break;
82                                 }
83                                 if (c == libaltosConstants.LIBALTOS_TIMEOUT)
84                                         continue;
85                                 if (c == '\r')
86                                         continue;
87                                 synchronized(this) {
88                                         if (c == '\n') {
89                                                 if (line_count != 0) {
90                                                         try {
91                                                                 line = new String(line_bytes, 0, line_count, "UTF-8");
92                                                         } catch (UnsupportedEncodingException ue) {
93                                                                 line = "";
94                                                                 for (int i = 0; i < line_count; i++)
95                                                                         line = line + line_bytes[i];
96                                                         }
97                                                         if (debug)
98                                                                 System.out.printf("\t\t\t\t\t%s\n", line);
99                                                         if (line.startsWith("TELEM") || line.startsWith("VERSION") || line.startsWith("CRC")) {
100                                                                 for (int e = 0; e < monitors.size(); e++) {
101                                                                         LinkedBlockingQueue<AltosLine> q = monitors.get(e);
102                                                                         q.put(new AltosLine (line));
103                                                                 }
104                                                         } else {
105                                                                 reply_queue.put(new AltosLine (line));
106                                                         }
107                                                         line_count = 0;
108                                                         line = "";
109                                                 }
110                                         } else {
111                                                 if (line_bytes == null) {
112                                                         line_bytes = new byte[256];
113                                                 } else if (line_count == line_bytes.length) {
114                                                         byte[] new_line_bytes = new byte[line_count * 2];
115                                                         System.arraycopy(line_bytes, 0, new_line_bytes, 0, line_count);
116                                                         line_bytes = new_line_bytes;
117                                                 }
118                                                 line_bytes[line_count] = (byte) c;
119                                                 line_count++;
120                                         }
121                                 }
122                         }
123                 } catch (InterruptedException e) {
124                 }
125         }
126
127         public void flush_output() {
128                 if (altos != null) {
129                         for (String s : pending_output)
130                                 System.out.print(s);
131                         pending_output.clear();
132                         libaltos.altos_flush(altos);
133                 }
134         }
135
136         boolean         abort;
137         JDialog         timeout_dialog;
138         boolean timeout_started = false;
139
140         private void stop_timeout_dialog() {
141                 if (timeout_started) {
142                         timeout_started = false;
143                         Runnable r = new Runnable() {
144                                         public void run() {
145                                                 timeout_dialog.setVisible(false);
146                                         }
147                                 };
148                         SwingUtilities.invokeLater(r);
149                 }
150         }
151
152         private void start_timeout_dialog_internal() {
153
154                 Object[] options = { "Cancel" };
155
156                 JOptionPane     pane = new JOptionPane();
157                 pane.setMessage(String.format("Connecting to %s", device.getPath()));
158                 pane.setOptions(options);
159                 pane.setInitialValue(null);
160
161                 timeout_dialog = pane.createDialog(frame, "Connecting...");
162
163                 timeout_dialog.setVisible(true);
164
165                 Object o = pane.getValue();
166                 if (o == null)
167                         return;
168                 if (options[0].equals(o))
169                         abort = true;
170                 timeout_dialog.dispose();
171                 timeout_dialog = null;
172         }
173
174         private boolean check_timeout() {
175                 if (!timeout_started && frame != null) {
176                         if (!SwingUtilities.isEventDispatchThread()) {
177                                 timeout_started = true;
178                                 Runnable r = new Runnable() {
179                                                 public void run() {
180                                                         start_timeout_dialog_internal();
181                                                 }
182                                         };
183                                 SwingUtilities.invokeLater(r);
184                         }
185                 }
186                 return abort;
187         }
188
189         public void flush_input() {
190                 flush_output();
191                 boolean got_some;
192
193                 int timeout = 100;
194                 if (remote)
195                         timeout = 500;
196                 do {
197                         try {
198                                 Thread.sleep(timeout);
199                         } catch (InterruptedException ie) {
200                         }
201                         got_some = !reply_queue.isEmpty();
202                         synchronized(this) {
203                                 if (!"VERSION".startsWith(line) &&
204                                     !line.startsWith("VERSION"))
205                                         line = "";
206                                 reply_queue.clear();
207                         }
208                 } while (got_some);
209         }
210
211         public String get_reply() throws InterruptedException {
212                 if (SwingUtilities.isEventDispatchThread())
213                         System.out.printf("Uh-oh, reading serial device from swing thread\n");
214                 flush_output();
215                 AltosLine line = reply_queue.take();
216                 return line.line;
217         }
218
219         int     in_reply;
220
221         public String get_reply(int timeout) throws InterruptedException {
222                 boolean can_cancel = true;
223                 ++in_reply;
224
225                 if (SwingUtilities.isEventDispatchThread()) {
226                         can_cancel = false;
227                         System.out.printf("Uh-oh, reading serial device from swing thread\n");
228                 }
229                 flush_output();
230                 if (remote && can_cancel) {
231                         timeout = 500;
232                 }
233                 abort = false;
234                 timeout_started = false;
235                 for (;;) {
236                         System.out.printf("timeout %d\n", timeout);
237                         AltosLine line = reply_queue.poll(timeout, TimeUnit.MILLISECONDS);
238                         if (line != null) {
239                                 stop_timeout_dialog();
240                                 --in_reply;
241                                 return line.line;
242                         }
243                         System.out.printf("no line remote %b can_cancel %b\n", remote, can_cancel);
244                         if (!remote || !can_cancel || check_timeout()) {
245                                 --in_reply;
246                                 return null;
247                         }
248                 }
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 (in_reply != 0)
272                         System.out.printf("Uh-oh. Closing active serial device\n");
273
274                 if (altos != null) {
275                         libaltos.altos_close(altos);
276                 }
277                 if (input_thread != null) {
278                         try {
279                                 input_thread.interrupt();
280                                 input_thread.join();
281                         } catch (InterruptedException e) {
282                         }
283                         input_thread = null;
284                 }
285                 if (altos != null) {
286                         libaltos.altos_free(altos);
287                         altos = null;
288                 }
289                 synchronized (devices_opened) {
290                         devices_opened.remove(device.getPath());
291                 }
292                 if (debug)
293                         System.out.printf("Closing %s\n", device.getPath());
294         }
295
296         private void putc(char c) {
297                 if (altos != null)
298                         libaltos.altos_putchar(altos, c);
299         }
300
301         public void print(String data) {
302                 if (debug)
303                         pending_output.add(data);
304                 for (int i = 0; i < data.length(); i++)
305                         putc(data.charAt(i));
306         }
307
308         public void printf(String format, Object ... arguments) {
309                 print(String.format(format, arguments));
310         }
311
312         private void open() throws FileNotFoundException, AltosSerialInUseException {
313                 synchronized (devices_opened) {
314                         if (devices_opened.contains(device.getPath()))
315                                 throw new AltosSerialInUseException(device);
316                         devices_opened.add(device.getPath());
317                 }
318                 altos = device.open();
319                 if (altos == null) {
320                         close();
321                         throw new FileNotFoundException(device.toShortString());
322                 }
323                 if (debug)
324                         System.out.printf("Open %s\n", device.getPath());
325                 input_thread = new Thread(this);
326                 input_thread.start();
327                 print("~\nE 0\n");
328                 set_monitor(false);
329                 flush_output();
330         }
331
332         public void set_radio() {
333                 telemetry = AltosPreferences.telemetry(device.getSerial());
334                 channel = AltosPreferences.channel(device.getSerial());
335                 set_channel(channel);
336                 set_callsign(AltosPreferences.callsign());
337         }
338
339         private int telemetry_len() {
340                 return Altos.telemetry_len(telemetry);
341         }
342
343         public void set_channel(int in_channel) {
344                 channel = in_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         public void set_telemetry(int in_telemetry) {
356                 telemetry = in_telemetry;
357                 if (altos != null) {
358                         if (monitor_mode)
359                                 printf("m 0\nm %x\n", telemetry_len());
360                         flush_output();
361                 }
362         }
363
364         void set_monitor(boolean monitor) {
365                 monitor_mode = monitor;
366                 if (altos != null) {
367                         if (monitor)
368                                 printf("m %x\n", telemetry_len());
369                         else
370                                 printf("m 0\n");
371                         flush_output();
372                 }
373         }
374
375         public void set_callsign(String callsign) {
376                 if (altos != null) {
377                         printf ("c c %s\n", callsign);
378                         flush_output();
379                 }
380         }
381
382         public void start_remote() {
383                 if (debug)
384                         System.out.printf("start remote\n");
385                 set_radio();
386                 printf("p\nE 0\n");
387                 flush_input();
388                 remote = true;
389         }
390
391         public void stop_remote() {
392                 if (debug)
393                         System.out.printf("stop remote\n");
394                 try {
395                         flush_input();
396                 } finally {
397                         printf ("~\n");
398                         flush_output();
399                 }
400                 remote = false;
401         }
402
403         public void set_frame(Frame in_frame) {
404                 frame = in_frame;
405         }
406
407         public AltosSerial(AltosDevice in_device) throws FileNotFoundException, AltosSerialInUseException {
408                 device = in_device;
409                 line = "";
410                 monitor_mode = false;
411                 frame = null;
412                 telemetry = Altos.ao_telemetry_standard;
413                 monitors = new LinkedList<LinkedBlockingQueue<AltosLine>> ();
414                 reply_queue = new LinkedBlockingQueue<AltosLine> ();
415                 open();
416         }
417 }