Merge branch 'master' of git://git.gag.com/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,
527                                                                 AltosDevice.product_basestation);
528
529                 if (device != null) {
530                         try {
531                                 stop_display();
532                                 serial_line.open(device);
533                                 DeviceThread thread = new DeviceThread(serial_line, device.getPath());
534                                 serial_line.set_channel(AltosPreferences.channel());
535                                 serial_line.set_callsign(AltosPreferences.callsign());
536                                 run_display(thread);
537                         } catch (FileNotFoundException ee) {
538                                 JOptionPane.showMessageDialog(AltosUI.this,
539                                                               String.format("Cannot open device \"%s\"",
540                                                                             device.getPath()),
541                                                               "Cannot open target device",
542                                                               JOptionPane.ERROR_MESSAGE);
543                         } catch (IOException ee) {
544                                 JOptionPane.showMessageDialog(AltosUI.this,
545                                                               device.getPath(),
546                                                               "Unkonwn I/O error",
547                                                               JOptionPane.ERROR_MESSAGE);
548                         }
549                 }
550         }
551
552         void DisconnectFromDevice () {
553                 stop_display();
554         }
555
556         void ConfigureCallsign() {
557                 String  result;
558                 result = JOptionPane.showInputDialog(AltosUI.this,
559                                                      "Configure Callsign",
560                                                      AltosPreferences.callsign());
561                 if (result != null) {
562                         AltosPreferences.set_callsign(result);
563                         if (serial_line != null)
564                                 serial_line.set_callsign(result);
565                 }
566         }
567
568         void ConfigureTeleMetrum() {
569                 new AltosConfig(AltosUI.this);
570         }
571
572         void FlashImage() {
573                 new AltosFlashUI(AltosUI.this);
574         }
575
576         /*
577          * Open an existing telemetry file and replay it in realtime
578          */
579
580         class ReplayThread extends DisplayThread {
581                 AltosReader     reader;
582                 String          name;
583
584                 public AltosRecord read() {
585                         try {
586                                 return reader.read();
587                         } catch (IOException ie) {
588                                 JOptionPane.showMessageDialog(AltosUI.this,
589                                                               name,
590                                                               "error reading",
591                                                               JOptionPane.ERROR_MESSAGE);
592                         } catch (ParseException pe) {
593                         }
594                         return null;
595                 }
596
597                 public void close (boolean interrupted) {
598                         if (!interrupted)
599                                 report();
600                 }
601
602                 public ReplayThread(AltosReader in_reader, String in_name) {
603                         reader = in_reader;
604                 }
605                 void update(AltosState state) throws InterruptedException {
606                         /* Make it run in realtime after the rocket leaves the pad */
607                         if (state.state > Altos.ao_flight_pad)
608                                 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
609                 }
610         }
611
612         class ReplayTelemetryThread extends ReplayThread {
613                 ReplayTelemetryThread(FileInputStream in, String in_name) {
614                         super(new AltosTelemetryReader(in), in_name);
615                 }
616
617         }
618
619         class ReplayEepromThread extends ReplayThread {
620                 ReplayEepromThread(FileInputStream in, String in_name) {
621                         super(new AltosEepromReader(in), in_name);
622                 }
623         }
624
625         Thread          display_thread;
626
627         private void stop_display() {
628                 if (display_thread != null && display_thread.isAlive()) {
629                         display_thread.interrupt();
630                         try {
631                                 display_thread.join();
632                         } catch (InterruptedException ie) {}
633                 }
634                 display_thread = null;
635         }
636
637         private void run_display(Thread thread) {
638                 stop_display();
639                 display_thread = thread;
640                 display_thread.start();
641         }
642
643         /*
644          * Replay a flight from telemetry data
645          */
646         private void Replay() {
647                 AltosLogfileChooser chooser = new AltosLogfileChooser(
648                         AltosUI.this);
649                 AltosReader reader = chooser.runDialog();
650                 if (reader != null)
651                         run_display(new ReplayThread(reader,
652                                                      chooser.filename()));
653         }
654
655         /* Connect to TeleMetrum, either directly or through
656          * a TeleDongle over the packet link
657          */
658         private void SaveFlightData() {
659                 new AltosEepromDownload(AltosUI.this);
660         }
661
662         /* Load a flight log file and write out a CSV file containing
663          * all of the data in standard units
664          */
665
666         private void ExportData() {
667                 new AltosCSVUI(AltosUI.this);
668         }
669
670         /* Create the AltosUI menus
671          */
672         private void createMenu() {
673                 JMenuBar menubar = new JMenuBar();
674                 JMenu menu;
675                 JMenuItem item;
676                 JRadioButtonMenuItem radioitem;
677
678                 // File menu
679                 {
680                         menu = new JMenu("File");
681                         menu.setMnemonic(KeyEvent.VK_F);
682                         menubar.add(menu);
683
684                         item = new JMenuItem("Replay File",KeyEvent.VK_R);
685                         item.addActionListener(new ActionListener() {
686                                         public void actionPerformed(ActionEvent e) {
687                                                 Replay();
688                                         }
689                                 });
690                         menu.add(item);
691
692                         item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
693                         item.addActionListener(new ActionListener() {
694                                         public void actionPerformed(ActionEvent e) {
695                                                 SaveFlightData();
696                                         }
697                                 });
698                         menu.add(item);
699
700                         item = new JMenuItem("Flash Image",KeyEvent.VK_F);
701                         item.addActionListener(new ActionListener() {
702                                         public void actionPerformed(ActionEvent e) {
703                                                 FlashImage();
704                                         }
705                                 });
706                         menu.add(item);
707
708                         item = new JMenuItem("Export Data",KeyEvent.VK_F);
709                         item.addActionListener(new ActionListener() {
710                                         public void actionPerformed(ActionEvent e) {
711                                                 ExportData();
712                                         }
713                                 });
714                         menu.add(item);
715
716                         item = new JMenuItem("Quit",KeyEvent.VK_Q);
717                         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
718                                                                    ActionEvent.CTRL_MASK));
719                         item.addActionListener(new ActionListener() {
720                                         public void actionPerformed(ActionEvent e) {
721                                                 System.exit(0);
722                                         }
723                                 });
724                         menu.add(item);
725                 }
726
727                 // Device menu
728                 {
729                         menu = new JMenu("Device");
730                         menu.setMnemonic(KeyEvent.VK_D);
731                         menubar.add(menu);
732
733                         item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
734                         item.addActionListener(new ActionListener() {
735                                         public void actionPerformed(ActionEvent e) {
736                                                 ConnectToDevice();
737                                         }
738                                 });
739                         menu.add(item);
740
741                         item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
742                         item.addActionListener(new ActionListener() {
743                                         public void actionPerformed(ActionEvent e) {
744                                                 DisconnectFromDevice();
745                                         }
746                                 });
747                         menu.add(item);
748
749                         menu.addSeparator();
750
751                         item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
752                         item.addActionListener(new ActionListener() {
753                                         public void actionPerformed(ActionEvent e) {
754                                                 ConfigureCallsign();
755                                         }
756                                 });
757
758                         menu.add(item);
759
760                         item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
761                         item.addActionListener(new ActionListener() {
762                                         public void actionPerformed(ActionEvent e) {
763                                                 ConfigureTeleMetrum();
764                                         }
765                                 });
766
767                         menu.add(item);
768                 }
769                 // Log menu
770                 {
771                         menu = new JMenu("Log");
772                         menu.setMnemonic(KeyEvent.VK_L);
773                         menubar.add(menu);
774
775                         item = new JMenuItem("New Log",KeyEvent.VK_N);
776                         item.addActionListener(new ActionListener() {
777                                         public void actionPerformed(ActionEvent e) {
778                                         }
779                                 });
780                         menu.add(item);
781
782                         item = new JMenuItem("Configure Log",KeyEvent.VK_C);
783                         item.addActionListener(new ActionListener() {
784                                         public void actionPerformed(ActionEvent e) {
785                                                 AltosPreferences.ConfigureLog();
786                                         }
787                                 });
788                         menu.add(item);
789                 }
790                 // Voice menu
791                 {
792                         menu = new JMenu("Voice", true);
793                         menu.setMnemonic(KeyEvent.VK_V);
794                         menubar.add(menu);
795
796                         radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
797                         radioitem.addActionListener(new ActionListener() {
798                                         public void actionPerformed(ActionEvent e) {
799                                                 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
800                                                 boolean enabled = item.isSelected();
801                                                 AltosPreferences.set_voice(enabled);
802                                                 if (enabled)
803                                                         voice.speak_always("Enable voice.");
804                                                 else
805                                                         voice.speak_always("Disable voice.");
806                                         }
807                                 });
808                         menu.add(radioitem);
809                         item = new JMenuItem("Test Voice",KeyEvent.VK_T);
810                         item.addActionListener(new ActionListener() {
811                                         public void actionPerformed(ActionEvent e) {
812                                                 voice.speak("That's one small step for man; one giant leap for mankind.");
813                                         }
814                                 });
815                         menu.add(item);
816                 }
817
818                 // Channel menu
819                 {
820                         menu = new AltosChannelMenu(AltosPreferences.channel());
821                         menu.addActionListener(new ActionListener() {
822                                                 public void actionPerformed(ActionEvent e) {
823                                                         int new_channel = Integer.parseInt(e.getActionCommand());
824                                                         AltosPreferences.set_channel(new_channel);
825                                                         serial_line.set_channel(new_channel);
826                                                 }
827                                 });
828                         menu.setMnemonic(KeyEvent.VK_C);
829                         menubar.add(menu);
830                 }
831
832                 this.setJMenuBar(menubar);
833
834         }
835
836         static String replace_extension(String input, String extension) {
837                 int dot = input.lastIndexOf(".");
838                 if (dot > 0)
839                         input = input.substring(0,dot);
840                 return input.concat(extension);
841         }
842
843         static AltosReader open_logfile(String filename) {
844                 File file = new File (filename);
845                 try {
846                         FileInputStream in;
847
848                         in = new FileInputStream(file);
849                         if (filename.endsWith("eeprom"))
850                                 return new AltosEepromReader(in);
851                         else
852                                 return new AltosTelemetryReader(in);
853                 } catch (FileNotFoundException fe) {
854                         System.out.printf("Cannot open '%s'\n", filename);
855                         return null;
856                 }
857         }
858
859         static AltosCSV open_csv(String filename) {
860                 File file = new File (filename);
861                 try {
862                         return new AltosCSV(file);
863                 } catch (FileNotFoundException fe) {
864                         System.out.printf("Cannot open '%s'\n", filename);
865                         return null;
866                 }
867         }
868
869         static void process_file(String input) {
870                 String output = replace_extension(input,".csv");
871                 if (input.equals(output)) {
872                         System.out.printf("Not processing '%s'\n", input);
873                         return;
874                 }
875                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
876                 AltosReader reader = open_logfile(input);
877                 if (reader == null)
878                         return;
879                 AltosCSV writer = open_csv(output);
880                 if (writer == null)
881                         return;
882                 writer.write(reader);
883                 reader.close();
884                 writer.close();
885         }
886
887         public static void main(final String[] args) {
888
889                 /* Handle batch-mode */
890                 if (args.length > 0) {
891                         for (int i = 0; i < args.length; i++)
892                                 process_file(args[i]);
893                 } else {
894                         AltosUI altosui = new AltosUI();
895                         altosui.setVisible(true);
896                 }
897         }
898 }