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