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