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