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