altosui: Report error message back from libaltos
[fw/altos] / altosui / AltosScanUI.java
1 /*
2  * Copyright © 2011 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 package altosui;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import javax.swing.filechooser.FileNameExtensionFilter;
24 import javax.swing.table.*;
25 import javax.swing.event.*;
26 import java.io.*;
27 import java.util.*;
28 import java.text.*;
29 import java.util.prefs.*;
30 import java.util.concurrent.*;
31
32 class AltosScanResult {
33         String          callsign;
34         int             serial;
35         int             flight;
36         AltosFrequency  frequency;
37         int             telemetry;
38         
39         boolean interrupted = false;
40         
41         public String toString() {
42                 return String.format("%-9.9s serial %-4d flight %-4d (%s %s)",
43                                      callsign, serial, flight, frequency.toShortString(), Altos.telemetry_name(telemetry));
44         }
45
46         public String toShortString() {
47                 return String.format("%s %d %d %7.3f %d",
48                                      callsign, serial, flight, frequency, telemetry);
49         }
50
51         public AltosScanResult(String in_callsign, int in_serial,
52                                int in_flight, AltosFrequency in_frequency, int in_telemetry) {
53                 callsign = in_callsign;
54                 serial = in_serial;
55                 flight = in_flight;
56                 frequency = in_frequency;
57                 telemetry = in_telemetry;
58         }
59
60         public boolean equals(AltosScanResult other) {
61                 return (callsign.equals(other.callsign) &&
62                         serial == other.serial &&
63                         flight == other.flight &&
64                         frequency.frequency == other.frequency.frequency &&
65                         telemetry == other.telemetry);
66         }
67 }
68
69 class AltosScanResults extends LinkedList<AltosScanResult> implements ListModel {
70         
71         LinkedList<ListDataListener>    listeners = new LinkedList<ListDataListener>();
72
73         public boolean add(AltosScanResult r) {
74                 for (AltosScanResult old : this)
75                         if (old.equals(r))
76                                 return true;
77
78                 super.add(r);
79                 ListDataEvent   de = new ListDataEvent(this,
80                                                        ListDataEvent.INTERVAL_ADDED,
81                                                        this.size() - 2, this.size() - 1);
82                 for (ListDataListener l : listeners)
83                         l.contentsChanged(de);
84                 return true;
85         }
86
87         public void addListDataListener(ListDataListener l) {
88                 listeners.add(l);
89         }
90         
91         public void removeListDataListener(ListDataListener l) {
92                 listeners.remove(l);
93         }
94
95         public AltosScanResult getElementAt(int i) {
96                 return this.get(i);
97         }
98
99         public int getSize() {
100                 return this.size();
101         }
102 }
103
104 public class AltosScanUI
105         extends JDialog
106         implements ActionListener
107 {
108         AltosUI                         owner;
109         AltosDevice                     device;
110         AltosConfigData                 config_data;
111         AltosTelemetryReader            reader;
112         private JList                   list;
113         private JLabel                  scanning_label;
114         private JLabel                  frequency_label;
115         private JLabel                  telemetry_label;
116         private JButton                 cancel_button;
117         private JButton                 monitor_button;
118         private JCheckBox[]             telemetry_boxes;
119         javax.swing.Timer               timer;
120         AltosScanResults                results = new AltosScanResults();
121
122         int                             telemetry;
123
124         final static int                timeout = 1200;
125         TelemetryHandler                handler;
126         Thread                          thread;
127         AltosFrequency[]                frequencies;
128         int                             frequency_index;
129
130         void scan_exception(Exception e) {
131                 if (e instanceof FileNotFoundException) {
132                         JOptionPane.showMessageDialog(owner,
133                                                       ((FileNotFoundException) e).getMessage(),
134                                                       "Cannot open target device",
135                                                       JOptionPane.ERROR_MESSAGE);
136                 } else if (e instanceof AltosSerialInUseException) {
137                         JOptionPane.showMessageDialog(owner,
138                                                       String.format("Device \"%s\" already in use",
139                                                                     device.toShortString()),
140                                                       "Device in use",
141                                                       JOptionPane.ERROR_MESSAGE);
142                 } else if (e instanceof IOException) {
143                         IOException ee = (IOException) e;
144                         JOptionPane.showMessageDialog(owner,
145                                                       device.toShortString(),
146                                                       ee.getLocalizedMessage(),
147                                                       JOptionPane.ERROR_MESSAGE);
148                 } else {
149                         JOptionPane.showMessageDialog(owner,
150                                                       String.format("Connection to \"%s\" failed",
151                                                                     device.toShortString()),
152                                                       "Connection Failed",
153                                                       JOptionPane.ERROR_MESSAGE);
154                 }
155                 close();
156         }
157
158         class TelemetryHandler implements Runnable {
159
160                 public void run() {
161
162                         boolean interrupted = false;
163
164                         try {
165                                 for (;;) {
166                                         try {
167                                                 AltosRecord     record = reader.read();
168                                                 if (record == null)
169                                                         continue;
170                                                 if ((record.seen & AltosRecord.seen_flight) != 0) {
171                                                         final AltosScanResult   result = new AltosScanResult(record.callsign,
172                                                                                                      record.serial,
173                                                                                                      record.flight,
174                                                                                                      frequencies[frequency_index],
175                                                                                                      telemetry);
176                                                         Runnable r = new Runnable() {
177                                                                         public void run() {
178                                                                                 results.add(result);
179                                                                         }
180                                                                 };
181                                                         SwingUtilities.invokeLater(r);
182                                                 }
183                                         } catch (ParseException pp) {
184                                         } catch (AltosCRCException ce) {
185                                         }
186                                 }
187                         } catch (InterruptedException ee) {
188                                 interrupted = true;
189                         } catch (IOException ie) {
190                         } finally {
191                                 reader.close(interrupted);
192                         }
193                 }
194         }
195
196         void set_label() {
197                 frequency_label.setText(String.format("Frequency: %s", frequencies[frequency_index].toString()));
198                 telemetry_label.setText(String.format("Telemetry: %s", Altos.telemetry_name(telemetry)));
199         }
200
201         void set_telemetry() {
202                 reader.set_telemetry(telemetry);
203         }
204         
205         void set_frequency() throws InterruptedException, TimeoutException {
206                 reader.set_frequency(frequencies[frequency_index].frequency);
207         }
208         
209         void next() throws InterruptedException, TimeoutException {
210                 reader.serial.set_monitor(false);
211                 Thread.sleep(100);
212                 ++frequency_index;
213                 if (frequency_index >= frequencies.length ||
214                     !telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected())
215                 {
216                         frequency_index = 0;
217                         do {
218                                 ++telemetry;
219                                 if (telemetry > Altos.ao_telemetry_max)
220                                         telemetry = Altos.ao_telemetry_min;
221                         } while (!telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected());
222                         set_telemetry();
223                 }
224                 set_frequency();
225                 set_label();
226                 reader.serial.set_monitor(true);
227         }
228
229
230         void close() {
231                 if (thread != null && thread.isAlive()) {
232                         thread.interrupt();
233                         try {
234                                 thread.join();
235                         } catch (InterruptedException ie) {}
236                 }
237                 thread = null;
238                 if (timer != null)
239                         timer.stop();
240                 setVisible(false);
241                 dispose();
242         }
243
244         void tick_timer() throws InterruptedException, TimeoutException {
245                 next();
246         }
247
248         public void actionPerformed(ActionEvent e) {
249                 String cmd = e.getActionCommand();
250
251                 try {
252                         if (cmd.equals("cancel"))
253                                 close();
254
255                         if (cmd.equals("tick"))
256                                 tick_timer();
257
258                         if (cmd.equals("telemetry")) {
259                                 int k;
260                                 int scanning_telemetry = 0;
261                                 for (k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
262                                         int j = k - Altos.ao_telemetry_min;
263                                         if (telemetry_boxes[j].isSelected())
264                                                 scanning_telemetry |= (1 << k);
265                                 }
266                                 if (scanning_telemetry == 0) {
267                                         scanning_telemetry |= (1 << Altos.ao_telemetry_standard);
268                                         telemetry_boxes[Altos.ao_telemetry_standard - Altos.ao_telemetry_min].setSelected(true);
269                                 }
270                                 AltosPreferences.set_scanning_telemetry(scanning_telemetry);
271                         }
272
273                         if (cmd.equals("monitor")) {
274                                 close();
275                                 AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
276                                 if (r != null) {
277                                         if (device != null) {
278                                                 if (reader != null) {
279                                                         reader.set_telemetry(r.telemetry);
280                                                         reader.set_frequency(r.frequency.frequency);
281                                                         reader.save_frequency();
282                                                         owner.telemetry_window(device);
283                                                 }
284                                         }
285                                 }
286                         }
287                 } catch (TimeoutException te) {
288                         close();
289                 } catch (InterruptedException ie) {
290                         close();
291                 }
292         }
293
294         /* A window listener to catch closing events and tell the config code */
295         class ConfigListener extends WindowAdapter {
296                 AltosScanUI     ui;
297
298                 public ConfigListener(AltosScanUI this_ui) {
299                         ui = this_ui;
300                 }
301
302                 public void windowClosing(WindowEvent e) {
303                         ui.actionPerformed(new ActionEvent(e.getSource(),
304                                                            ActionEvent.ACTION_PERFORMED,
305                                                            "close"));
306                 }
307         }
308
309         private boolean open() {
310                 device = AltosDeviceDialog.show(owner, Altos.product_basestation);
311                 if (device == null)
312                         return false;
313                 try {
314                         reader = new AltosTelemetryReader(device);
315                         set_frequency();
316                         set_telemetry();
317                         try {
318                                 Thread.sleep(100);
319                         } catch (InterruptedException ie) {
320                         }
321                         reader.flush();
322                         handler = new TelemetryHandler();
323                         thread = new Thread(handler);
324                         thread.start();
325                         return true;
326                 } catch (FileNotFoundException ee) {
327                         JOptionPane.showMessageDialog(owner,
328                                                       ee.getMessage(),
329                                                       "Cannot open target device",
330                                                       JOptionPane.ERROR_MESSAGE);
331                 } catch (AltosSerialInUseException si) {
332                         JOptionPane.showMessageDialog(owner,
333                                                       String.format("Device \"%s\" already in use",
334                                                                     device.toShortString()),
335                                                       "Device in use",
336                                                       JOptionPane.ERROR_MESSAGE);
337                 } catch (IOException ee) {
338                         JOptionPane.showMessageDialog(owner,
339                                                       device.toShortString(),
340                                                       "Unkonwn I/O error",
341                                                       JOptionPane.ERROR_MESSAGE);
342                 } catch (TimeoutException te) {
343                         JOptionPane.showMessageDialog(owner,
344                                                       device.toShortString(),
345                                                       "Timeout error",
346                                                       JOptionPane.ERROR_MESSAGE);
347                 } catch (InterruptedException ie) {
348                         JOptionPane.showMessageDialog(owner,
349                                                       device.toShortString(),
350                                                       "Interrupted exception",
351                                                       JOptionPane.ERROR_MESSAGE);
352                 }
353                 if (reader != null)
354                         reader.close(false);
355                 return false;
356         }
357
358         public AltosScanUI(AltosUI in_owner) {
359
360                 owner = in_owner;
361
362                 frequencies = AltosPreferences.common_frequencies();
363                 frequency_index = 0;
364                 telemetry = Altos.ao_telemetry_min;
365
366                 if (!open())
367                         return;
368
369                 Container               pane = getContentPane();
370                 GridBagConstraints      c = new GridBagConstraints();
371                 Insets                  i = new Insets(4,4,4,4);
372
373                 timer = new javax.swing.Timer(timeout, this);
374                 timer.setActionCommand("tick");
375                 timer.restart();
376
377                 owner = in_owner;
378
379                 pane.setLayout(new GridBagLayout());
380
381                 scanning_label = new JLabel("Scanning:");
382                 frequency_label = new JLabel("");
383                 telemetry_label = new JLabel("");
384                 
385                 set_label();
386
387                 c.fill = GridBagConstraints.HORIZONTAL;
388                 c.anchor = GridBagConstraints.WEST;
389                 c.insets = i;
390                 c.weightx = 1;
391                 c.weighty = 1;
392
393                 c.gridx = 0;
394                 c.gridy = 0;
395                 c.gridwidth = 2;
396
397                 pane.add(scanning_label, c);
398                 c.gridy = 1;
399                 pane.add(frequency_label, c);
400                 c.gridy = 2;
401                 pane.add(telemetry_label, c);
402
403                 int     scanning_telemetry = AltosPreferences.scanning_telemetry();
404                 telemetry_boxes = new JCheckBox[Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1];
405                 for (int k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
406                         int j = k - Altos.ao_telemetry_min;
407                         telemetry_boxes[j] = new JCheckBox(Altos.ao_telemetry_name[k]);
408                         c.gridy = 3 + j;
409                         pane.add(telemetry_boxes[j], c);
410                         telemetry_boxes[j].setActionCommand("telemetry");
411                         telemetry_boxes[j].addActionListener(this);
412                         telemetry_boxes[j].setSelected((scanning_telemetry & (1 << k)) != 0);
413                 }
414
415                 int     y_offset = 3 + (Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1);
416                                 
417                 list = new JList(results) {
418                                 //Subclass JList to workaround bug 4832765, which can cause the
419                                 //scroll pane to not let the user easily scroll up to the beginning
420                                 //of the list.  An alternative would be to set the unitIncrement
421                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
422                                 //aligned scrolling, but it should work.
423                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
424                                                                       int orientation,
425                                                                       int direction) {
426                                         int row;
427                                         if (orientation == SwingConstants.VERTICAL &&
428                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
429                                                 Rectangle r = getCellBounds(row, row);
430                                                 if ((r.y == visibleRect.y) && (row != 0))  {
431                                                         Point loc = r.getLocation();
432                                                         loc.y--;
433                                                         int prevIndex = locationToIndex(loc);
434                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
435
436                                                         if (prevR == null || prevR.y >= r.y) {
437                                                                 return 0;
438                                                         }
439                                                         return prevR.height;
440                                                 }
441                                         }
442                                         return super.getScrollableUnitIncrement(
443                                                 visibleRect, orientation, direction);
444                                 }
445                         };
446
447                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
448                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
449                 list.setVisibleRowCount(-1);
450
451                 list.addMouseListener(new MouseAdapter() {
452                                  public void mouseClicked(MouseEvent e) {
453                                          if (e.getClickCount() == 2) {
454                                                  monitor_button.doClick(); //emulate button click
455                                          }
456                                  }
457                         });
458                 JScrollPane listScroller = new JScrollPane(list);
459                 listScroller.setPreferredSize(new Dimension(400, 80));
460                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
461
462                 //Create a container so that we can add a title around
463                 //the scroll pane.  Can't add a title directly to the
464                 //scroll pane because its background would be white.
465                 //Lay out the label and scroll pane from top to bottom.
466                 JPanel listPane = new JPanel();
467                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
468
469                 JLabel label = new JLabel("Select Device");
470                 label.setLabelFor(list);
471                 listPane.add(label);
472                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
473                 listPane.add(listScroller);
474                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
475
476                 c.fill = GridBagConstraints.BOTH;
477                 c.anchor = GridBagConstraints.CENTER;
478                 c.insets = i;
479                 c.weightx = 1;
480                 c.weighty = 1;
481
482                 c.gridx = 0;
483                 c.gridy = y_offset;
484                 c.gridwidth = 2;
485                 c.anchor = GridBagConstraints.CENTER;
486
487                 pane.add(listPane, c);
488
489                 cancel_button = new JButton("Cancel");
490                 cancel_button.addActionListener(this);
491                 cancel_button.setActionCommand("cancel");
492
493                 c.fill = GridBagConstraints.NONE;
494                 c.anchor = GridBagConstraints.CENTER;
495                 c.insets = i;
496                 c.weightx = 1;
497                 c.weighty = 1;
498
499                 c.gridx = 0;
500                 c.gridy = y_offset + 1;
501                 c.gridwidth = 1;
502                 c.anchor = GridBagConstraints.CENTER;
503
504                 pane.add(cancel_button, c);
505
506                 monitor_button = new JButton("Monitor");
507                 monitor_button.addActionListener(this);
508                 monitor_button.setActionCommand("monitor");
509
510                 c.fill = GridBagConstraints.NONE;
511                 c.anchor = GridBagConstraints.CENTER;
512                 c.insets = i;
513                 c.weightx = 1;
514                 c.weighty = 1;
515
516                 c.gridx = 1;
517                 c.gridy = y_offset + 1;
518                 c.gridwidth = 1;
519                 c.anchor = GridBagConstraints.CENTER;
520
521                 pane.add(monitor_button, c);
522
523                 pack();
524                 setLocationRelativeTo(owner);
525
526                 addWindowListener(new ConfigListener(this));
527
528                 setVisible(true);
529         }
530 }