62e612ed07d0fc9282e00e9ab0910f7951db6a6b
[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_csv = 1;
368         static final int process_kml = 2;
369
370         static void process_file(String input, int process) {
371                 AltosRecordIterable iterable = open_logfile(input);
372                 if (iterable == null)
373                         return;
374                 if (process == 0)
375                         process = process_csv;
376                 if ((process & process_csv) != 0) {
377                         String output = Altos.replace_extension(input,".csv");
378                         System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
379                         if (input.equals(output)) {
380                                 System.out.printf("Not processing '%s'\n", input);
381                         } else {
382                                 AltosWriter writer = open_csv("/dev/stdout");
383                                 if (writer != null) {
384                                         writer.write(iterable);
385                                         writer.close();
386                                 }
387                         }
388                 }
389                 if ((process & process_kml) != 0) {
390                         String output = Altos.replace_extension(input,".kml");
391                         System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
392                         if (input.equals(output)) {
393                                 System.out.printf("Not processing '%s'\n", input);
394                         } else {
395                                 AltosWriter writer = open_kml(output);
396                                 if (writer == null)
397                                         return;
398                                 writer.write(iterable);
399                                 writer.close();
400                         }
401                 }
402         }
403
404         public static void main(final String[] args) {
405                 int     process = 0;
406                 /* Handle batch-mode */
407         if (args.length == 1 && args[0].equals("--help")) {
408                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
409                 System.out.printf("  Options:\n");
410                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
411                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
412                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
413                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
414         } else if (args.length == 3 && args[0].equals("--fetchmaps")) {
415             double lat = Double.parseDouble(args[1]);
416             double lon = Double.parseDouble(args[2]);
417             AltosSiteMap.prefetchMaps(lat, lon, 5, 5);
418         } else if (args.length == 2 && args[0].equals("--replay")) {
419                         String filename = args[1];
420                         FileInputStream in;
421                         try {
422                                 in = new FileInputStream(filename);
423                         } catch (Exception e) {
424                                 System.out.printf("Failed to open file '%s'\n", filename);
425                                 return;
426                         }
427                         AltosRecordIterable recs;
428                         AltosReplayReader reader;
429                         if (filename.endsWith("eeprom")) {
430                                 recs = new AltosEepromIterable(in);
431                         } else {
432                                 recs = new AltosTelemetryIterable(in);
433                         }
434                         reader = new AltosReplayReader(recs.iterator(), new File(filename));
435                         AltosFlightUI flight_ui = new AltosFlightUI(new AltosVoice(), reader);
436                         flight_ui.set_exit_on_close();
437                         return;
438                 } else if (args.length > 0) {
439                         for (int i = 0; i < args.length; i++) {
440                                 if (args[i].equals("--kml"))
441                                         process |= process_kml;
442                                 else if (args[i].equals("--csv"))
443                                         process |= process_csv;
444                                 else
445                                         process_file(args[i], process);
446                         }
447                 } else {
448                         AltosUI altosui = new AltosUI();
449                         altosui.setVisible(true);
450
451                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(Altos.product_basestation);
452                         for (AltosDevice device : devices)
453                                 altosui.telemetry_window(device);
454                 }
455         }
456 }