ca1e68bbe74631bf663cb0490d78b2e5295145d1
[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                 new TeleGPSConfig(this);
214         }
215
216         void export() {
217         }
218
219         void graph() {
220         }
221
222         public void actionPerformed(ActionEvent ev) {
223
224                 /* File menu */
225                 if (new_command.equals(ev.getActionCommand())) {
226                         new_window();
227                         return;
228                 }
229                 if (preferences_command.equals(ev.getActionCommand())) {
230                         preferences();
231                         return;
232                 }
233                 if (load_maps_command.equals(ev.getActionCommand())) {
234                         load_maps();
235                         return;
236                 }
237                 if (close_command.equals(ev.getActionCommand())) {
238                         close();
239                         return;
240                 }
241                 if (exit_command.equals(ev.getActionCommand()))
242                         System.exit(0);
243
244                 /* Monitor menu */
245                 if (monitor_command.equals(ev.getActionCommand())) {
246                         monitor();
247                         return;
248                 }
249                 if (disconnect_command.equals(ev.getActionCommand())) {
250                         disconnect();
251                         return;
252                 }
253                 if (scan_command.equals(ev.getActionCommand())) {
254                         scan();
255                         return;
256                 }
257
258                 /* Device menu */
259                 if (download_command.equals(ev.getActionCommand())) {
260                         download();
261                         return;
262                 }
263                 if (configure_command.equals(ev.getActionCommand())) {
264                         configure();
265                         return;
266                 }
267                 if (export_command.equals(ev.getActionCommand())) {
268                         export();
269                         return;
270                 }
271                 if (graph_command.equals(ev.getActionCommand())) {
272                         graph();
273                         return;
274                 }
275         }
276
277         void add_frequency_menu(int serial, final AltosFlightReader reader) {
278                 // Channel menu
279                 frequencies = new AltosFreqList(AltosUIPreferences.frequency(serial));
280                 frequencies.set_product("Monitor");
281                 frequencies.set_serial(serial);
282                 frequencies.addActionListener(new ActionListener() {
283                                 public void actionPerformed(ActionEvent e) {
284                                         double frequency = frequencies.frequency();
285                                         try {
286                                                 reader.set_frequency(frequency);
287                                         } catch (TimeoutException te) {
288                                         } catch (InterruptedException ie) {
289                                         }
290                                         reader.save_frequency();
291                                 }
292                         });
293                 menu_bar.add(frequencies);
294         }
295
296         void remove_frequency_menu() {
297                 if (frequencies != null) {
298                         menu_bar.remove(frequencies);
299                         frequencies = null;
300                 }
301         }
302
303         public void set_reader(AltosFlightReader reader) {
304                 setTitle(String.format("TeleGPS %s", reader.name));
305                 thread = new AltosDisplayThread(this, voice(), this, reader);
306                 thread.start();
307         }
308
309         static int      number_of_windows;
310
311         private void close() {
312                 AltosUIPreferences.unregister_font_listener(this);
313                 setVisible(false);
314                 dispose();
315                 --number_of_windows;
316                 if (number_of_windows == 0)
317                         System.exit(0);
318         }
319
320         private void add_menu(JMenu menu, String label, String action) {
321                 JMenuItem       item = new JMenuItem(label);
322                 menu.add(item);
323                 item.addActionListener(this);
324                 item.setActionCommand(action);
325         }
326
327
328         private JMenu make_menu(String label, String[][] items) {
329                 JMenu   menu = new JMenu(label);
330                 for (int i = 0; i < items.length; i++)
331                         add_menu(menu, items[i][0], items[i][1]);
332                 menu_bar.add(menu);
333                 return menu;
334         }
335
336         public TeleGPS() {
337
338                 AltosUIPreferences.set_component(this);
339
340                 reader = null;
341
342                 bag = getContentPane();
343                 bag.setLayout(new GridBagLayout());
344
345                 GridBagConstraints c = new GridBagConstraints();
346
347                 setTitle("TeleGPS");
348
349                 menu_bar = new JMenuBar();
350                 setJMenuBar(menu_bar);
351
352                 file_menu = make_menu("File", file_menu_entries);
353                 monitor_menu = make_menu("Monitor", monitor_menu_entries);
354                 device_menu = make_menu("Device", device_menu_entries);
355
356                 int serial = -1;
357
358                 /* TeleGPS status is always visible */
359                 telegps_status = new TeleGPSStatus();
360                 c.gridx = 0;
361                 c.gridy = 1;
362                 c.fill = GridBagConstraints.HORIZONTAL;
363                 c.weightx = 1;
364                 c.gridwidth = 2;
365                 bag.add(telegps_status, c);
366                 c.gridwidth = 1;
367
368
369                 /* The rest of the window uses a tabbed pane to
370                  * show one of the alternate data views
371                  */
372                 pane = new JTabbedPane();
373
374                 /* Make the tabbed pane use the rest of the window space */
375                 c.gridx = 0;
376                 c.gridy = 2;
377                 c.fill = GridBagConstraints.BOTH;
378                 c.weightx = 1;
379                 c.weighty = 1;
380                 c.gridwidth = 2;
381                 bag.add(pane, c);
382
383                 sitemap = new AltosSiteMap();
384                 pane.add("Site Map", sitemap);
385
386                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
387
388                 AltosUIPreferences.register_font_listener(this);
389
390                 addWindowListener(new WindowAdapter() {
391                                 @Override
392                                 public void windowClosing(WindowEvent e) {
393                                         close();
394                                 }
395                         });
396
397                 pack();
398                 setVisible(true);
399
400                 ++number_of_windows;
401
402                 status_update = new TeleGPSStatusUpdate(telegps_status);
403
404                 new javax.swing.Timer(100, status_update).start();
405         }
406
407         public TeleGPS(AltosFlightReader reader) {
408                 this();
409                 set_reader(reader);
410         }
411
412         static AltosStateIterable record_iterable(File file) {
413                 FileInputStream in;
414                 try {
415                         in = new FileInputStream(file);
416                 } catch (Exception e) {
417                         System.out.printf("Failed to open file '%s'\n", file);
418                         return null;
419                 }
420                 if (file.getName().endsWith("telem"))
421                         return new AltosTelemetryFile(in);
422                 else
423                         return new AltosEepromFile(in);
424         }
425
426         static AltosReplayReader replay_file(File file) {
427                 AltosStateIterable states = record_iterable(file);
428                 if (states == null)
429                         return null;
430                 return new AltosReplayReader(states.iterator(), file);
431         }
432
433         static boolean process_replay(File file) {
434                 AltosReplayReader new_reader = replay_file(file);
435                 if (new_reader == null)
436                         return false;
437
438                 new TeleGPS(new_reader);
439                 return true;
440         }
441
442         static final int process_none = 0;
443         static final int process_csv = 1;
444         static final int process_kml = 2;
445         static final int process_graph = 3;
446         static final int process_replay = 4;
447         static final int process_summary = 5;
448         static final int process_cat = 6;
449
450         public static boolean load_library(Frame frame) {
451                 if (!AltosUILib.load_library()) {
452                         JOptionPane.showMessageDialog(frame,
453                                                       String.format("No AltOS library in \"%s\"",
454                                                                     System.getProperty("java.library.path","<undefined>")),
455                                                       "Cannot load device access library",
456                                                       JOptionPane.ERROR_MESSAGE);
457                         return false;
458                 }
459                 return true;
460         }
461
462         public static void help(int code) {
463                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
464                 System.out.printf("  Options:\n");
465                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
466                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
467                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
468                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
469                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
470                 System.exit(code);
471         }
472
473         public static void main(String[] args) {
474                 int     errors = 0;
475
476                 load_library(null);
477                 try {
478                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
479                 } catch (Exception e) {
480                 }
481
482                 boolean any_created = false;
483
484
485                 /* Handle batch-mode */
486                 int process = process_none;
487                 for (int i = 0; i < args.length; i++) {
488                         if (args[i].equals("--help"))
489                                 help(0);
490                         else if (args[i].equals("--fetchmaps")) {
491                                 if (args.length < i + 3) {
492                                         help(1);
493                                 } else {
494                                         double lat = Double.parseDouble(args[i+1]);
495                                         double lon = Double.parseDouble(args[i+2]);
496                                         AltosSiteMap.prefetchMaps(lat, lon);
497                                         i += 2;
498                                 }
499                         } else if (args[i].equals("--replay"))
500                                 process = process_replay;
501                         else if (args[i].equals("--kml"))
502                                 process = process_kml;
503                         else if (args[i].equals("--csv"))
504                                 process = process_csv;
505                         else if (args[i].equals("--graph"))
506                                 process = process_graph;
507                         else if (args[i].equals("--summary"))
508                                 process = process_summary;
509                         else if (args[i].equals("--cat"))
510                                 process = process_cat;
511                         else if (args[i].startsWith("--"))
512                                 help(1);
513                         else {
514                                 File file = new File(args[i]);
515                                 switch (process) {
516                                 case process_graph:
517                                         ++errors;
518                                         break;
519                                 case process_none:
520                                 case process_replay:
521                                         if (!process_replay(file))
522                                                 ++errors;
523                                         any_created = true;
524                                         break;
525                                 case process_kml:
526                                         ++errors;
527                                         break;
528                                 case process_csv:
529                                         ++errors;
530                                         break;
531                                 case process_summary:
532                                         ++errors;
533                                         break;
534                                 case process_cat:
535                                         ++errors;
536                                 }
537                         }
538                 }
539                 if (errors != 0)
540                         System.exit(errors);
541                 if (!any_created)
542                         new TeleGPS();
543         }
544 }