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