altosui: Show AltosFrequency in scan results
[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         javax.swing.Timer               timer;
119         AltosScanResults                results = new AltosScanResults();
120
121         int                             telemetry;
122
123         final static int                timeout = 1200;
124         TelemetryHandler                handler;
125         Thread                          thread;
126         AltosFrequency[]                frequencies;
127         int                             frequency_index;
128
129         void scan_exception(Exception e) {
130                 if (e instanceof FileNotFoundException) {
131                         JOptionPane.showMessageDialog(owner,
132                                                       String.format("Cannot open device \"%s\"",
133                                                                     device.toShortString()),
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                         frequency_index = 0;
215                         ++telemetry;
216                         if (telemetry > Altos.ao_telemetry_max)
217                                 telemetry = Altos.ao_telemetry_min;
218                         set_telemetry();
219                 }
220                 set_frequency();
221                 set_label();
222                 reader.serial.set_monitor(true);
223         }
224
225
226         void close() {
227                 if (thread != null && thread.isAlive()) {
228                         thread.interrupt();
229                         try {
230                                 thread.join();
231                         } catch (InterruptedException ie) {}
232                 }
233                 thread = null;
234                 if (timer != null)
235                         timer.stop();
236                 setVisible(false);
237                 dispose();
238         }
239
240         void tick_timer() throws InterruptedException, TimeoutException {
241                 next();
242         }
243
244         public void actionPerformed(ActionEvent e) {
245                 String cmd = e.getActionCommand();
246
247                 try {
248                         if (cmd.equals("cancel"))
249                                 close();
250
251                         if (cmd.equals("tick"))
252                                 tick_timer();
253
254                         if (cmd.equals("monitor")) {
255                                 close();
256                                 AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
257                                 if (r != null) {
258                                         if (device != null) {
259                                                 if (reader != null) {
260                                                         reader.set_telemetry(r.telemetry);
261                                                         reader.set_frequency(r.frequency.frequency);
262                                                         reader.save_frequency();
263                                                         owner.telemetry_window(device);
264                                                 }
265                                         }
266                                 }
267                         }
268                 } catch (TimeoutException te) {
269                         close();
270                 } catch (InterruptedException ie) {
271                         close();
272                 }
273         }
274
275         /* A window listener to catch closing events and tell the config code */
276         class ConfigListener extends WindowAdapter {
277                 AltosScanUI     ui;
278
279                 public ConfigListener(AltosScanUI this_ui) {
280                         ui = this_ui;
281                 }
282
283                 public void windowClosing(WindowEvent e) {
284                         ui.actionPerformed(new ActionEvent(e.getSource(),
285                                                            ActionEvent.ACTION_PERFORMED,
286                                                            "close"));
287                 }
288         }
289
290         private boolean open() {
291                 device = AltosDeviceDialog.show(owner, Altos.product_basestation);
292                 if (device == null)
293                         return false;
294                 try {
295                         reader = new AltosTelemetryReader(device);
296                         set_frequency();
297                         set_telemetry();
298                         try {
299                                 Thread.sleep(100);
300                         } catch (InterruptedException ie) {
301                         }
302                         reader.flush();
303                         handler = new TelemetryHandler();
304                         thread = new Thread(handler);
305                         thread.start();
306                         return true;
307                 } catch (FileNotFoundException ee) {
308                         JOptionPane.showMessageDialog(owner,
309                                                       String.format("Cannot open device \"%s\"",
310                                                                     device.toShortString()),
311                                                       "Cannot open target device",
312                                                       JOptionPane.ERROR_MESSAGE);
313                 } catch (AltosSerialInUseException si) {
314                         JOptionPane.showMessageDialog(owner,
315                                                       String.format("Device \"%s\" already in use",
316                                                                     device.toShortString()),
317                                                       "Device in use",
318                                                       JOptionPane.ERROR_MESSAGE);
319                 } catch (IOException ee) {
320                         JOptionPane.showMessageDialog(owner,
321                                                       device.toShortString(),
322                                                       "Unkonwn I/O error",
323                                                       JOptionPane.ERROR_MESSAGE);
324                 } catch (TimeoutException te) {
325                         JOptionPane.showMessageDialog(owner,
326                                                       device.toShortString(),
327                                                       "Timeout error",
328                                                       JOptionPane.ERROR_MESSAGE);
329                 } catch (InterruptedException ie) {
330                         JOptionPane.showMessageDialog(owner,
331                                                       device.toShortString(),
332                                                       "Interrupted exception",
333                                                       JOptionPane.ERROR_MESSAGE);
334                 }
335                 if (reader != null)
336                         reader.close(false);
337                 return false;
338         }
339
340         public AltosScanUI(AltosUI in_owner) {
341
342                 owner = in_owner;
343
344                 frequencies = AltosPreferences.common_frequencies();
345                 frequency_index = 0;
346                 telemetry = Altos.ao_telemetry_min;
347
348                 if (!open())
349                         return;
350
351                 Container               pane = getContentPane();
352                 GridBagConstraints      c = new GridBagConstraints();
353                 Insets                  i = new Insets(4,4,4,4);
354
355                 timer = new javax.swing.Timer(timeout, this);
356                 timer.setActionCommand("tick");
357                 timer.restart();
358
359                 owner = in_owner;
360
361                 pane.setLayout(new GridBagLayout());
362
363                 scanning_label = new JLabel("Scanning:");
364                 frequency_label = new JLabel("");
365                 telemetry_label = new JLabel("");
366                 
367                 set_label();
368
369                 c.fill = GridBagConstraints.NONE;
370                 c.anchor = GridBagConstraints.WEST;
371                 c.insets = i;
372                 c.weightx = 1;
373                 c.weighty = 1;
374
375                 c.gridx = 0;
376                 c.gridy = 0;
377                 c.gridwidth = 2;
378
379                 pane.add(scanning_label, c);
380                 c.gridy = 1;
381                 pane.add(frequency_label, c);
382                 c.gridy = 2;
383                 pane.add(telemetry_label, c);
384
385                 list = new JList(results) {
386                                 //Subclass JList to workaround bug 4832765, which can cause the
387                                 //scroll pane to not let the user easily scroll up to the beginning
388                                 //of the list.  An alternative would be to set the unitIncrement
389                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
390                                 //aligned scrolling, but it should work.
391                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
392                                                                       int orientation,
393                                                                       int direction) {
394                                         int row;
395                                         if (orientation == SwingConstants.VERTICAL &&
396                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
397                                                 Rectangle r = getCellBounds(row, row);
398                                                 if ((r.y == visibleRect.y) && (row != 0))  {
399                                                         Point loc = r.getLocation();
400                                                         loc.y--;
401                                                         int prevIndex = locationToIndex(loc);
402                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
403
404                                                         if (prevR == null || prevR.y >= r.y) {
405                                                                 return 0;
406                                                         }
407                                                         return prevR.height;
408                                                 }
409                                         }
410                                         return super.getScrollableUnitIncrement(
411                                                 visibleRect, orientation, direction);
412                                 }
413                         };
414
415                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
416                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
417                 list.setVisibleRowCount(-1);
418
419                 list.addMouseListener(new MouseAdapter() {
420                                  public void mouseClicked(MouseEvent e) {
421                                          if (e.getClickCount() == 2) {
422                                                  monitor_button.doClick(); //emulate button click
423                                          }
424                                  }
425                         });
426                 JScrollPane listScroller = new JScrollPane(list);
427                 listScroller.setPreferredSize(new Dimension(400, 80));
428                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
429
430                 //Create a container so that we can add a title around
431                 //the scroll pane.  Can't add a title directly to the
432                 //scroll pane because its background would be white.
433                 //Lay out the label and scroll pane from top to bottom.
434                 JPanel listPane = new JPanel();
435                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
436
437                 JLabel label = new JLabel("Select Device");
438                 label.setLabelFor(list);
439                 listPane.add(label);
440                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
441                 listPane.add(listScroller);
442                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
443
444                 c.fill = GridBagConstraints.BOTH;
445                 c.anchor = GridBagConstraints.CENTER;
446                 c.insets = i;
447                 c.weightx = 1;
448                 c.weighty = 1;
449
450                 c.gridx = 0;
451                 c.gridy = 3;
452                 c.gridwidth = 2;
453                 c.anchor = GridBagConstraints.CENTER;
454
455                 pane.add(listPane, c);
456
457                 cancel_button = new JButton("Cancel");
458                 cancel_button.addActionListener(this);
459                 cancel_button.setActionCommand("cancel");
460
461                 c.fill = GridBagConstraints.NONE;
462                 c.anchor = GridBagConstraints.CENTER;
463                 c.insets = i;
464                 c.weightx = 1;
465                 c.weighty = 1;
466
467                 c.gridx = 0;
468                 c.gridy = 4;
469                 c.gridwidth = 1;
470                 c.anchor = GridBagConstraints.CENTER;
471
472                 pane.add(cancel_button, c);
473
474                 monitor_button = new JButton("Monitor");
475                 monitor_button.addActionListener(this);
476                 monitor_button.setActionCommand("monitor");
477
478                 c.fill = GridBagConstraints.NONE;
479                 c.anchor = GridBagConstraints.CENTER;
480                 c.insets = i;
481                 c.weightx = 1;
482                 c.weighty = 1;
483
484                 c.gridx = 1;
485                 c.gridy = 4;
486                 c.gridwidth = 1;
487                 c.anchor = GridBagConstraints.CENTER;
488
489                 pane.add(monitor_button, c);
490
491                 pack();
492                 setLocationRelativeTo(owner);
493
494                 addWindowListener(new ConfigListener(this));
495
496                 setVisible(true);
497         }
498 }