e78c2124ab5142102b7a6da44fc55e49b720dc19
[fw/altos] / telegps / TeleGPS.java
1 /*
2  * Copyright © 2014 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.telegps;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import java.io.*;
24 import java.util.concurrent.*;
25 import java.util.*;
26 import org.altusmetrum.altoslib_5.*;
27 import org.altusmetrum.altosuilib_3.*;
28
29 public class TeleGPS
30         extends AltosUIFrame
31         implements AltosFlightDisplay, AltosFontListener, AltosUnitsListener, ActionListener
32 {
33
34         static String[] telegps_icon_names = {
35                 "/telegps-16.png",
36                 "/telegps-32.png",
37                 "/telegps-48.png",
38                 "/telegps-64.png",
39                 "/telegps-128.png",
40                 "/telegps-256.png"
41         };
42
43         static { set_icon_names(telegps_icon_names); }
44
45         static AltosVoice       voice;
46
47         static AltosVoice voice() {
48                 if (voice == null)
49                         voice = new AltosVoice();
50                 return voice;
51         }
52
53         AltosFlightReader       reader;
54         TeleGPSDisplayThread    thread;
55
56         JMenuBar                menu_bar;
57
58         JMenu                   file_menu;
59         JMenu                   monitor_menu;
60         JMenu                   device_menu;
61         AltosFreqList           frequencies;
62         ActionListener          frequency_listener;
63
64         Container               bag;
65
66         TeleGPSStatus           telegps_status;
67         TeleGPSStatusUpdate     status_update;
68         javax.swing.Timer       status_timer;
69
70         JTabbedPane             pane;
71
72         AltosUIMap              map;
73         TeleGPSInfo             gps_info;
74         TeleGPSState            gps_state;
75         AltosInfoTable          info_table;
76
77         LinkedList<AltosFlightDisplay>  displays;
78
79         /* File menu */
80         final static String     new_command = "new";
81         final static String     graph_command = "graph";
82         final static String     export_command = "export";
83         final static String     load_maps_command = "loadmaps";
84         final static String     preferences_command = "preferences";
85         final static String     close_command = "close";
86         final static String     exit_command = "exit";
87
88         static final String[][] file_menu_entries = new String[][] {
89                 { "New Window",         new_command },
90                 { "Graph Data",         graph_command },
91                 { "Export Data",        export_command },
92                 { "Load Maps",          load_maps_command },
93                 { "Preferences",        preferences_command },
94                 { "Close",              close_command },
95                 { "Exit",               exit_command },
96         };
97
98         /* Monitor menu */
99         final static String     connect_command = "connect";
100         final static String     disconnect_command = "disconnect";
101         final static String     scan_command = "scan";
102
103         static final String[][] monitor_menu_entries = new String[][] {
104                 { "Connect Device",     connect_command },
105                 { "Disconnect",         disconnect_command },
106                 { "Scan Channels",      scan_command },
107         };
108
109         /* Device menu */
110         final static String     download_command = "download";
111         final static String     configure_command = "configure";
112         final static String     flash_command = "flash";
113
114         static final String[][] device_menu_entries = new String[][] {
115                 { "Download Data",      download_command },
116                 { "Configure Device",   configure_command },
117                 { "Flash Device",       flash_command },
118         };
119
120         void stop_display() {
121                 if (thread != null && thread.isAlive()) {
122                         thread.interrupt();
123                         try {
124                                 thread.join();
125                         } catch (InterruptedException ie) {}
126                 }
127                 thread = null;
128         }
129
130         public void reset() {
131                 for (AltosFlightDisplay display : displays)
132                         display.reset();
133         }
134
135         public void font_size_changed(int font_size) {
136                 for (AltosFlightDisplay display : displays)
137                         display.font_size_changed(font_size);
138         }
139
140         public void units_changed(boolean imperial_units) {
141                 for (AltosFlightDisplay display : displays)
142                         display.units_changed(imperial_units);
143         }
144
145         public void show(AltosState state, AltosListenerState listener_state) {
146                 try {
147                         status_update.saved_state = state;
148
149                         if (state == null)
150                                 state = new AltosState();
151
152                         int i = 0;
153                         for (AltosFlightDisplay display : displays) {
154                                 display.show(state, listener_state);
155                                 i++;
156                         }
157                 } catch (Exception ex) {
158                         System.out.printf("Exception %s\n", ex.toString());
159                         for (StackTraceElement e : ex.getStackTrace())
160                                 System.out.printf("%s\n", e.toString());
161                 }
162         }
163
164         void new_window() {
165                 new TeleGPS();
166         }
167
168         void preferences() {
169                 new TeleGPSPreferences(this, voice());
170         }
171
172         void load_maps() {
173                 new AltosUIMapPreload(this);
174         }
175
176         void disconnect() {
177                 setTitle("TeleGPS");
178                 stop_display();
179                 if (status_timer != null) {
180                         status_timer.stop();
181                         status_timer = null;
182                         status_update = null;
183                 }
184
185                 telegps_status.disable_receive();
186                 disable_frequency_menu();
187         }
188
189         void connect(AltosDevice device) {
190                 if (reader != null)
191                         disconnect();
192                 try {
193                         AltosFlightReader       reader = new AltosTelemetryReader(new AltosSerial(device));
194                         set_reader(reader, device);
195                 } catch (FileNotFoundException ee) {
196                         JOptionPane.showMessageDialog(this,
197                                                       ee.getMessage(),
198                                                       String.format ("Cannot open %s", device.toShortString()),
199                                                       JOptionPane.ERROR_MESSAGE);
200                 } catch (AltosSerialInUseException si) {
201                         JOptionPane.showMessageDialog(this,
202                                                       String.format("Device \"%s\" already in use",
203                                                                     device.toShortString()),
204                                                       "Device in use",
205                                                       JOptionPane.ERROR_MESSAGE);
206                 } catch (IOException ee) {
207                         JOptionPane.showMessageDialog(this,
208                                                       String.format ("Unknown I/O error on %s", device.toShortString()),
209                                                       "Unknown I/O error",
210                                                       JOptionPane.ERROR_MESSAGE);
211                 } catch (TimeoutException te) {
212                         JOptionPane.showMessageDialog(this,
213                                                       String.format ("Timeout on %s", device.toShortString()),
214                                                       "Timeout error",
215                                                       JOptionPane.ERROR_MESSAGE);
216                 } catch (InterruptedException ie) {
217                         JOptionPane.showMessageDialog(this,
218                                                       String.format("Interrupted %s", device.toShortString()),
219                                                       "Interrupted exception",
220                                                       JOptionPane.ERROR_MESSAGE);
221                 }
222         }
223
224         void connect() {
225                 AltosDevice     device = AltosDeviceUIDialog.show(this,
226                                                                   AltosLib.product_basestation);
227                 if (device == null)
228                         return;
229                 connect(device);
230         }
231
232         public void scan_device_selected(AltosDevice device) {
233                 connect(device);
234         }
235
236         void scan() {
237                 new AltosScanUI(this, false);
238         }
239
240         void download(){
241                 new AltosEepromManage(this, AltosLib.product_telegps);
242         }
243
244         void configure() {
245                 new TeleGPSConfig(this);
246         }
247
248         void export() {
249                 AltosDataChooser chooser;
250                 chooser = new AltosDataChooser(this);
251                 AltosStateIterable states = chooser.runDialog();
252                 if (states == null)
253                         return;
254                 new AltosCSVUI(this, states, chooser.file());
255         }
256
257         void graph() {
258                 AltosDataChooser chooser;
259                 chooser = new AltosDataChooser(this);
260                 AltosStateIterable states = chooser.runDialog();
261                 if (states == null)
262                         return;
263                 try {
264                         new TeleGPSGraphUI(states, chooser.file());
265                 } catch (InterruptedException ie) {
266                 } catch (IOException ie) {
267                 }
268         }
269
270         void flash() {
271                 AltosFlashUI.show(this);
272         }
273
274         public void actionPerformed(ActionEvent ev) {
275
276                 /* File menu */
277                 if (new_command.equals(ev.getActionCommand())) {
278                         new_window();
279                         return;
280                 }
281                 if (preferences_command.equals(ev.getActionCommand())) {
282                         preferences();
283                         return;
284                 }
285                 if (load_maps_command.equals(ev.getActionCommand())) {
286                         load_maps();
287                         return;
288                 }
289                 if (close_command.equals(ev.getActionCommand())) {
290                         close();
291                         return;
292                 }
293                 if (exit_command.equals(ev.getActionCommand()))
294                         System.exit(0);
295
296                 /* Monitor menu */
297                 if (connect_command.equals(ev.getActionCommand())) {
298                         connect();
299                         return;
300                 }
301                 if (disconnect_command.equals(ev.getActionCommand())) {
302                         disconnect();
303                         return;
304                 }
305                 if (scan_command.equals(ev.getActionCommand())) {
306                         scan();
307                         return;
308                 }
309
310                 /* Device menu */
311                 if (download_command.equals(ev.getActionCommand())) {
312                         download();
313                         return;
314                 }
315                 if (configure_command.equals(ev.getActionCommand())) {
316                         configure();
317                         return;
318                 }
319                 if (export_command.equals(ev.getActionCommand())) {
320                         export();
321                         return;
322                 }
323                 if (graph_command.equals(ev.getActionCommand())) {
324                         graph();
325                         return;
326                 }
327                 if (flash_command.equals(ev.getActionCommand())) {
328                         flash();
329                         return;
330                 }
331         }
332
333         void enable_frequency_menu(int serial, final AltosFlightReader reader) {
334
335                 if (frequency_listener != null)
336                         disable_frequency_menu();
337
338                 frequency_listener = new ActionListener() {
339                                 public void actionPerformed(ActionEvent e) {
340                                         double frequency = frequencies.frequency();
341                                         try {
342                                                 reader.set_frequency(frequency);
343                                         } catch (TimeoutException te) {
344                                         } catch (InterruptedException ie) {
345                                         }
346                                         reader.save_frequency();
347                                 }
348                         };
349
350                 frequencies.addActionListener(frequency_listener);
351                 frequencies.set_product("Monitor");
352                 frequencies.set_serial(serial);
353                 frequencies.set_frequency(AltosUIPreferences.frequency(serial));
354
355                 menu_bar.add(frequencies);
356                 menu_bar.repaint();
357         }
358
359         void disable_frequency_menu() {
360                 if (frequency_listener == null)
361                         return;
362                 frequencies.removeActionListener(frequency_listener);
363                 menu_bar.remove(frequencies);
364                 menu_bar.repaint();
365                 frequency_listener = null;
366         }
367
368         public void set_reader(AltosFlightReader reader, AltosDevice device) {
369                 status_update = new TeleGPSStatusUpdate(telegps_status);
370
371                 status_timer = new javax.swing.Timer(100, status_update);
372                 status_timer.start();
373
374                 setTitle(String.format("TeleGPS %s", reader.name));
375                 thread = new TeleGPSDisplayThread(this, voice(), this, reader);
376                 thread.start();
377
378                 if (device != null)
379                         enable_frequency_menu(device.getSerial(), reader);
380         }
381
382         static int      number_of_windows;
383
384         static public void add_window() {
385                 ++number_of_windows;
386         }
387
388         static public void subtract_window() {
389                 --number_of_windows;
390                 if (number_of_windows == 0)
391                         System.exit(0);
392         }
393
394         private void close() {
395                 disconnect();
396                 AltosUIPreferences.unregister_font_listener(this);
397                 AltosPreferences.unregister_units_listener(this);
398                 setVisible(false);
399                 dispose();
400                 subtract_window();
401         }
402
403         private void add_menu(JMenu menu, String label, String action) {
404                 JMenuItem       item = new JMenuItem(label);
405                 menu.add(item);
406                 item.addActionListener(this);
407                 item.setActionCommand(action);
408         }
409
410
411         private JMenu make_menu(String label, String[][] items) {
412                 JMenu   menu = new JMenu(label);
413                 for (int i = 0; i < items.length; i++) {
414                         if (MAC_OS_X) {
415                                 if (items[i][1].equals("exit"))
416                                         continue;
417                                 if (items[i][1].equals("preferences"))
418                                         continue;
419                         }
420                         add_menu(menu, items[i][0], items[i][1]);
421                 }
422                 menu_bar.add(menu);
423                 return menu;
424         }
425
426         /* OSXAdapter interfaces */
427         public void macosx_file_handler(String path) {
428                 process_graph(new File(path));
429         }
430
431         public void macosx_quit_handler() {
432                 System.exit(0);
433         }
434
435         public void macosx_preferences_handler() {
436                 preferences();
437         }
438
439         public TeleGPS() {
440
441                 AltosUIPreferences.set_component(this);
442
443                 register_for_macosx_events();
444
445                 reader = null;
446
447                 bag = getContentPane();
448                 bag.setLayout(new GridBagLayout());
449
450                 GridBagConstraints c = new GridBagConstraints();
451
452                 setTitle("TeleGPS");
453
454                 menu_bar = new JMenuBar();
455                 setJMenuBar(menu_bar);
456
457                 file_menu = make_menu("File", file_menu_entries);
458                 monitor_menu = make_menu("Monitor", monitor_menu_entries);
459                 device_menu = make_menu("Device", device_menu_entries);
460                 frequencies = new AltosFreqList();
461
462                 displays = new LinkedList<AltosFlightDisplay>();
463
464                 int serial = -1;
465
466                 /* TeleGPS status is always visible */
467                 telegps_status = new TeleGPSStatus();
468                 c.gridx = 0;
469                 c.gridy = 1;
470                 c.fill = GridBagConstraints.HORIZONTAL;
471                 c.weightx = 1;
472                 c.gridwidth = 2;
473                 bag.add(telegps_status, c);
474                 c.gridwidth = 1;
475                 displays.add(telegps_status);
476
477
478                 /* The rest of the window uses a tabbed pane to
479                  * show one of the alternate data views
480                  */
481                 pane = new JTabbedPane();
482
483                 /* Make the tabbed pane use the rest of the window space */
484                 c.gridx = 0;
485                 c.gridy = 2;
486                 c.fill = GridBagConstraints.BOTH;
487                 c.weightx = 1;
488                 c.weighty = 1;
489                 c.gridwidth = 2;
490                 bag.add(pane, c);
491
492                 map = new AltosUIMap();
493                 pane.add(map.getName(), map);
494                 displays.add(map);
495
496                 gps_info = new TeleGPSInfo();
497                 pane.add(gps_info.getName(), gps_info);
498                 displays.add(gps_info);
499
500                 gps_state = new TeleGPSState();
501                 pane.add(gps_state.getName(), gps_state);
502                 displays.add(gps_state);
503
504                 info_table = new AltosInfoTable();
505                 pane.add("Table", info_table);
506                 displays.add(info_table);
507
508                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
509
510                 AltosUIPreferences.register_font_listener(this);
511                 AltosPreferences.register_units_listener(this);
512
513                 addWindowListener(new WindowAdapter() {
514                                 @Override
515                                 public void windowClosing(WindowEvent e) {
516                                         close();
517                                 }
518                         });
519
520                 pack();
521                 setVisible(true);
522
523                 add_window();
524         }
525
526         public TeleGPS(AltosFlightReader reader) {
527                 this();
528                 set_reader(reader, null);
529         }
530
531         public TeleGPS(AltosDevice device) {
532                 this();
533                 connect(device);
534         }
535
536         static AltosStateIterable record_iterable(File file) {
537                 FileInputStream in;
538                 try {
539                         in = new FileInputStream(file);
540                 } catch (Exception e) {
541                         System.out.printf("Failed to open file '%s'\n", file);
542                         return null;
543                 }
544                 if (file.getName().endsWith("telem"))
545                         return new AltosTelemetryFile(in);
546                 else
547                         return new AltosEepromFile(in);
548         }
549
550         static AltosReplayReader replay_file(File file) {
551                 AltosStateIterable states = record_iterable(file);
552                 if (states == null)
553                         return null;
554                 return new AltosReplayReader(states.iterator(), file);
555         }
556
557         static boolean process_graph(File file) {
558                 AltosStateIterable states = record_iterable(file);
559                 if (states == null)
560                         return false;
561                 try {
562                         new TeleGPSGraphUI(states, file);
563                 } catch (Exception e) {
564                         return false;
565                 }
566                 return true;
567         }
568
569         static boolean process_replay(File file) {
570                 AltosReplayReader new_reader = replay_file(file);
571                 if (new_reader == null)
572                         return false;
573
574                 new TeleGPS(new_reader);
575                 return true;
576         }
577
578         static final int process_none = 0;
579         static final int process_csv = 1;
580         static final int process_kml = 2;
581         static final int process_graph = 3;
582         static final int process_replay = 4;
583         static final int process_summary = 5;
584         static final int process_cat = 6;
585
586         public static boolean load_library(Frame frame) {
587                 if (!AltosUILib.load_library()) {
588                         JOptionPane.showMessageDialog(frame,
589                                                       String.format("No AltOS library in \"%s\"",
590                                                                     System.getProperty("java.library.path","<undefined>")),
591                                                       "Cannot load device access library",
592                                                       JOptionPane.ERROR_MESSAGE);
593                         return false;
594                 }
595                 return true;
596         }
597
598         public static void help(int code) {
599                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
600                 System.out.printf("  Options:\n");
601                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
602                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
603                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
604                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
605                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
606                 System.exit(code);
607         }
608
609         public static void main(String[] args) {
610                 int     errors = 0;
611
612                 load_library(null);
613                 try {
614                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
615                 } catch (Exception e) {
616                 }
617
618                 boolean any_created = false;
619
620
621                 /* Handle batch-mode */
622                 int process = process_none;
623                 for (int i = 0; i < args.length; i++) {
624                         if (args[i].equals("--help"))
625                                 help(0);
626                         else if (args[i].equals("--fetchmaps")) {
627                                 if (args.length < i + 3) {
628                                         help(1);
629                                 } else {
630                                         double lat = Double.parseDouble(args[i+1]);
631                                         double lon = Double.parseDouble(args[i+2]);
632                                         AltosUIMap.prefetch_maps(lat, lon);
633                                         i += 2;
634                                 }
635                         } else if (args[i].equals("--replay"))
636                                 process = process_replay;
637                         else if (args[i].equals("--kml"))
638                                 process = process_kml;
639                         else if (args[i].equals("--csv"))
640                                 process = process_csv;
641                         else if (args[i].equals("--graph"))
642                                 process = process_graph;
643                         else if (args[i].equals("--summary"))
644                                 process = process_summary;
645                         else if (args[i].equals("--cat"))
646                                 process = process_cat;
647                         else if (args[i].startsWith("--"))
648                                 help(1);
649                         else {
650                                 File file = new File(args[i]);
651                                 switch (process) {
652                                 case process_none:
653                                 case process_graph:
654                                         if (!process_graph(file))
655                                                 ++errors;
656                                         break;
657                                 case process_replay:
658                                         if (!process_replay(file))
659                                                 ++errors;
660                                         any_created = true;
661                                         break;
662                                 case process_kml:
663                                         ++errors;
664                                         break;
665                                 case process_csv:
666                                         ++errors;
667                                         break;
668                                 case process_summary:
669                                         ++errors;
670                                         break;
671                                 case process_cat:
672                                         ++errors;
673                                 }
674                         }
675                 }
676                 if (errors != 0)
677                         System.exit(errors);
678                 if (number_of_windows == 0) {
679                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(AltosLib.product_basestation);
680                         if (devices != null)
681                                 for (AltosDevice device : devices) {
682                                         new TeleGPS(device);
683                                         any_created = true;
684                                 }
685                         if (number_of_windows == 0)
686                                 new TeleGPS();
687                 }
688         }
689 }