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