Merge branch 'scan-telemetry' into preload-maps
[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.LinkedBlockingQueue;
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                 }
71         }
72
73         Container       pane;
74         GridBagLayout   gridbag;
75
76         JButton addButton(int x, int y, String label) {
77                 GridBagConstraints      c;
78                 JButton                 b;
79
80                 c = new GridBagConstraints();
81                 c.gridx = x; c.gridy = y;
82                 c.fill = GridBagConstraints.BOTH;
83                 c.weightx = 1;
84                 c.weighty = 1;
85                 b = new JButton(label);
86
87                 Dimension ps = b.getPreferredSize();
88
89                 gridbag.setConstraints(b, c);
90                 add(b, c);
91                 return b;
92         }
93
94         public AltosUI() {
95
96                 load_library(null);
97
98                 java.net.URL imgURL = AltosUI.class.getResource("/altus-metrum-16x16.jpg");
99                 if (imgURL != null)
100                         setIconImage(new ImageIcon(imgURL).getImage());
101
102                 AltosPreferences.set_component(this);
103
104                 pane = getContentPane();
105                 gridbag = new GridBagLayout();
106                 pane.setLayout(gridbag);
107
108                 JButton b;
109
110                 b = addButton(0, 0, "Monitor Flight");
111                 b.addActionListener(new ActionListener() {
112                                         public void actionPerformed(ActionEvent e) {
113                                                 ConnectToDevice();
114                                         }
115                                 });
116                 b = addButton(1, 0, "Save Flight Data");
117                 b.addActionListener(new ActionListener() {
118                                         public void actionPerformed(ActionEvent e) {
119                                                 SaveFlightData();
120                                         }
121                                 });
122                 b = addButton(2, 0, "Replay Flight");
123                 b.addActionListener(new ActionListener() {
124                                         public void actionPerformed(ActionEvent e) {
125                                                 Replay();
126                                         }
127                                 });
128                 b = addButton(3, 0, "Graph Data");
129                 b.addActionListener(new ActionListener() {
130                                         public void actionPerformed(ActionEvent e) {
131                                                 GraphData();
132                                         }
133                                 });
134                 b = addButton(4, 0, "Export Data");
135                 b.addActionListener(new ActionListener() {
136                                         public void actionPerformed(ActionEvent e) {
137                                                 ExportData();
138                                         }
139                                 });
140                 b = addButton(0, 1, "Configure TeleMetrum");
141                 b.addActionListener(new ActionListener() {
142                                         public void actionPerformed(ActionEvent e) {
143                                                 ConfigureTeleMetrum();
144                                         }
145                                 });
146
147                 b = addButton(1, 1, "Configure AltosUI");
148                 b.addActionListener(new ActionListener() {
149                                 public void actionPerformed(ActionEvent e) {
150                                         ConfigureAltosUI();
151                                 }
152                         });
153
154                 b = addButton(2, 1, "Flash Image");
155                 b.addActionListener(new ActionListener() {
156                                 public void actionPerformed(ActionEvent e) {
157                                         FlashImage();
158                                 }
159                         });
160
161                 b = addButton(3, 1, "Fire Igniter");
162                 b.addActionListener(new ActionListener() {
163                                 public void actionPerformed(ActionEvent e) {
164                                         FireIgniter();
165                                 }
166                         });
167
168                 b = addButton(4, 1, "Quit");
169                 b.addActionListener(new ActionListener() {
170                                 public void actionPerformed(ActionEvent e) {
171                                         System.exit(0);
172                                 }
173                         });
174
175
176                 b = addButton(0, 2, "Scan Channels");
177                 b.addActionListener(new ActionListener() {
178                                 public void actionPerformed(ActionEvent e) {
179                                         ScanChannels();
180                                 }
181                         });
182
183                 b = addButton(1, 2, "Load Maps");
184                 b.addActionListener(new ActionListener() {
185                                 public void actionPerformed(ActionEvent e) {
186                                         LoadMaps();
187                                 }
188                         });
189
190                 setTitle("AltOS");
191
192                 pane.doLayout();
193                 pane.validate();
194
195                 doLayout();
196                 validate();
197
198                 setVisible(true);
199
200                 Insets i = getInsets();
201                 Dimension ps = rootPane.getPreferredSize();
202                 ps.width += i.left + i.right;
203                 ps.height += i.top + i.bottom;
204                 setPreferredSize(ps);
205                 setSize(ps);
206                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
207                 addWindowListener(new WindowAdapter() {
208                         @Override
209                         public void windowClosing(WindowEvent e) {
210                                 System.exit(0);
211                         }
212                 });
213         }
214
215         private void ConnectToDevice() {
216                 AltosDevice     device = AltosDeviceDialog.show(AltosUI.this,
217                                                                 Altos.product_basestation);
218
219                 if (device != null)
220                         telemetry_window(device);
221         }
222
223         void ConfigureCallsign() {
224                 String  result;
225                 result = JOptionPane.showInputDialog(AltosUI.this,
226                                                      "Configure Callsign",
227                                                      AltosPreferences.callsign());
228                 if (result != null)
229                         AltosPreferences.set_callsign(result);
230         }
231
232         void ConfigureTeleMetrum() {
233                 new AltosConfig(AltosUI.this);
234         }
235
236         void FlashImage() {
237                 AltosFlashUI.show(AltosUI.this);
238         }
239
240         void FireIgniter() {
241                 new AltosIgniteUI(AltosUI.this);
242         }
243
244         void ScanChannels() {
245                 new AltosScanUI(AltosUI.this);
246         }
247
248         void LoadMaps() {
249                 new AltosSiteMapPreload(AltosUI.this);
250         }
251
252         /*
253          * Replay a flight from telemetry data
254          */
255         private void Replay() {
256                 AltosDataChooser chooser = new AltosDataChooser(
257                         AltosUI.this);
258
259                 AltosRecordIterable iterable = chooser.runDialog();
260                 if (iterable != null) {
261                         AltosFlightReader reader = new AltosReplayReader(iterable.iterator(),
262                                                                          chooser.filename());
263                         new AltosFlightUI(voice, reader);
264                 }
265         }
266
267         /* Connect to TeleMetrum, either directly or through
268          * a TeleDongle over the packet link
269          */
270         private void SaveFlightData() {
271                 new AltosEepromManage(AltosUI.this);
272         }
273
274         /* Load a flight log file and write out a CSV file containing
275          * all of the data in standard units
276          */
277
278         private void ExportData() {
279                 AltosDataChooser chooser;
280                 chooser = new AltosDataChooser(this);
281                 AltosRecordIterable record_reader = chooser.runDialog();
282                 if (record_reader == null)
283                         return;
284                 new AltosCSVUI(AltosUI.this, record_reader, chooser.file());
285         }
286
287         /* Load a flight log CSV file and display a pretty graph.
288          */
289
290         private void GraphData() {
291                 AltosDataChooser chooser;
292                 chooser = new AltosDataChooser(this);
293                 AltosRecordIterable record_reader = chooser.runDialog();
294                 if (record_reader == null)
295                         return;
296                 new AltosGraphUI(record_reader);
297         }
298
299         private void ConfigureAltosUI() {
300                 new AltosConfigureUI(AltosUI.this, voice);
301         }
302
303         static AltosRecordIterable open_logfile(String filename) {
304                 File file = new File (filename);
305                 try {
306                         FileInputStream in;
307
308                         in = new FileInputStream(file);
309                         if (filename.endsWith("eeprom"))
310                                 return new AltosEepromIterable(in);
311                         else
312                                 return new AltosTelemetryIterable(in);
313                 } catch (FileNotFoundException fe) {
314                         System.out.printf("Cannot open '%s'\n", filename);
315                         return null;
316                 }
317         }
318
319         static AltosWriter open_csv(String filename) {
320                 File file = new File (filename);
321                 try {
322                         return new AltosCSV(file);
323                 } catch (FileNotFoundException fe) {
324                         System.out.printf("Cannot open '%s'\n", filename);
325                         return null;
326                 }
327         }
328
329         static AltosWriter open_kml(String filename) {
330                 File file = new File (filename);
331                 try {
332                         return new AltosKML(file);
333                 } catch (FileNotFoundException fe) {
334                         System.out.printf("Cannot open '%s'\n", filename);
335                         return null;
336                 }
337         }
338
339         static final int process_csv = 1;
340         static final int process_kml = 2;
341
342         static void process_file(String input, int process) {
343                 AltosRecordIterable iterable = open_logfile(input);
344                 if (iterable == null)
345                         return;
346                 if (process == 0)
347                         process = process_csv;
348                 if ((process & process_csv) != 0) {
349                         String output = Altos.replace_extension(input,".csv");
350                         System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
351                         if (input.equals(output)) {
352                                 System.out.printf("Not processing '%s'\n", input);
353                         } else {
354                                 AltosWriter writer = open_csv("/dev/stdout");
355                                 if (writer != null) {
356                                         writer.write(iterable);
357                                         writer.close();
358                                 }
359                         }
360                 }
361                 if ((process & process_kml) != 0) {
362                         String output = Altos.replace_extension(input,".kml");
363                         System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
364                         if (input.equals(output)) {
365                                 System.out.printf("Not processing '%s'\n", input);
366                         } else {
367                                 AltosWriter writer = open_kml(output);
368                                 if (writer == null)
369                                         return;
370                                 writer.write(iterable);
371                                 writer.close();
372                         }
373                 }
374         }
375
376         public static void main(final String[] args) {
377                 int     process = 0;
378                 /* Handle batch-mode */
379         if (args.length == 1 && args[0].equals("--help")) {
380                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
381                 System.out.printf("  Options:\n");
382                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
383                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
384                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
385                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
386         } else if (args.length == 3 && args[0].equals("--fetchmaps")) {
387             double lat = Double.parseDouble(args[1]);
388             double lon = Double.parseDouble(args[2]);
389             AltosSiteMap.prefetchMaps(lat, lon, 5, 5);
390         } else if (args.length == 2 && args[0].equals("--replay")) {
391                         String filename = args[1];
392                         FileInputStream in;
393                         try {
394                                 in = new FileInputStream(filename);
395                         } catch (Exception e) {
396                                 System.out.printf("Failed to open file '%s'\n", filename);
397                                 return;
398                         }
399                         AltosRecordIterable recs;
400                         AltosReplayReader reader;
401                         if (filename.endsWith("eeprom")) {
402                                 recs = new AltosEepromIterable(in);
403                         } else {
404                                 recs = new AltosTelemetryIterable(in);
405                         }
406                         reader = new AltosReplayReader(recs.iterator(), filename);
407                         AltosFlightUI flight_ui = new AltosFlightUI(new AltosVoice(), reader);
408                         flight_ui.set_exit_on_close();
409                         return;
410                 } else if (args.length > 0) {
411                         for (int i = 0; i < args.length; i++) {
412                                 if (args[i].equals("--kml"))
413                                         process |= process_kml;
414                                 else if (args[i].equals("--csv"))
415                                         process |= process_csv;
416                                 else
417                                         process_file(args[i], process);
418                         }
419                 } else {
420                         AltosUI altosui = new AltosUI();
421                         altosui.setVisible(true);
422
423                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(Altos.product_basestation);
424                         for (AltosDevice device : devices)
425                                 altosui.telemetry_window(device);
426                 }
427         }
428 }