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