altosui: Clean up command line processing. Add --graph
[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 = addButton(1, 0, "Save Flight Data");
127                 b.addActionListener(new ActionListener() {
128                                         public void actionPerformed(ActionEvent e) {
129                                                 SaveFlightData();
130                                         }
131                                 });
132                 b = addButton(2, 0, "Replay Flight");
133                 b.addActionListener(new ActionListener() {
134                                         public void actionPerformed(ActionEvent e) {
135                                                 Replay();
136                                         }
137                                 });
138                 b = addButton(3, 0, "Graph Data");
139                 b.addActionListener(new ActionListener() {
140                                         public void actionPerformed(ActionEvent e) {
141                                                 GraphData();
142                                         }
143                                 });
144                 b = addButton(4, 0, "Export Data");
145                 b.addActionListener(new ActionListener() {
146                                         public void actionPerformed(ActionEvent e) {
147                                                 ExportData();
148                                         }
149                                 });
150                 b = addButton(0, 1, "Configure Altimeter");
151                 b.addActionListener(new ActionListener() {
152                                         public void actionPerformed(ActionEvent e) {
153                                                 ConfigureTeleMetrum();
154                                         }
155                                 });
156
157                 b = addButton(1, 1, "Configure AltosUI");
158                 b.addActionListener(new ActionListener() {
159                                 public void actionPerformed(ActionEvent e) {
160                                         ConfigureAltosUI();
161                                 }
162                         });
163
164                 b = addButton(2, 1, "Flash Image");
165                 b.addActionListener(new ActionListener() {
166                                 public void actionPerformed(ActionEvent e) {
167                                         FlashImage();
168                                 }
169                         });
170
171                 b = addButton(3, 1, "Fire Igniter");
172                 b.addActionListener(new ActionListener() {
173                                 public void actionPerformed(ActionEvent e) {
174                                         FireIgniter();
175                                 }
176                         });
177
178                 b = addButton(4, 1, "Quit");
179                 b.addActionListener(new ActionListener() {
180                                 public void actionPerformed(ActionEvent e) {
181                                         System.exit(0);
182                                 }
183                         });
184
185
186                 b = addButton(0, 2, "Scan Channels");
187                 b.addActionListener(new ActionListener() {
188                                 public void actionPerformed(ActionEvent e) {
189                                         ScanChannels();
190                                 }
191                         });
192
193                 b = addButton(1, 2, "Load Maps");
194                 b.addActionListener(new ActionListener() {
195                                 public void actionPerformed(ActionEvent e) {
196                                         LoadMaps();
197                                 }
198                         });
199
200                 b = addButton(2, 2, "Monitor Idle");
201                 b.addActionListener(new ActionListener() {
202                                 public void actionPerformed(ActionEvent e) {
203                                         IdleMonitor();
204                                 }
205                         });
206
207                 setTitle("AltOS");
208
209                 pane.doLayout();
210                 pane.validate();
211
212                 doLayout();
213                 validate();
214
215                 setVisible(true);
216
217                 Insets i = getInsets();
218                 Dimension ps = rootPane.getPreferredSize();
219                 ps.width += i.left + i.right;
220                 ps.height += i.top + i.bottom;
221                 setPreferredSize(ps);
222                 setSize(ps);
223                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
224                 addWindowListener(new WindowAdapter() {
225                         @Override
226                         public void windowClosing(WindowEvent e) {
227                                 System.exit(0);
228                         }
229                 });
230         }
231
232         private void ConnectToDevice() {
233                 AltosDevice     device = AltosDeviceDialog.show(AltosUI.this,
234                                                                 Altos.product_basestation);
235
236                 if (device != null)
237                         telemetry_window(device);
238         }
239
240         void ConfigureCallsign() {
241                 String  result;
242                 result = JOptionPane.showInputDialog(AltosUI.this,
243                                                      "Configure Callsign",
244                                                      AltosPreferences.callsign());
245                 if (result != null)
246                         AltosPreferences.set_callsign(result);
247         }
248
249         void ConfigureTeleMetrum() {
250                 new AltosConfig(AltosUI.this);
251         }
252
253         void FlashImage() {
254                 AltosFlashUI.show(AltosUI.this);
255         }
256
257         void FireIgniter() {
258                 new AltosIgniteUI(AltosUI.this);
259         }
260
261         void ScanChannels() {
262                 new AltosScanUI(AltosUI.this);
263         }
264
265         void LoadMaps() {
266                 new AltosSiteMapPreload(AltosUI.this);
267         }
268
269         /*
270          * Replay a flight from telemetry data
271          */
272         private void Replay() {
273                 AltosDataChooser chooser = new AltosDataChooser(
274                         AltosUI.this);
275
276                 AltosRecordIterable iterable = chooser.runDialog();
277                 if (iterable != null) {
278                         AltosFlightReader reader = new AltosReplayReader(iterable.iterator(),
279                                                                          chooser.file());
280                         new AltosFlightUI(voice, reader);
281                 }
282         }
283
284         /* Connect to TeleMetrum, either directly or through
285          * a TeleDongle over the packet link
286          */
287         private void SaveFlightData() {
288                 new AltosEepromManage(AltosUI.this);
289         }
290
291         /* Load a flight log file and write out a CSV file containing
292          * all of the data in standard units
293          */
294
295         private void ExportData() {
296                 AltosDataChooser chooser;
297                 chooser = new AltosDataChooser(this);
298                 AltosRecordIterable record_reader = chooser.runDialog();
299                 if (record_reader == null)
300                         return;
301                 new AltosCSVUI(AltosUI.this, record_reader, chooser.file());
302         }
303
304         /* Load a flight log CSV file and display a pretty graph.
305          */
306
307         private void GraphData() {
308                 AltosDataChooser chooser;
309                 chooser = new AltosDataChooser(this);
310                 AltosRecordIterable record_reader = chooser.runDialog();
311                 if (record_reader == null)
312                         return;
313                 try {
314                         new AltosGraphUI(record_reader);
315                 } catch (InterruptedException ie) {
316                 } catch (IOException ie) {
317                 }
318         }
319
320         private void ConfigureAltosUI() {
321                 new AltosConfigureUI(AltosUI.this, voice);
322         }
323
324         private void IdleMonitor() {
325                 try {
326                         new AltosIdleMonitorUI(this);
327                 } catch (Exception e) {
328                 }
329         }
330
331         static AltosRecordIterable open_logfile(String filename) {
332                 File file = new File (filename);
333                 try {
334                         FileInputStream in;
335
336                         in = new FileInputStream(file);
337                         if (filename.endsWith("eeprom"))
338                                 return new AltosEepromIterable(in);
339                         else
340                                 return new AltosTelemetryIterable(in);
341                 } catch (FileNotFoundException fe) {
342                         System.out.printf("Cannot open '%s'\n", filename);
343                         return null;
344                 }
345         }
346
347         static AltosWriter open_csv(String filename) {
348                 File file = new File (filename);
349                 try {
350                         return new AltosCSV(file);
351                 } catch (FileNotFoundException fe) {
352                         System.out.printf("Cannot open '%s'\n", filename);
353                         return null;
354                 }
355         }
356
357         static AltosWriter open_kml(String filename) {
358                 File file = new File (filename);
359                 try {
360                         return new AltosKML(file);
361                 } catch (FileNotFoundException fe) {
362                         System.out.printf("Cannot open '%s'\n", filename);
363                         return null;
364                 }
365         }
366
367         static final int process_none = 0;
368         static final int process_csv = 1;
369         static final int process_kml = 2;
370         static final int process_graph = 3;
371         static final int process_replay = 4;
372
373         static void process_csv(String input) {
374                 AltosRecordIterable iterable = open_logfile(input);
375                 if (iterable == null)
376                         return;
377
378                 String output = Altos.replace_extension(input,".csv");
379                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
380                 if (input.equals(output)) {
381                         System.out.printf("Not processing '%s'\n", input);
382                 } else {
383                         AltosWriter writer = open_csv(output);
384                         if (writer == null)
385                                 return;
386                         writer.write(iterable);
387                         writer.close();
388                 }
389         }
390
391         static void process_kml(String input) {
392                 AltosRecordIterable iterable = open_logfile(input);
393                 if (iterable == null)
394                         return;
395
396                 String output = Altos.replace_extension(input,".kml");
397                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
398                 if (input.equals(output)) {
399                         System.out.printf("Not processing '%s'\n", input);
400                 } else {
401                         AltosWriter writer = open_kml(output);
402                         if (writer == null)
403                                 return;
404                         writer.write(iterable);
405                         writer.close();
406                 }
407         }
408
409         static void process_replay(String filename) {
410                 FileInputStream in;
411                 try {
412                         in = new FileInputStream(filename);
413                 } catch (Exception e) {
414                         System.out.printf("Failed to open file '%s'\n", filename);
415                         return;
416                 }
417                 AltosRecordIterable recs;
418                 AltosReplayReader reader;
419                 if (filename.endsWith("eeprom")) {
420                         recs = new AltosEepromIterable(in);
421                 } else {
422                         recs = new AltosTelemetryIterable(in);
423                 }
424                 reader = new AltosReplayReader(recs.iterator(), new File(filename));
425                 AltosFlightUI flight_ui = new AltosFlightUI(new AltosVoice(), reader);
426                 flight_ui.set_exit_on_close();
427         }
428
429         static void process_graph(String filename) {
430                 FileInputStream in;
431                 try {
432                         in = new FileInputStream(filename);
433                 } catch (Exception e) {
434                         System.out.printf("Failed to open file '%s'\n", filename);
435                         return;
436                 }
437                 AltosRecordIterable recs;
438                 if (filename.endsWith("eeprom")) {
439                         recs = new AltosEepromIterable(in);
440                 } else {
441                         recs = new AltosTelemetryIterable(in);
442                 }
443                 try {
444                         new AltosGraphUI(recs);
445                 } catch (InterruptedException ie) {
446                 } catch (IOException ie) {
447                 }
448         }
449         
450         public static void help(int code) {
451                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
452                 System.out.printf("  Options:\n");
453                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
454                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
455                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
456                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
457                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
458                 System.exit(code);
459         }
460         
461         public static void main(final String[] args) {
462                 /* Handle batch-mode */
463                 if (args.length == 0) {
464                         AltosUI altosui = new AltosUI();
465                         altosui.setVisible(true);
466
467                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(Altos.product_basestation);
468                         for (AltosDevice device : devices)
469                                 altosui.telemetry_window(device);
470                 } else {
471                         int process = process_none;
472                         for (int i = 0; i < args.length; i++) {
473                                 if (args[i].equals("--help"))
474                                         help(0);
475                                 else if (args[i].equals("--fetchmaps")) {
476                                         if (args.length < i + 3) {
477                                                 help(1);
478                                         } else {
479                                                 double lat = Double.parseDouble(args[i+1]);
480                                                 double lon = Double.parseDouble(args[i+2]);
481                                                 AltosSiteMap.prefetchMaps(lat, lon, 5, 5);
482                                                 i += 2;
483                                         }
484                                 } else if (args[i].equals("--replay"))
485                                         process = process_replay;
486                                 else if (args[i].equals("--kml"))
487                                         process = process_kml;
488                                 else if (args[i].equals("--csv"))
489                                         process = process_csv;
490                                 else if (args[i].equals("--graph"))
491                                         process = process_graph;
492                                 else if (args[i].startsWith("--"))
493                                         help(1);
494                                 else {
495                                         switch (process) {
496                                         case process_none:
497                                         case process_graph:
498                                                 process_graph(args[i]);
499                                                 break;
500                                         case process_replay:
501                                                 process_replay(args[i]);
502                                                 break;
503                                         case process_kml:
504                                                 process_kml(args[i]);
505                                                 break;
506                                         case process_csv:
507                                                 process_csv(args[i]);
508                                                 break;
509                                         }
510                                 }
511                         }
512                 }
513         }
514 }