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