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