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