45482decbca20aa16a5dff413048e234d0e6a848
[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_4.*;
27 import org.altusmetrum.altosuilib_2.*;
28
29 public class TeleGPS extends AltosUIFrame implements AltosFlightDisplay, AltosFontListener, ActionListener {
30
31         static String[] telegps_icon_names = {
32                 "/telegps-16.png",
33                 "/telegps-32.png",
34                 "/telegps-48.png",
35                 "/telegps-64.png",
36                 "/telegps-128.png",
37                 "/telegps-256.png"
38         };
39
40         static { set_icon_names(telegps_icon_names); }
41
42         static AltosVoice       voice;
43
44         static AltosVoice voice() {
45                 if (voice == null)
46                         voice = new AltosVoice();
47                 return voice;
48         }
49
50         AltosFlightReader       reader;
51         AltosDisplayThread      thread;
52
53         JTabbedPane     pane;
54
55         AltosSiteMap    sitemap;
56         boolean         has_map;
57
58         JMenuBar        menu_bar;
59         JMenu           file_menu;
60         JMenu           monitor_menu;
61         JMenu           device_menu;
62
63         /* File menu */
64         final static String     new_command = "new";
65         final static String     preferences_command = "preferences";
66         final static String     load_maps_command = "loadmaps";
67         final static String     close_command = "close";
68         final static String     exit_command = "exit";
69
70         static final String[][] file_menu_entries = new String[][] {
71                 { "New Window",         new_command },
72                 { "Preferences",        preferences_command },
73                 { "Load Maps",          load_maps_command },
74                 { "Close",              close_command },
75                 { "Exit",               exit_command },
76         };
77
78         /* Monitor menu */
79         final static String     monitor_command = "monitor";
80         final static String     disconnect_command = "disconnect";
81         final static String     scan_command = "scan";
82
83         static final String[][] monitor_menu_entries = new String[][] {
84                 { "Monitor Device",     monitor_command },
85                 { "Disconnect",         disconnect_command },
86                 { "Scan Channels",      scan_command },
87         };
88
89         /* Device menu */
90         final static String     download_command = "download";
91         final static String     configure_command = "configure";
92         final static String     export_command = "export";
93         final static String     graph_command = "graph";
94
95         static final String[][] device_menu_entries = new String[][] {
96                 { "Download Data",      download_command },
97                 { "Configure Device",   configure_command },
98                 { "Export Data",        export_command },
99                 { "Graph Data",         graph_command },
100         };
101
102 //      private AltosInfoTable flightInfo;
103
104         boolean exit_on_close = false;
105
106         void stop_display() {
107                 if (thread != null && thread.isAlive()) {
108                         thread.interrupt();
109                         try {
110                                 thread.join();
111                         } catch (InterruptedException ie) {}
112                 }
113                 thread = null;
114         }
115
116         public void reset() {
117                 sitemap.reset();
118         }
119
120         public void set_font() {
121                 sitemap.set_font();
122         }
123
124         public void font_size_changed(int font_size) {
125                 set_font();
126         }
127
128
129 //      AltosFlightStatusUpdate status_update;
130
131         public void show(AltosState state, AltosListenerState listener_state) {
132 //              status_update.saved_state = state;
133
134                 if (state == null)
135                         state = new AltosState();
136
137                 sitemap.show(state, listener_state);
138                 telegps_status.show(state, listener_state);
139         }
140
141         Container               bag;
142         AltosFreqList           frequencies;
143         JLabel                  telemetry;
144         TeleGPSStatus           telegps_status;
145         TeleGPSStatusUpdate     status_update;
146
147         ActionListener          show_timer;
148
149         void new_window() {
150                 new TeleGPS();
151         }
152
153         void preferences() {
154         }
155
156         void load_maps() {
157                 new AltosSiteMapPreload(this);
158         }
159
160         void monitor() {
161                 AltosDevice     device = AltosDeviceUIDialog.show(this,
162                                                                   AltosLib.product_basestation);
163                 if (device == null)
164                         return;
165                 if (reader != null)
166                         disconnect();
167                 try {
168                         AltosFlightReader       reader = new AltosTelemetryReader(new AltosSerial(device));
169                         set_reader(reader);
170                         add_frequency_menu(device.getSerial(), reader);
171                 } catch (FileNotFoundException ee) {
172                         JOptionPane.showMessageDialog(this,
173                                                       ee.getMessage(),
174                                                       String.format ("Cannot open %s", device.toShortString()),
175                                                       JOptionPane.ERROR_MESSAGE);
176                 } catch (AltosSerialInUseException si) {
177                         JOptionPane.showMessageDialog(this,
178                                                       String.format("Device \"%s\" already in use",
179                                                                     device.toShortString()),
180                                                       "Device in use",
181                                                       JOptionPane.ERROR_MESSAGE);
182                 } catch (IOException ee) {
183                         JOptionPane.showMessageDialog(this,
184                                                       String.format ("Unknown I/O error on %s", device.toShortString()),
185                                                       "Unknown I/O error",
186                                                       JOptionPane.ERROR_MESSAGE);
187                 } catch (TimeoutException te) {
188                         JOptionPane.showMessageDialog(this,
189                                                       String.format ("Timeout on %s", device.toShortString()),
190                                                       "Timeout error",
191                                                       JOptionPane.ERROR_MESSAGE);
192                 } catch (InterruptedException ie) {
193                         JOptionPane.showMessageDialog(this,
194                                                       String.format("Interrupted %s", device.toShortString()),
195                                                       "Interrupted exception",
196                                                       JOptionPane.ERROR_MESSAGE);
197                 }
198         }
199
200         void disconnect() {
201                 setTitle("TeleGPS");
202                 stop_display();
203                 remove_frequency_menu();
204         }
205
206         void scan() {
207         }
208
209         void download(){
210         }
211
212         void configure() {
213         }
214
215         void export() {
216         }
217
218         void graph() {
219         }
220
221         public void actionPerformed(ActionEvent ev) {
222
223                 /* File menu */
224                 if (new_command.equals(ev.getActionCommand())) {
225                         new_window();
226                         return;
227                 }
228                 if (preferences_command.equals(ev.getActionCommand())) {
229                         preferences();
230                         return;
231                 }
232                 if (load_maps_command.equals(ev.getActionCommand())) {
233                         load_maps();
234                         return;
235                 }
236                 if (close_command.equals(ev.getActionCommand())) {
237                         close();
238                         return;
239                 }
240                 if (exit_command.equals(ev.getActionCommand()))
241                         System.exit(0);
242
243                 /* Monitor menu */
244                 if (monitor_command.equals(ev.getActionCommand())) {
245                         monitor();
246                         return;
247                 }
248                 if (disconnect_command.equals(ev.getActionCommand())) {
249                         disconnect();
250                         return;
251                 }
252                 if (scan_command.equals(ev.getActionCommand())) {
253                         scan();
254                         return;
255                 }
256
257                 /* Device menu */
258                 if (download_command.equals(ev.getActionCommand())) {
259                         download();
260                         return;
261                 }
262                 if (configure_command.equals(ev.getActionCommand())) {
263                         configure();
264                         return;
265                 }
266                 if (export_command.equals(ev.getActionCommand())) {
267                         export();
268                         return;
269                 }
270                 if (graph_command.equals(ev.getActionCommand())) {
271                         graph();
272                         return;
273                 }
274         }
275
276         void add_frequency_menu(int serial, final AltosFlightReader reader) {
277                 // Channel menu
278                 frequencies = new AltosFreqList(AltosUIPreferences.frequency(serial));
279                 frequencies.set_product("Monitor");
280                 frequencies.set_serial(serial);
281                 frequencies.addActionListener(new ActionListener() {
282                                 public void actionPerformed(ActionEvent e) {
283                                         double frequency = frequencies.frequency();
284                                         try {
285                                                 reader.set_frequency(frequency);
286                                         } catch (TimeoutException te) {
287                                         } catch (InterruptedException ie) {
288                                         }
289                                         reader.save_frequency();
290                                 }
291                         });
292                 menu_bar.add(frequencies);
293         }
294
295         void remove_frequency_menu() {
296                 if (frequencies != null) {
297                         menu_bar.remove(frequencies);
298                         frequencies = null;
299                 }
300         }
301
302         public void set_reader(AltosFlightReader reader) {
303                 setTitle(String.format("TeleGPS %s", reader.name));
304                 thread = new AltosDisplayThread(this, voice(), this, reader);
305                 thread.start();
306         }
307
308         static int      number_of_windows;
309
310         private void close() {
311                 AltosUIPreferences.unregister_font_listener(this);
312                 setVisible(false);
313                 dispose();
314                 --number_of_windows;
315                 if (number_of_windows == 0)
316                         System.exit(0);
317         }
318
319         private void add_menu(JMenu menu, String label, String action) {
320                 JMenuItem       item = new JMenuItem(label);
321                 menu.add(item);
322                 item.addActionListener(this);
323                 item.setActionCommand(action);
324         }
325
326
327         private JMenu make_menu(String label, String[][] items) {
328                 JMenu   menu = new JMenu(label);
329                 for (int i = 0; i < items.length; i++)
330                         add_menu(menu, items[i][0], items[i][1]);
331                 menu_bar.add(menu);
332                 return menu;
333         }
334
335         public TeleGPS() {
336
337                 AltosUIPreferences.set_component(this);
338
339                 reader = null;
340
341                 bag = getContentPane();
342                 bag.setLayout(new GridBagLayout());
343
344                 GridBagConstraints c = new GridBagConstraints();
345
346                 setTitle("TeleGPS");
347
348                 menu_bar = new JMenuBar();
349                 setJMenuBar(menu_bar);
350
351                 file_menu = make_menu("File", file_menu_entries);
352                 monitor_menu = make_menu("Monitor", monitor_menu_entries);
353                 device_menu = make_menu("Device", device_menu_entries);
354
355                 int serial = -1;
356
357                 /* TeleGPS status is always visible */
358                 telegps_status = new TeleGPSStatus();
359                 c.gridx = 0;
360                 c.gridy = 1;
361                 c.fill = GridBagConstraints.HORIZONTAL;
362                 c.weightx = 1;
363                 c.gridwidth = 2;
364                 bag.add(telegps_status, c);
365                 c.gridwidth = 1;
366
367
368                 /* The rest of the window uses a tabbed pane to
369                  * show one of the alternate data views
370                  */
371                 pane = new JTabbedPane();
372
373                 /* Make the tabbed pane use the rest of the window space */
374                 c.gridx = 0;
375                 c.gridy = 2;
376                 c.fill = GridBagConstraints.BOTH;
377                 c.weightx = 1;
378                 c.weighty = 1;
379                 c.gridwidth = 2;
380                 bag.add(pane, c);
381
382                 sitemap = new AltosSiteMap();
383                 pane.add("Site Map", sitemap);
384
385                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
386
387                 AltosUIPreferences.register_font_listener(this);
388
389                 addWindowListener(new WindowAdapter() {
390                                 @Override
391                                 public void windowClosing(WindowEvent e) {
392                                         close();
393                                 }
394                         });
395
396                 pack();
397                 setVisible(true);
398
399                 ++number_of_windows;
400
401                 status_update = new TeleGPSStatusUpdate(telegps_status);
402
403                 new javax.swing.Timer(100, status_update).start();
404         }
405
406         public TeleGPS(AltosFlightReader reader) {
407                 this();
408                 set_reader(reader);
409         }
410
411         static AltosStateIterable record_iterable(File file) {
412                 FileInputStream in;
413                 try {
414                         in = new FileInputStream(file);
415                 } catch (Exception e) {
416                         System.out.printf("Failed to open file '%s'\n", file);
417                         return null;
418                 }
419                 if (file.getName().endsWith("telem"))
420                         return new AltosTelemetryFile(in);
421                 else
422                         return new AltosEepromFile(in);
423         }
424
425         static AltosReplayReader replay_file(File file) {
426                 AltosStateIterable states = record_iterable(file);
427                 if (states == null)
428                         return null;
429                 return new AltosReplayReader(states.iterator(), file);
430         }
431
432         static boolean process_replay(File file) {
433                 AltosReplayReader new_reader = replay_file(file);
434                 if (new_reader == null)
435                         return false;
436
437                 new TeleGPS(new_reader);
438                 return true;
439         }
440
441         static final int process_none = 0;
442         static final int process_csv = 1;
443         static final int process_kml = 2;
444         static final int process_graph = 3;
445         static final int process_replay = 4;
446         static final int process_summary = 5;
447         static final int process_cat = 6;
448
449         public static boolean load_library(Frame frame) {
450                 if (!AltosUILib.load_library()) {
451                         JOptionPane.showMessageDialog(frame,
452                                                       String.format("No AltOS library in \"%s\"",
453                                                                     System.getProperty("java.library.path","<undefined>")),
454                                                       "Cannot load device access library",
455                                                       JOptionPane.ERROR_MESSAGE);
456                         return false;
457                 }
458                 return true;
459         }
460
461         public static void help(int code) {
462                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
463                 System.out.printf("  Options:\n");
464                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
465                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
466                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
467                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
468                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
469                 System.exit(code);
470         }
471
472         public static void main(String[] args) {
473                 int     errors = 0;
474
475                 load_library(null);
476                 try {
477                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
478                 } catch (Exception e) {
479                 }
480
481                 boolean any_created = false;
482
483
484                 /* Handle batch-mode */
485                 int process = process_none;
486                 for (int i = 0; i < args.length; i++) {
487                         if (args[i].equals("--help"))
488                                 help(0);
489                         else if (args[i].equals("--fetchmaps")) {
490                                 if (args.length < i + 3) {
491                                         help(1);
492                                 } else {
493                                         double lat = Double.parseDouble(args[i+1]);
494                                         double lon = Double.parseDouble(args[i+2]);
495                                         AltosSiteMap.prefetchMaps(lat, lon);
496                                         i += 2;
497                                 }
498                         } else if (args[i].equals("--replay"))
499                                 process = process_replay;
500                         else if (args[i].equals("--kml"))
501                                 process = process_kml;
502                         else if (args[i].equals("--csv"))
503                                 process = process_csv;
504                         else if (args[i].equals("--graph"))
505                                 process = process_graph;
506                         else if (args[i].equals("--summary"))
507                                 process = process_summary;
508                         else if (args[i].equals("--cat"))
509                                 process = process_cat;
510                         else if (args[i].startsWith("--"))
511                                 help(1);
512                         else {
513                                 File file = new File(args[i]);
514                                 switch (process) {
515                                 case process_graph:
516                                         ++errors;
517                                         break;
518                                 case process_none:
519                                 case process_replay:
520                                         if (!process_replay(file))
521                                                 ++errors;
522                                         any_created = true;
523                                         break;
524                                 case process_kml:
525                                         ++errors;
526                                         break;
527                                 case process_csv:
528                                         ++errors;
529                                         break;
530                                 case process_summary:
531                                         ++errors;
532                                         break;
533                                 case process_cat:
534                                         ++errors;
535                                 }
536                         }
537                 }
538                 if (errors != 0)
539                         System.exit(errors);
540                 if (!any_created)
541                         new TeleGPS();
542         }
543 }