3aaeb888380c5400caed334476238da980e166a6
[fw/altos] / ao-tools / 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 altosui.Altos;
32 import altosui.AltosSerial;
33 import altosui.AltosSerialMonitor;
34 import altosui.AltosRecord;
35 import altosui.AltosTelemetry;
36 import altosui.AltosState;
37 import altosui.AltosDeviceDialog;
38 import altosui.AltosPreferences;
39 import altosui.AltosLog;
40 import altosui.AltosVoice;
41 import altosui.AltosFlightStatusTableModel;
42 import altosui.AltosFlightInfoTableModel;
43 import altosui.AltosChannelMenu;
44 import altosui.AltosFlashUI;
45 import altosui.AltosLogfileChooser;
46 import altosui.AltosCSVUI;
47 import altosui.AltosLine;
48
49 import libaltosJNI.*;
50
51 public class AltosUI extends JFrame {
52         private int channel = -1;
53
54         private AltosFlightStatusTableModel flightStatusModel;
55         private JTable flightStatus;
56
57         static final int info_columns = 3;
58
59         private AltosFlightInfoTableModel[] flightInfoModel;
60         private JTable[] flightInfo;
61         private AltosSerial serial_line;
62         private AltosLog altos_log;
63         private Box[] ibox;
64         private Box vbox;
65         private Box hbox;
66
67         private Font statusFont = new Font("SansSerif", Font.BOLD, 24);
68         private Font infoLabelFont = new Font("SansSerif", Font.PLAIN, 14);
69         private Font infoValueFont = new Font("Monospaced", Font.PLAIN, 14);
70
71         public AltosVoice voice = new AltosVoice();
72
73         public AltosUI() {
74
75                 String[] statusNames = { "Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
76                 Object[][] statusData = { { "0", "pad", "-50", "0" } };
77
78                 java.net.URL imgURL = AltosUI.class.getResource("/altus-metrum-16x16.jpg");
79                 if (imgURL != null)
80                         setIconImage(new ImageIcon(imgURL).getImage());
81
82                 AltosPreferences.init(this);
83
84                 vbox = Box.createVerticalBox();
85                 this.add(vbox);
86
87                 flightStatusModel = new AltosFlightStatusTableModel();
88                 flightStatus = new JTable(flightStatusModel);
89                 flightStatus.setFont(statusFont);
90                 TableColumnModel tcm = flightStatus.getColumnModel();
91                 for (int i = 0; i < flightStatusModel.getColumnCount(); i++) {
92                         DefaultTableCellRenderer       r = new DefaultTableCellRenderer();
93                         r.setFont(statusFont);
94                         r.setHorizontalAlignment(SwingConstants.CENTER);
95                         tcm.getColumn(i).setCellRenderer(r);
96                 }
97
98                 FontMetrics     statusMetrics = flightStatus.getFontMetrics(statusFont);
99                 int statusHeight = (statusMetrics.getHeight() + statusMetrics.getLeading()) * 15 / 10;
100                 flightStatus.setRowHeight(statusHeight);
101                 flightStatus.setShowGrid(false);
102
103                 vbox.add(flightStatus);
104
105                 hbox = Box.createHorizontalBox();
106                 vbox.add(hbox);
107
108                 flightInfo = new JTable[3];
109                 flightInfoModel = new AltosFlightInfoTableModel[3];
110                 ibox = new Box[3];
111                 FontMetrics     infoValueMetrics = flightStatus.getFontMetrics(infoValueFont);
112                 int infoHeight = (infoValueMetrics.getHeight() + infoValueMetrics.getLeading()) * 20 / 10;
113
114                 for (int i = 0; i < info_columns; i++) {
115                         ibox[i] = Box.createVerticalBox();
116                         flightInfoModel[i] = new AltosFlightInfoTableModel();
117                         flightInfo[i] = new JTable(flightInfoModel[i]);
118                         flightInfo[i].setFont(infoValueFont);
119                         flightInfo[i].setRowHeight(infoHeight);
120                         flightInfo[i].setShowGrid(true);
121                         ibox[i].add(flightInfo[i].getTableHeader());
122                         ibox[i].add(flightInfo[i]);
123                         hbox.add(ibox[i]);
124                 }
125
126                 setTitle("AltOS");
127
128                 createMenu();
129
130                 serial_line = new AltosSerial();
131                 altos_log = new AltosLog(serial_line);
132                 int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
133                 this.setSize(new Dimension (infoValueMetrics.charWidth('0') * 6 * 20,
134                                             statusHeight * 4 + infoHeight * 17));
135                 this.validate();
136                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
137                 addWindowListener(new WindowAdapter() {
138                         @Override
139                         public void windowClosing(WindowEvent e) {
140                                 System.exit(0);
141                         }
142                 });
143                 voice.speak("Rocket flight monitor ready.");
144         }
145
146         public void info_reset() {
147                 for (int i = 0; i < info_columns; i++)
148                         flightInfoModel[i].resetRow();
149         }
150
151         public void info_add_row(int col, String name, String value) {
152                 flightInfoModel[col].addRow(name, value);
153         }
154
155         public void info_add_row(int col, String name, String format, Object... parameters) {
156                 flightInfoModel[col].addRow(name, String.format(format, parameters));
157         }
158
159         public void info_add_deg(int col, String name, double v, int pos, int neg) {
160                 int     c = pos;
161                 if (v < 0) {
162                         c = neg;
163                         v = -v;
164                 }
165                 double  deg = Math.floor(v);
166                 double  min = (v - deg) * 60;
167
168                 flightInfoModel[col].addRow(name, String.format("%3.0f°%08.5f'", deg, min));
169         }
170
171         public void info_finish() {
172                 for (int i = 0; i < info_columns; i++)
173                         flightInfoModel[i].finish();
174         }
175
176         public void show(AltosState state, int crc_errors) {
177                 if (state == null)
178                         return;
179                 flightStatusModel.set(state);
180
181                 info_reset();
182                 info_add_row(0, "Rocket state", "%s", state.data.state());
183                 info_add_row(0, "Callsign", "%s", state.data.callsign);
184                 info_add_row(0, "Rocket serial", "%6d", state.data.serial);
185                 info_add_row(0, "Rocket flight", "%6d", state.data.flight);
186
187                 info_add_row(0, "RSSI", "%6d    dBm", state.data.rssi);
188                 info_add_row(0, "CRC Errors", "%6d", crc_errors);
189                 info_add_row(0, "Height", "%6.0f    m", state.height);
190                 info_add_row(0, "Max height", "%6.0f    m", state.max_height);
191                 info_add_row(0, "Acceleration", "%8.1f  m/s²", state.acceleration);
192                 info_add_row(0, "Max acceleration", "%8.1f  m/s²", state.max_acceleration);
193                 info_add_row(0, "Speed", "%8.1f  m/s", state.ascent ? state.speed : state.baro_speed);
194                 info_add_row(0, "Max Speed", "%8.1f  m/s", state.max_speed);
195                 info_add_row(0, "Temperature", "%9.2f °C", state.temperature);
196                 info_add_row(0, "Battery", "%9.2f V", state.battery);
197                 info_add_row(0, "Drogue", "%9.2f V", state.drogue_sense);
198                 info_add_row(0, "Main", "%9.2f V", state.main_sense);
199                 info_add_row(0, "Pad altitude", "%6.0f    m", state.ground_altitude);
200                 if (state.gps == null) {
201                         info_add_row(1, "GPS", "not available");
202                 } else {
203                         if (state.gps_ready)
204                                 info_add_row(1, "GPS state", "%s", "ready");
205                         else
206                                 info_add_row(1, "GPS state", "wait (%d)",
207                                              state.gps_waiting);
208                         if (state.data.gps.locked)
209                                 info_add_row(1, "GPS", "   locked");
210                         else if (state.data.gps.connected)
211                                 info_add_row(1, "GPS", " unlocked");
212                         else
213                                 info_add_row(1, "GPS", "  missing");
214                         info_add_row(1, "Satellites", "%6d", state.data.gps.nsat);
215                         info_add_deg(1, "Latitude", state.gps.lat, 'N', 'S');
216                         info_add_deg(1, "Longitude", state.gps.lon, 'E', 'W');
217                         info_add_row(1, "GPS altitude", "%6d", state.gps.alt);
218                         info_add_row(1, "GPS height", "%6.0f", state.gps_height);
219
220                         /* The SkyTraq GPS doesn't report these values */
221                         if (false) {
222                                 info_add_row(1, "GPS ground speed", "%8.1f m/s %3d°",
223                                              state.gps.ground_speed,
224                                              state.gps.course);
225                                 info_add_row(1, "GPS climb rate", "%8.1f m/s",
226                                              state.gps.climb_rate);
227                                 info_add_row(1, "GPS error", "%6d m(h)%3d m(v)",
228                                              state.gps.h_error, state.gps.v_error);
229                         }
230                         info_add_row(1, "GPS hdop", "%8.1f", state.gps.hdop);
231
232                         if (state.npad > 0) {
233                                 if (state.from_pad != null) {
234                                         info_add_row(1, "Distance from pad", "%6d m",
235                                                      (int) (state.from_pad.distance + 0.5));
236                                         info_add_row(1, "Direction from pad", "%6d°",
237                                                      (int) (state.from_pad.bearing + 0.5));
238                                         info_add_row(1, "Elevation from pad", "%6d°",
239                                                      (int) (state.elevation + 0.5));
240                                         info_add_row(1, "Range from pad", "%6d m",
241                                                      (int) (state.range + 0.5));
242                                 } else {
243                                         info_add_row(1, "Distance from pad", "unknown");
244                                         info_add_row(1, "Direction from pad", "unknown");
245                                         info_add_row(1, "Elevation from pad", "unknown");
246                                         info_add_row(1, "Range from pad", "unknown");
247                                 }
248                                 info_add_deg(1, "Pad latitude", state.pad_lat, 'N', 'S');
249                                 info_add_deg(1, "Pad longitude", state.pad_lon, 'E', 'W');
250                                 info_add_row(1, "Pad GPS alt", "%6.0f m", state.pad_alt);
251                         }
252                         info_add_row(1, "GPS date", "%04d-%02d-%02d",
253                                        state.gps.year,
254                                        state.gps.month,
255                                        state.gps.day);
256                         info_add_row(1, "GPS time", "  %02d:%02d:%02d",
257                                        state.gps.hour,
258                                        state.gps.minute,
259                                        state.gps.second);
260                         int     nsat_vis = 0;
261                         int     c;
262
263                         if (state.gps.cc_gps_sat == null)
264                                 info_add_row(2, "Satellites Visible", "%4d", 0);
265                         else {
266                                 info_add_row(2, "Satellites Visible", "%4d", state.gps.cc_gps_sat.length);
267                                 for (c = 0; c < state.gps.cc_gps_sat.length; c++) {
268                                         info_add_row(2, "Satellite id,C/N0",
269                                                      "%4d, %4d",
270                                                      state.gps.cc_gps_sat[c].svid,
271                                                      state.gps.cc_gps_sat[c].c_n0);
272                                 }
273                         }
274                 }
275                 info_finish();
276         }
277
278         class IdleThread extends Thread {
279
280                 boolean started;
281                 private AltosState state;
282                 int     reported_landing;
283                 int     report_interval;
284                 long    report_time;
285
286                 public synchronized void report(boolean last) {
287                         if (state == null)
288                                 return;
289
290                         /* reset the landing count once we hear about a new flight */
291                         if (state.state < Altos.ao_flight_drogue)
292                                 reported_landing = 0;
293
294                         /* Shut up once the rocket is on the ground */
295                         if (reported_landing > 2) {
296                                 return;
297                         }
298
299                         /* If the rocket isn't on the pad, then report height */
300                         if (Altos.ao_flight_drogue <= state.state &&
301                             state.state < Altos.ao_flight_landed &&
302                             state.range >= 0)
303                         {
304                                 voice.speak("Height %d, bearing %d, elevation %d, range %d.\n",
305                                             (int) (state.height + 0.5),
306                                             (int) (state.from_pad.bearing + 0.5),
307                                             (int) (state.elevation + 0.5),
308                                             (int) (state.range + 0.5));
309                         } else if (state.state > Altos.ao_flight_pad) {
310                                 voice.speak("%d meters", (int) (state.height + 0.5));
311                         } else {
312                                 reported_landing = 0;
313                         }
314
315                         /* If the rocket is coming down, check to see if it has landed;
316                          * either we've got a landed report or we haven't heard from it in
317                          * a long time
318                          */
319                         if (state.state >= Altos.ao_flight_drogue &&
320                             (last ||
321                              System.currentTimeMillis() - state.report_time >= 15000 ||
322                              state.state == Altos.ao_flight_landed))
323                         {
324                                 if (Math.abs(state.baro_speed) < 20 && state.height < 100)
325                                         voice.speak("rocket landed safely");
326                                 else
327                                         voice.speak("rocket may have crashed");
328                                 if (state.from_pad != null)
329                                         voice.speak("Bearing %d degrees, range %d meters.",
330                                                     (int) (state.from_pad.bearing + 0.5),
331                                                     (int) (state.from_pad.distance + 0.5));
332                                 ++reported_landing;
333                         }
334                 }
335
336                 long now () {
337                         return System.currentTimeMillis();
338                 }
339
340                 void set_report_time() {
341                         report_time = now() + report_interval;
342                 }
343
344                 public void run () {
345
346                         reported_landing = 0;
347                         state = null;
348                         report_interval = 10000;
349                         try {
350                                 for (;;) {
351                                         set_report_time();
352                                         for (;;) {
353                                                 voice.drain();
354                                                 synchronized (this) {
355                                                         long    sleep_time = report_time - now();
356                                                         if (sleep_time <= 0)
357                                                                 break;
358                                                         wait(sleep_time);
359                                                 }
360                                         }
361                                         report(false);
362                                 }
363                         } catch (InterruptedException ie) {
364                                 try {
365                                         voice.drain();
366                                 } catch (InterruptedException iie) { }
367                         }
368                 }
369
370                 public synchronized void notice(AltosState new_state, boolean spoken) {
371                         AltosState old_state = state;
372                         state = new_state;
373                         if (!started && state.state > Altos.ao_flight_pad) {
374                                 started = true;
375                                 start();
376                         }
377
378                         if (state.state < Altos.ao_flight_drogue)
379                                 report_interval = 10000;
380                         else
381                                 report_interval = 20000;
382                         if (old_state != null && old_state.state != state.state) {
383                                 report_time = now();
384                                 this.notify();
385                         } else if (spoken)
386                                 set_report_time();
387                 }
388         }
389
390         private boolean tell(AltosState state, AltosState old_state) {
391                 boolean ret = false;
392                 if (old_state == null || old_state.state != state.state) {
393                         voice.speak(state.data.state());
394                         if ((old_state == null || old_state.state <= Altos.ao_flight_boost) &&
395                             state.state > Altos.ao_flight_boost) {
396                                 voice.speak("max speed: %d meters per second.",
397                                             (int) (state.max_speed + 0.5));
398                                 ret = true;
399                         } else if ((old_state == null || old_state.state < Altos.ao_flight_drogue) &&
400                                    state.state >= Altos.ao_flight_drogue) {
401                                 voice.speak("max height: %d meters.",
402                                             (int) (state.max_height + 0.5));
403                                 ret = true;
404                         }
405                 }
406                 if (old_state == null || old_state.gps_ready != state.gps_ready) {
407                         if (state.gps_ready) {
408                                 voice.speak("GPS ready");
409                                 ret = true;
410                         }
411                         else if (old_state != null) {
412                                 voice.speak("GPS lost");
413                                 ret = true;
414                         }
415                 }
416                 old_state = state;
417                 return ret;
418         }
419
420         class DisplayThread extends Thread {
421                 IdleThread      idle_thread;
422
423                 String          name;
424
425                 int             crc_errors;
426
427                 void init() { }
428
429                 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException { return null; }
430
431                 void close(boolean interrupted) { }
432
433                 void update(AltosState state) throws InterruptedException { }
434
435                 public void run() {
436                         boolean         interrupted = false;
437                         String          line;
438                         AltosState      state = null;
439                         AltosState      old_state = null;
440                         boolean         told;
441
442                         idle_thread = new IdleThread();
443
444                         info_reset();
445                         info_finish();
446                         try {
447                                 for (;;) {
448                                         try {
449                                                 AltosRecord record = read();
450                                                 if (record == null)
451                                                         break;
452                                                 old_state = state;
453                                                 state = new AltosState(record, state);
454                                                 update(state);
455                                                 show(state, crc_errors);
456                                                 told = tell(state, old_state);
457                                                 idle_thread.notice(state, told);
458                                         } catch (ParseException pp) {
459                                                 System.out.printf("Parse error: %d \"%s\"\n", pp.getErrorOffset(), pp.getMessage());
460                                         } catch (AltosCRCException ce) {
461                                                 ++crc_errors;
462                                                 show(state, crc_errors);
463                                         }
464                                 }
465                         } catch (InterruptedException ee) {
466                                 interrupted = true;
467                         } catch (IOException ie) {
468                                 JOptionPane.showMessageDialog(AltosUI.this,
469                                                               String.format("Error reading from \"%s\"", name),
470                                                               "Telemetry Read Error",
471                                                               JOptionPane.ERROR_MESSAGE);
472                         } finally {
473                                 close(interrupted);
474                                 idle_thread.interrupt();
475                                 try {
476                                         idle_thread.join();
477                                 } catch (InterruptedException ie) {}
478                         }
479                 }
480
481                 public void report() {
482                         if (idle_thread != null)
483                                 idle_thread.report(true);
484                 }
485         }
486
487         class DeviceThread extends DisplayThread {
488                 AltosSerial     serial;
489                 LinkedBlockingQueue<AltosLine> telem;
490
491                 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException {
492                         AltosLine l = telem.take();
493                         if (l.line == null)
494                                 throw new IOException("IO error");
495                         return new AltosTelemetry(l.line);
496                 }
497
498                 void close(boolean interrupted) {
499                         serial.close();
500                         serial.remove_monitor(telem);
501                 }
502
503                 public DeviceThread(AltosSerial s, String in_name) {
504                         serial = s;
505                         telem = new LinkedBlockingQueue<AltosLine>();
506                         serial.add_monitor(telem);
507                         name = in_name;
508                 }
509         }
510
511         private void ConnectToDevice() {
512                 AltosDevice     device = AltosDeviceDialog.show(AltosUI.this, AltosDevice.BaseStation);
513
514                 if (device != null) {
515                         try {
516                                 stop_display();
517                                 serial_line.open(device);
518                                 DeviceThread thread = new DeviceThread(serial_line, device.getPath());
519                                 serial_line.set_channel(AltosPreferences.channel());
520                                 serial_line.set_callsign(AltosPreferences.callsign());
521                                 run_display(thread);
522                         } catch (FileNotFoundException ee) {
523                                 JOptionPane.showMessageDialog(AltosUI.this,
524                                                               String.format("Cannot open device \"%s\"",
525                                                                             device.getPath()),
526                                                               "Cannot open target device",
527                                                               JOptionPane.ERROR_MESSAGE);
528                         } catch (IOException ee) {
529                                 JOptionPane.showMessageDialog(AltosUI.this,
530                                                               device.getPath(),
531                                                               "Unkonwn I/O error",
532                                                               JOptionPane.ERROR_MESSAGE);
533                         }
534                 }
535         }
536
537         void DisconnectFromDevice () {
538                 stop_display();
539         }
540
541         void ConfigureCallsign() {
542                 String  result;
543                 result = JOptionPane.showInputDialog(AltosUI.this,
544                                                      "Configure Callsign",
545                                                      AltosPreferences.callsign());
546                 if (result != null) {
547                         AltosPreferences.set_callsign(result);
548                         if (serial_line != null)
549                                 serial_line.set_callsign(result);
550                 }
551         }
552
553         void ConfigureTeleMetrum() {
554                 new AltosConfig(AltosUI.this);
555         }
556
557         void FlashImage() {
558                 new AltosFlashUI(AltosUI.this);
559         }
560
561         /*
562          * Open an existing telemetry file and replay it in realtime
563          */
564
565         class ReplayThread extends DisplayThread {
566                 AltosReader     reader;
567                 String          name;
568
569                 public AltosRecord read() {
570                         try {
571                                 return reader.read();
572                         } catch (IOException ie) {
573                                 JOptionPane.showMessageDialog(AltosUI.this,
574                                                               name,
575                                                               "error reading",
576                                                               JOptionPane.ERROR_MESSAGE);
577                         } catch (ParseException pe) {
578                         }
579                         return null;
580                 }
581
582                 public void close (boolean interrupted) {
583                         if (!interrupted)
584                                 report();
585                 }
586
587                 public ReplayThread(AltosReader in_reader, String in_name) {
588                         reader = in_reader;
589                 }
590                 void update(AltosState state) throws InterruptedException {
591                         /* Make it run in realtime after the rocket leaves the pad */
592                         if (state.state > Altos.ao_flight_pad)
593                                 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
594                 }
595         }
596
597         class ReplayTelemetryThread extends ReplayThread {
598                 ReplayTelemetryThread(FileInputStream in, String in_name) {
599                         super(new AltosTelemetryReader(in), in_name);
600                 }
601
602         }
603
604         class ReplayEepromThread extends ReplayThread {
605                 ReplayEepromThread(FileInputStream in, String in_name) {
606                         super(new AltosEepromReader(in), in_name);
607                 }
608         }
609
610         Thread          display_thread;
611
612         private void stop_display() {
613                 if (display_thread != null && display_thread.isAlive()) {
614                         display_thread.interrupt();
615                         try {
616                                 display_thread.join();
617                         } catch (InterruptedException ie) {}
618                 }
619                 display_thread = null;
620         }
621
622         private void run_display(Thread thread) {
623                 stop_display();
624                 display_thread = thread;
625                 display_thread.start();
626         }
627
628         /*
629          * Replay a flight from telemetry data
630          */
631         private void Replay() {
632                 AltosLogfileChooser chooser = new AltosLogfileChooser(
633                         AltosUI.this);
634                 AltosReader reader = chooser.runDialog();
635                 if (reader != null)
636                         run_display(new ReplayThread(reader,
637                                                      chooser.filename()));
638         }
639
640         /* Connect to TeleMetrum, either directly or through
641          * a TeleDongle over the packet link
642          */
643         private void SaveFlightData() {
644                 new AltosEepromDownload(AltosUI.this);
645         }
646
647         /* Load a flight log file and write out a CSV file containing
648          * all of the data in standard units
649          */
650
651         private void ExportData() {
652                 new AltosCSVUI(AltosUI.this);
653         }
654
655         /* Create the AltosUI menus
656          */
657         private void createMenu() {
658                 JMenuBar menubar = new JMenuBar();
659                 JMenu menu;
660                 JMenuItem item;
661                 JRadioButtonMenuItem radioitem;
662
663                 // File menu
664                 {
665                         menu = new JMenu("File");
666                         menu.setMnemonic(KeyEvent.VK_F);
667                         menubar.add(menu);
668
669                         item = new JMenuItem("Replay File",KeyEvent.VK_R);
670                         item.addActionListener(new ActionListener() {
671                                         public void actionPerformed(ActionEvent e) {
672                                                 Replay();
673                                         }
674                                 });
675                         menu.add(item);
676
677                         item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
678                         item.addActionListener(new ActionListener() {
679                                         public void actionPerformed(ActionEvent e) {
680                                                 SaveFlightData();
681                                         }
682                                 });
683                         menu.add(item);
684
685                         item = new JMenuItem("Flash Image",KeyEvent.VK_F);
686                         item.addActionListener(new ActionListener() {
687                                         public void actionPerformed(ActionEvent e) {
688                                                 FlashImage();
689                                         }
690                                 });
691                         menu.add(item);
692
693                         item = new JMenuItem("Export Data",KeyEvent.VK_F);
694                         item.addActionListener(new ActionListener() {
695                                         public void actionPerformed(ActionEvent e) {
696                                                 ExportData();
697                                         }
698                                 });
699                         menu.add(item);
700
701                         item = new JMenuItem("Quit",KeyEvent.VK_Q);
702                         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
703                                                                    ActionEvent.CTRL_MASK));
704                         item.addActionListener(new ActionListener() {
705                                         public void actionPerformed(ActionEvent e) {
706                                                 System.exit(0);
707                                         }
708                                 });
709                         menu.add(item);
710                 }
711
712                 // Device menu
713                 {
714                         menu = new JMenu("Device");
715                         menu.setMnemonic(KeyEvent.VK_D);
716                         menubar.add(menu);
717
718                         item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
719                         item.addActionListener(new ActionListener() {
720                                         public void actionPerformed(ActionEvent e) {
721                                                 ConnectToDevice();
722                                         }
723                                 });
724                         menu.add(item);
725
726                         item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
727                         item.addActionListener(new ActionListener() {
728                                         public void actionPerformed(ActionEvent e) {
729                                                 DisconnectFromDevice();
730                                         }
731                                 });
732                         menu.add(item);
733
734                         menu.addSeparator();
735
736                         item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
737                         item.addActionListener(new ActionListener() {
738                                         public void actionPerformed(ActionEvent e) {
739                                                 ConfigureCallsign();
740                                         }
741                                 });
742
743                         menu.add(item);
744
745                         item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
746                         item.addActionListener(new ActionListener() {
747                                         public void actionPerformed(ActionEvent e) {
748                                                 ConfigureTeleMetrum();
749                                         }
750                                 });
751
752                         menu.add(item);
753                 }
754                 // Log menu
755                 {
756                         menu = new JMenu("Log");
757                         menu.setMnemonic(KeyEvent.VK_L);
758                         menubar.add(menu);
759
760                         item = new JMenuItem("New Log",KeyEvent.VK_N);
761                         item.addActionListener(new ActionListener() {
762                                         public void actionPerformed(ActionEvent e) {
763                                         }
764                                 });
765                         menu.add(item);
766
767                         item = new JMenuItem("Configure Log",KeyEvent.VK_C);
768                         item.addActionListener(new ActionListener() {
769                                         public void actionPerformed(ActionEvent e) {
770                                                 AltosPreferences.ConfigureLog();
771                                         }
772                                 });
773                         menu.add(item);
774                 }
775                 // Voice menu
776                 {
777                         menu = new JMenu("Voice", true);
778                         menu.setMnemonic(KeyEvent.VK_V);
779                         menubar.add(menu);
780
781                         radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
782                         radioitem.addActionListener(new ActionListener() {
783                                         public void actionPerformed(ActionEvent e) {
784                                                 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
785                                                 boolean enabled = item.isSelected();
786                                                 AltosPreferences.set_voice(enabled);
787                                                 if (enabled)
788                                                         voice.speak_always("Enable voice.");
789                                                 else
790                                                         voice.speak_always("Disable voice.");
791                                         }
792                                 });
793                         menu.add(radioitem);
794                         item = new JMenuItem("Test Voice",KeyEvent.VK_T);
795                         item.addActionListener(new ActionListener() {
796                                         public void actionPerformed(ActionEvent e) {
797                                                 voice.speak("That's one small step for man; one giant leap for mankind.");
798                                         }
799                                 });
800                         menu.add(item);
801                 }
802
803                 // Channel menu
804                 {
805                         menu = new AltosChannelMenu(AltosPreferences.channel());
806                         menu.addActionListener(new ActionListener() {
807                                                 public void actionPerformed(ActionEvent e) {
808                                                         int new_channel = Integer.parseInt(e.getActionCommand());
809                                                         AltosPreferences.set_channel(new_channel);
810                                                         serial_line.set_channel(new_channel);
811                                                 }
812                                 });
813                         menu.setMnemonic(KeyEvent.VK_C);
814                         menubar.add(menu);
815                 }
816
817                 this.setJMenuBar(menubar);
818
819         }
820
821         static String replace_extension(String input, String extension) {
822                 int dot = input.lastIndexOf(".");
823                 if (dot > 0)
824                         input = input.substring(0,dot);
825                 return input.concat(extension);
826         }
827
828         static AltosReader open_logfile(String filename) {
829                 File file = new File (filename);
830                 try {
831                         FileInputStream in;
832
833                         in = new FileInputStream(file);
834                         if (filename.endsWith("eeprom"))
835                                 return new AltosEepromReader(in);
836                         else
837                                 return new AltosTelemetryReader(in);
838                 } catch (FileNotFoundException fe) {
839                         System.out.printf("Cannot open '%s'\n", filename);
840                         return null;
841                 }
842         }
843
844         static AltosCSV open_csv(String filename) {
845                 File file = new File (filename);
846                 try {
847                         return new AltosCSV(file);
848                 } catch (FileNotFoundException fe) {
849                         System.out.printf("Cannot open '%s'\n", filename);
850                         return null;
851                 }
852         }
853
854         static void process_file(String input) {
855                 String output = replace_extension(input,".csv");
856                 if (input.equals(output)) {
857                         System.out.printf("Not processing '%s'\n", input);
858                         return;
859                 }
860                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
861                 AltosReader reader = open_logfile(input);
862                 if (reader == null)
863                         return;
864                 AltosCSV writer = open_csv(output);
865                 if (writer == null)
866                         return;
867                 writer.write(reader);
868                 reader.close();
869                 writer.close();
870         }
871
872         public static void main(final String[] args) {
873
874                 /* Handle batch-mode */
875                 if (args.length > 0) {
876                         for (int i = 0; i < args.length; i++)
877                                 process_file(args[i]);
878                 } else {
879                         AltosUI altosui = new AltosUI();
880                         altosui.setVisible(true);
881                 }
882         }
883 }