altosui: Don't ship TeleMetrum v3.0 firmware (yet)
[fw/altos] / altosui / AltosUI.java
1 /*
2  * Copyright © 2010 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 altosui;
20
21 import java.awt.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import java.io.*;
25 import java.util.concurrent.*;
26 import org.altusmetrum.altoslib_11.*;
27 import org.altusmetrum.altosuilib_11.*;
28
29 public class AltosUI extends AltosUIFrame {
30         public AltosVoice voice = new AltosVoice();
31
32         public static boolean load_library(Frame frame) {
33                 if (!Altos.load_library()) {
34                         JOptionPane.showMessageDialog(frame,
35                                                       String.format("No AltOS library in \"%s\"",
36                                                                     System.getProperty("java.library.path","<undefined>")),
37                                                       "Cannot load device access library",
38                                                       JOptionPane.ERROR_MESSAGE);
39                         return false;
40                 }
41                 return true;
42         }
43
44         void telemetry_window(AltosDevice device) {
45                 try {
46                         AltosFlightReader reader = new AltosTelemetryReader(new AltosSerial(device));
47                         if (reader != null)
48                                 new AltosFlightUI(voice, reader, device.getSerial());
49                 } catch (FileNotFoundException ee) {
50                         JOptionPane.showMessageDialog(AltosUI.this,
51                                                       ee.getMessage(),
52                                                       String.format ("Cannot open %s", device.toShortString()),
53                                                       JOptionPane.ERROR_MESSAGE);
54                 } catch (AltosSerialInUseException si) {
55                         JOptionPane.showMessageDialog(AltosUI.this,
56                                                       String.format("Device \"%s\" already in use",
57                                                                     device.toShortString()),
58                                                       "Device in use",
59                                                       JOptionPane.ERROR_MESSAGE);
60                 } catch (IOException ee) {
61                         JOptionPane.showMessageDialog(AltosUI.this,
62                                                       String.format ("Unknown I/O error on %s", device.toShortString()),
63                                                       "Unknown I/O error",
64                                                       JOptionPane.ERROR_MESSAGE);
65                 } catch (TimeoutException te) {
66                         JOptionPane.showMessageDialog(this,
67                                                       String.format ("Timeout on %s", device.toShortString()),
68                                                       "Timeout error",
69                                                       JOptionPane.ERROR_MESSAGE);
70                 } catch (InterruptedException ie) {
71                         JOptionPane.showMessageDialog(this,
72                                                       String.format("Interrupted %s", device.toShortString()),
73                                                       "Interrupted exception",
74                                                       JOptionPane.ERROR_MESSAGE);
75                 }
76         }
77
78         public void scan_device_selected(AltosDevice device) {
79                 telemetry_window(device);
80         }
81
82         Container       pane;
83         GridBagLayout   gridbag;
84
85         JButton addButton(int x, int y, String label) {
86                 GridBagConstraints      c;
87                 JButton                 b;
88
89                 c = new GridBagConstraints();
90                 c.gridx = x; c.gridy = y;
91                 c.fill = GridBagConstraints.BOTH;
92                 c.weightx = 1;
93                 c.weighty = 1;
94                 b = new JButton(label);
95
96                 //Dimension ps = b.getPreferredSize();
97
98                 gridbag.setConstraints(b, c);
99                 add(b, c);
100                 return b;
101         }
102
103         /* OSXAdapter interfaces */
104         public void macosx_file_handler(String path) {
105                 process_graph(new File(path));
106         }
107
108         public void macosx_quit_handler() {
109                 System.exit(0);
110         }
111
112         public void macosx_preferences_handler() {
113                 ConfigureAltosUI();
114         }
115
116         public AltosUI() {
117
118                 load_library(null);
119
120                 register_for_macosx_events();
121
122                 AltosUIPreferences.set_component(this);
123
124                 pane = getContentPane();
125                 gridbag = new GridBagLayout();
126                 pane.setLayout(gridbag);
127
128                 JButton b;
129
130                 b = addButton(0, 0, "Monitor Flight");
131                 b.addActionListener(new ActionListener() {
132                                         public void actionPerformed(ActionEvent e) {
133                                                 ConnectToDevice();
134                                         }
135                                 });
136                 b.setToolTipText("Connect to TeleDongle and monitor telemetry");
137                 b = addButton(1, 0, "Save Flight Data");
138                 b.addActionListener(new ActionListener() {
139                                         public void actionPerformed(ActionEvent e) {
140                                                 SaveFlightData();
141                                         }
142                                 });
143                 b.setToolTipText("Download and/or delete flight data from an altimeter");
144                 b = addButton(2, 0, "Replay Flight");
145                 b.addActionListener(new ActionListener() {
146                                         public void actionPerformed(ActionEvent e) {
147                                                 Replay();
148                                         }
149                                 });
150                 b.setToolTipText("Watch an old flight in real-time");
151                 b = addButton(3, 0, "Graph Data");
152                 b.addActionListener(new ActionListener() {
153                                         public void actionPerformed(ActionEvent e) {
154                                                 GraphData();
155                                         }
156                                 });
157                 b.setToolTipText("Present flight data in a graph and table of statistics");
158                 b = addButton(4, 0, "Export Data");
159                 b.addActionListener(new ActionListener() {
160                                         public void actionPerformed(ActionEvent e) {
161                                                 ExportData();
162                                         }
163                                 });
164                 b.setToolTipText("Convert flight data for a spreadsheet or GoogleEarth");
165                 b = addButton(0, 1, "Configure Altimeter");
166                 b.addActionListener(new ActionListener() {
167                                         public void actionPerformed(ActionEvent e) {
168                                                 ConfigureTeleMetrum();
169                                         }
170                                 });
171                 b.setToolTipText("Set flight, storage and communication parameters");
172                 b = addButton(1, 1, "Configure AltosUI");
173                 b.addActionListener(new ActionListener() {
174                                 public void actionPerformed(ActionEvent e) {
175                                         ConfigureAltosUI();
176                                 }
177                         });
178                 b.setToolTipText("Global AltosUI settings");
179
180                 b = addButton(2, 1, "Configure Ground Station");
181                 b.addActionListener(new ActionListener() {
182                                 public void actionPerformed(ActionEvent e) {
183                                         ConfigureTeleDongle();
184                                 }
185                         });
186
187                 b = addButton(3, 1, "Flash Image");
188                 b.addActionListener(new ActionListener() {
189                                 public void actionPerformed(ActionEvent e) {
190                                         FlashImage();
191                                 }
192                         });
193                 b.setToolTipText("Replace the firmware in any AltusMetrum product");
194
195                 b = addButton(4, 1, "Fire Igniter");
196                 b.addActionListener(new ActionListener() {
197                                 public void actionPerformed(ActionEvent e) {
198                                         FireIgniter();
199                                 }
200                         });
201                 b.setToolTipText("Remote control of igniters for deployment testing");
202                 b = addButton(0, 2, "Scan Channels");
203                 b.addActionListener(new ActionListener() {
204                                 public void actionPerformed(ActionEvent e) {
205                                         ScanChannels();
206                                 }
207                         });
208                 b.setToolTipText("Find what channel an altimeter is sending telemetry on");
209                 b = addButton(1, 2, "Load Maps");
210                 b.addActionListener(new ActionListener() {
211                                 public void actionPerformed(ActionEvent e) {
212                                         LoadMaps();
213                                 }
214                         });
215                 b.setToolTipText("Download satellite images for off-line flight monitoring");
216                 b = addButton(2, 2, "Monitor Idle");
217                 b.addActionListener(new ActionListener() {
218                                 public void actionPerformed(ActionEvent e) {
219                                         IdleMonitor();
220                                 }
221                         });
222                 b.setToolTipText("Check flight readiness of altimeter in idle mode");
223
224 //              b = addButton(3, 2, "Launch Controller");
225 //              b.addActionListener(new ActionListener() {
226 //                              public void actionPerformed(ActionEvent e) {
227 //                                      LaunchController();
228 //                              }
229 //                      });
230
231                 b = addButton(4, 2, "Quit");
232                 b.addActionListener(new ActionListener() {
233                                 public void actionPerformed(ActionEvent e) {
234                                         System.exit(0);
235                                 }
236                         });
237                 b.setToolTipText("Close all active windows and terminate AltosUI");
238
239                 setTitle("AltOS");
240
241                 pane.doLayout();
242                 pane.validate();
243
244                 doLayout();
245                 validate();
246
247                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
248                 addWindowListener(new WindowAdapter() {
249                         @Override
250                         public void windowClosing(WindowEvent e) {
251                                 System.exit(0);
252                         }
253                 });
254
255                 setLocationByPlatform(false);
256
257                 /* Insets aren't set before the window is visible */
258                 setVisible(true);
259         }
260
261         private void ConnectToDevice() {
262                 AltosDevice     device = AltosDeviceUIDialog.show(AltosUI.this,
263                                                                 Altos.product_basestation);
264
265                 if (device != null)
266                         telemetry_window(device);
267         }
268
269         void ConfigureCallsign() {
270                 String  result;
271                 result = JOptionPane.showInputDialog(AltosUI.this,
272                                                      "Configure Callsign",
273                                                      AltosUIPreferences.callsign());
274                 if (result != null)
275                         AltosUIPreferences.set_callsign(result);
276         }
277
278         void ConfigureTeleMetrum() {
279                 new AltosConfig(AltosUI.this);
280         }
281
282         void ConfigureTeleDongle() {
283                 new AltosConfigTD(AltosUI.this);
284         }
285
286         void FlashImage() {
287                 AltosFlashUI.show(AltosUI.this);
288         }
289
290         void FireIgniter() {
291                 new AltosIgniteUI(AltosUI.this);
292         }
293
294         void ScanChannels() {
295                 new AltosScanUI(AltosUI.this, true);
296         }
297
298         void LoadMaps() {
299                 new AltosUIMapPreload(AltosUI.this);
300         }
301
302         void LaunchController() {
303                 new AltosLaunchUI(AltosUI.this);
304         }
305
306         /*
307          * Replay a flight from telemetry data
308          */
309         private void Replay() {
310                 AltosDataChooser chooser = new AltosDataChooser(
311                         AltosUI.this);
312
313                 Iterable<AltosState> states = chooser.runDialog();
314                 if (states != null) {
315                         AltosFlightReader reader = new AltosReplayReader(states.iterator(),
316                                                                          chooser.file());
317                         new AltosFlightUI(voice, reader);
318                 }
319         }
320
321         /* Connect to TeleMetrum, either directly or through
322          * a TeleDongle over the packet link
323          */
324         private void SaveFlightData() {
325                 new AltosEepromManage(AltosUI.this, AltosLib.product_any);
326         }
327
328         /* Load a flight log file and write out a CSV file containing
329          * all of the data in standard units
330          */
331
332         private void ExportData() {
333                 AltosDataChooser chooser;
334                 chooser = new AltosDataChooser(this);
335                 AltosStateIterable states = chooser.runDialog();
336                 if (states == null)
337                         return;
338                 new AltosCSVUI(AltosUI.this, states, chooser.file());
339         }
340
341         /* Load a flight log CSV file and display a pretty graph.
342          */
343
344         private void GraphData() {
345                 AltosDataChooser chooser;
346                 chooser = new AltosDataChooser(this);
347                 AltosStateIterable states = chooser.runDialog();
348                 if (states == null)
349                         return;
350                 try {
351                         new AltosGraphUI(states, chooser.file());
352                 } catch (InterruptedException ie) {
353                 } catch (IOException ie) {
354                 }
355         }
356
357         private void ConfigureAltosUI() {
358                 new AltosConfigureUI(AltosUI.this, voice);
359         }
360
361         private void IdleMonitor() {
362                 try {
363                         new AltosIdleMonitorUI(this);
364                 } catch (Exception e) {
365                 }
366         }
367
368         static AltosStateIterable open_logfile(File file) {
369                 try {
370                         FileInputStream in;
371
372                         in = new FileInputStream(file);
373                         if (file.getName().endsWith("telem"))
374                                 return new AltosTelemetryFile(in);
375                         else
376                                 return new AltosEepromFile(in);
377                 } catch (FileNotFoundException fe) {
378                         System.out.printf("%s\n", fe.getMessage());
379                         return null;
380                 }
381         }
382
383         static AltosWriter open_csv(File file) {
384                 try {
385                         return new AltosCSV(file);
386                 } catch (FileNotFoundException fe) {
387                         System.out.printf("%s\n", fe.getMessage());
388                         return null;
389                 }
390         }
391
392         static AltosWriter open_kml(File file) {
393                 try {
394                         return new AltosKML(file);
395                 } catch (FileNotFoundException fe) {
396                         System.out.printf("%s\n", fe.getMessage());
397                         return null;
398                 }
399         }
400
401         static final int process_none = 0;
402         static final int process_csv = 1;
403         static final int process_kml = 2;
404         static final int process_graph = 3;
405         static final int process_replay = 4;
406         static final int process_summary = 5;
407         static final int process_cat = 6;
408
409         static boolean process_csv(File input) {
410                 AltosStateIterable states = open_logfile(input);
411                 if (states == null)
412                         return false;
413
414                 File output = Altos.replace_extension(input,".csv");
415                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
416                 if (input.equals(output)) {
417                         System.out.printf("Not processing '%s'\n", input);
418                         return false;
419                 } else {
420                         AltosWriter writer = open_csv(output);
421                         if (writer == null)
422                                 return false;
423                         writer.write(states);
424                         writer.close();
425                 }
426                 return true;
427         }
428
429         static boolean process_kml(File input) {
430                 AltosStateIterable states = open_logfile(input);
431                 if (states == null)
432                         return false;
433
434                 File output = Altos.replace_extension(input,".kml");
435                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
436                 if (input.equals(output)) {
437                         System.out.printf("Not processing '%s'\n", input);
438                         return false;
439                 } else {
440                         AltosWriter writer = open_kml(output);
441                         if (writer == null)
442                                 return false;
443                         writer.write(states);
444                         writer.close();
445                         return true;
446                 }
447         }
448
449         static AltosStateIterable record_iterable(File file) {
450                 FileInputStream in;
451                 try {
452                         in = new FileInputStream(file);
453                 } catch (Exception e) {
454                         System.out.printf("Failed to open file '%s'\n", file);
455                         return null;
456                 }
457                 if (file.getName().endsWith("telem"))
458                         return new AltosTelemetryFile(in);
459                 else
460                         return new AltosEepromFile(in);
461         }
462
463         static AltosReplayReader replay_file(File file) {
464                 AltosStateIterable states = record_iterable(file);
465                 if (states == null)
466                         return null;
467                 return new AltosReplayReader(states.iterator(), file);
468         }
469
470         static boolean process_replay(File file) {
471                 AltosReplayReader reader = replay_file(file);
472                 if (reader == null)
473                         return false;
474                 AltosFlightUI flight_ui = new AltosFlightUI(new AltosVoice(), reader);
475                 return true;
476         }
477
478         static boolean process_graph(File file) {
479                 AltosStateIterable states = record_iterable(file);
480                 if (states == null)
481                         return false;
482                 try {
483                         new AltosGraphUI(states, file);
484                         return true;
485                 } catch (InterruptedException ie) {
486                 } catch (IOException ie) {
487                 }
488                 return false;
489         }
490
491         static boolean process_summary(File file) {
492                 AltosStateIterable states = record_iterable(file);
493                 if (states == null)
494                         return false;
495                 try {
496                         System.out.printf("%s:\n", file.toString());
497                         AltosFlightStats stats = new AltosFlightStats(states);
498                         if (stats.serial != AltosLib.MISSING)
499                                 System.out.printf("Serial:       %5d\n", stats.serial);
500                         if (stats.flight != AltosLib.MISSING)
501                                 System.out.printf("Flight:       %5d\n", stats.flight);
502                         if (stats.year != AltosLib.MISSING)
503                                 System.out.printf("Date:    %04d-%02d-%02d\n",
504                                                   stats.year, stats.month, stats.day);
505                         if (stats.hour != AltosLib.MISSING)
506                                 System.out.printf("Time:      %02d:%02d:%02d UTC\n",
507                                                   stats.hour, stats.minute, stats.second);
508                         if (stats.max_height != AltosLib.MISSING)
509                                 System.out.printf("Max height:  %6.0f m    %6.0f ft\n",
510                                                   stats.max_height,
511                                                   AltosConvert.meters_to_feet(stats.max_height));
512                         if (stats.max_speed != AltosLib.MISSING)
513                                 System.out.printf("Max speed:   %6.0f m/s  %6.0f ft/s  %6.4f Mach\n",
514                                                   stats.max_speed,
515                                                   AltosConvert.meters_to_feet(stats.max_speed),
516                                                   AltosConvert.meters_to_mach(stats.max_speed));
517                         if (stats.max_acceleration != AltosLib.MISSING) {
518                                 System.out.printf("Max accel:   %6.0f m/s² %6.0f ft/s² %6.2f g\n",
519                                                   stats.max_acceleration,
520                                                   AltosConvert.meters_to_feet(stats.max_acceleration),
521                                                   AltosConvert.meters_to_g(stats.max_acceleration));
522                         }
523                         if (stats.state_speed[Altos.ao_flight_drogue] != AltosLib.MISSING)
524                                 System.out.printf("Drogue rate: %6.0f m/s  %6.0f ft/s\n",
525                                                   stats.state_speed[Altos.ao_flight_drogue],
526                                                   AltosConvert.meters_to_feet(stats.state_speed[Altos.ao_flight_drogue]));
527                         if (stats.state_speed[Altos.ao_flight_main] != AltosLib.MISSING)
528                                 System.out.printf("Main rate:   %6.0f m/s  %6.0f ft/s\n",
529                                                   stats.state_speed[Altos.ao_flight_main],
530                                                   AltosConvert.meters_to_feet(stats.state_speed[Altos.ao_flight_main]));
531                         if (stats.state_end[Altos.ao_flight_main] != AltosLib.MISSING &&
532                             stats.state_start[Altos.ao_flight_boost] != AltosLib.MISSING)
533                                 System.out.printf("Flight time: %6.0f s\n",
534                                                   stats.state_end[Altos.ao_flight_main] -
535                                                   stats.state_start[Altos.ao_flight_boost]);
536                         System.out.printf("\n");
537                         return true;
538                 } catch (InterruptedException ie) {
539                 } catch (IOException ie) {
540                 }
541                 return false;
542         }
543
544         static boolean process_cat(File file) {
545                 try {
546                         AltosStateIterable eef = record_iterable(file);
547
548                         for (AltosState state : eef) {
549                                 if ((state.set & AltosState.set_gps) != 0) {
550                                         System.out.printf ("time %d %d-%d-%d %d:%d:%d lat %g lon %g alt %g\n",
551                                                            state.gps.seconds(),
552                                                            state.gps.year,
553                                                            state.gps.month,
554                                                            state.gps.day,
555                                                            state.gps.hour,
556                                                            state.gps.minute,
557                                                            state.gps.second,
558                                                            state.gps.lat,
559                                                            state.gps.lon,
560                                                            state.gps.alt);
561                                 } else {
562                                         System.out.printf ("tick %d state %d height %g\n",
563                                                            state.tick, state.state(), state.height());
564                                 }
565                         }
566
567                 } catch (Exception e) {
568                         System.out.printf("Failed to open file '%s'\n", file);
569                         return false;
570                 }
571                 return true;
572         }
573
574         public static void help(int code) {
575                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
576                 System.out.printf("  Options:\n");
577                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
578                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
579                 System.out.printf("    --summary <filename>\t\tText summary of a flight\n");
580                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
581                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
582                 System.exit(code);
583         }
584
585         public static void main(final String[] args) {
586                 int     errors = 0;
587                 load_library(null);
588                 try {
589                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
590                 } catch (Exception e) {
591                 }
592                 AltosUI altosui = null;
593
594                 /* Handle batch-mode */
595                 if (args.length == 0) {
596                         altosui = new AltosUI();
597                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(Altos.product_basestation);
598                         if (devices != null)
599                                 for (AltosDevice device : devices)
600                                         altosui.telemetry_window(device);
601                 } else {
602                         int process = process_none;
603                         for (int i = 0; i < args.length; i++) {
604                                 if (args[i].equals("--help"))
605                                         help(0);
606                                 else if (args[i].equals("--replay"))
607                                         process = process_replay;
608                                 else if (args[i].equals("--kml"))
609                                         process = process_kml;
610                                 else if (args[i].equals("--csv"))
611                                         process = process_csv;
612                                 else if (args[i].equals("--graph"))
613                                         process = process_graph;
614                                 else if (args[i].equals("--summary"))
615                                         process = process_summary;
616                                 else if (args[i].equals("--cat"))
617                                         process = process_cat;
618                                 else if (args[i].startsWith("--"))
619                                         help(1);
620                                 else {
621                                         File file = new File(args[i]);
622                                         switch (process) {
623                                         case process_none:
624                                                 if (altosui == null)
625                                                         altosui = new AltosUI();
626                                         case process_graph:
627                                                 if (!process_graph(file))
628                                                         ++errors;
629                                                 break;
630                                         case process_replay:
631                                                 if (!process_replay(file))
632                                                         ++errors;
633                                                 break;
634                                         case process_kml:
635                                                 if (!process_kml(file))
636                                                         ++errors;
637                                                 break;
638                                         case process_csv:
639                                                 if (!process_csv(file))
640                                                         ++errors;
641                                                 break;
642                                         case process_summary:
643                                                 if (!process_summary(file))
644                                                         ++errors;
645                                                 break;
646                                         case process_cat:
647                                                 if (!process_cat(file))
648                                                         ++errors;
649                                         }
650                                 }
651                         }
652                 }
653                 if (errors != 0)
654                         System.exit(errors);
655         }
656 }