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