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