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