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