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