altosui: When replay thread is interrupted, don't make final report
[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                 private AltosState state;
281                 int     reported_landing;
282
283                 public synchronized void report(boolean last) {
284                         if (state == null)
285                                 return;
286
287                         /* reset the landing count once we hear about a new flight */
288                         if (state.state < Altos.ao_flight_drogue)
289                                 reported_landing = 0;
290
291                         /* Shut up once the rocket is on the ground */
292                         if (reported_landing > 2) {
293                                 return;
294                         }
295
296                         /* If the rocket isn't on the pad, then report height */
297                         if (Altos.ao_flight_drogue <= state.state &&
298                             state.state < Altos.ao_flight_landed &&
299                             state.range >= 0)
300                         {
301                                 voice.speak("Height %d, bearing %d, elevation %d, range %d.\n",
302                                             (int) (state.height + 0.5),
303                                             (int) (state.from_pad.bearing + 0.5),
304                                             (int) (state.elevation + 0.5),
305                                             (int) (state.range + 0.5));
306                         } else if (state.state > Altos.ao_flight_pad) {
307                                 voice.speak("%d meters", (int) (state.height + 0.5));
308                         } else {
309                                 reported_landing = 0;
310                         }
311
312                         /* If the rocket is coming down, check to see if it has landed;
313                          * either we've got a landed report or we haven't heard from it in
314                          * a long time
315                          */
316                         if (state.state >= Altos.ao_flight_drogue &&
317                             (last ||
318                              System.currentTimeMillis() - state.report_time >= 15000 ||
319                              state.state == Altos.ao_flight_landed))
320                         {
321                                 if (Math.abs(state.baro_speed) < 20 && state.height < 100)
322                                         voice.speak("rocket landed safely");
323                                 else
324                                         voice.speak("rocket may have crashed");
325                                 if (state.from_pad != null)
326                                         voice.speak("Bearing %d degrees, range %d meters.",
327                                                     (int) (state.from_pad.bearing + 0.5),
328                                                     (int) (state.from_pad.distance + 0.5));
329                                 ++reported_landing;
330                         }
331                 }
332
333                 public void run () {
334
335                         reported_landing = 0;
336                         state = null;
337                         try {
338                                 for (;;) {
339                                         Thread.sleep(20000);
340                                         report(false);
341                                 }
342                         } catch (InterruptedException ie) {
343                         }
344                 }
345
346                 public void notice(AltosState new_state) {
347                         AltosState old_state = state;
348                         state = new_state;
349                         if (old_state != null && old_state.state != state.state)
350                                 report(false);
351                 }
352         }
353
354         private void tell(AltosState state, AltosState old_state) {
355                 if (old_state == null || old_state.state != state.state) {
356                         voice.speak(state.data.state());
357                         if ((old_state == null || old_state.state <= Altos.ao_flight_boost) &&
358                             state.state > Altos.ao_flight_boost) {
359                                 voice.speak("max speed: %d meters per second.",
360                                             (int) (state.max_speed + 0.5));
361                         } else if ((old_state == null || old_state.state < Altos.ao_flight_drogue) &&
362                                    state.state >= Altos.ao_flight_drogue) {
363                                 voice.speak("max height: %d meters.",
364                                             (int) (state.max_height + 0.5));
365                         }
366                 }
367                 if (old_state == null || old_state.gps_ready != state.gps_ready) {
368                         if (state.gps_ready)
369                                 voice.speak("GPS ready");
370                         else if (old_state != null)
371                                 voice.speak("GPS lost");
372                 }
373                 old_state = state;
374         }
375
376         class DisplayThread extends Thread {
377                 IdleThread      idle_thread;
378
379                 String          name;
380
381                 int             crc_errors;
382
383                 void init() { }
384
385                 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException { return null; }
386
387                 void close(boolean interrupted) { }
388
389                 void update(AltosState state) throws InterruptedException { }
390
391                 public void run() {
392                         boolean         interrupted = false;
393                         String          line;
394                         AltosState      state = null;
395                         AltosState      old_state = null;
396
397                         idle_thread = new IdleThread();
398
399                         info_reset();
400                         info_finish();
401                         idle_thread.start();
402                         try {
403                                 for (;;) {
404                                         try {
405                                                 AltosRecord record = read();
406                                                 if (record == null)
407                                                         break;
408                                                 old_state = state;
409                                                 state = new AltosState(record, state);
410                                                 update(state);
411                                                 show(state, crc_errors);
412                                                 tell(state, old_state);
413                                                 idle_thread.notice(state);
414                                         } catch (ParseException pp) {
415                                                 System.out.printf("Parse error: %d \"%s\"\n", pp.getErrorOffset(), pp.getMessage());
416                                         } catch (AltosCRCException ce) {
417                                                 ++crc_errors;
418                                                 show(state, crc_errors);
419                                         }
420                                 }
421                         } catch (InterruptedException ee) {
422                                 interrupted = true;
423                         } catch (IOException ie) {
424                                 JOptionPane.showMessageDialog(AltosUI.this,
425                                                               String.format("Error reading from \"%s\"", name),
426                                                               "Telemetry Read Error",
427                                                               JOptionPane.ERROR_MESSAGE);
428                         } finally {
429                                 close(interrupted);
430                                 idle_thread.interrupt();
431                                 try {
432                                         idle_thread.join();
433                                 } catch (InterruptedException ie) {}
434                         }
435                 }
436
437                 public void report() {
438                         if (idle_thread != null)
439                                 idle_thread.report(true);
440                 }
441         }
442
443         class DeviceThread extends DisplayThread {
444                 AltosSerial     serial;
445                 LinkedBlockingQueue<AltosLine> telem;
446
447                 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException {
448                         AltosLine l = telem.take();
449                         if (l.line == null)
450                                 throw new IOException("IO error");
451                         return new AltosTelemetry(l.line);
452                 }
453
454                 void close(boolean interrupted) {
455                         serial.close();
456                         serial.remove_monitor(telem);
457                 }
458
459                 public DeviceThread(AltosSerial s, String in_name) {
460                         serial = s;
461                         telem = new LinkedBlockingQueue<AltosLine>();
462                         serial.add_monitor(telem);
463                         name = in_name;
464                 }
465         }
466
467         private void ConnectToDevice() {
468                 AltosDevice     device = AltosDeviceDialog.show(AltosUI.this, AltosDevice.BaseStation);
469
470                 if (device != null) {
471                         try {
472                                 stop_display();
473                                 serial_line.open(device);
474                                 DeviceThread thread = new DeviceThread(serial_line, device.getPath());
475                                 serial_line.set_channel(AltosPreferences.channel());
476                                 serial_line.set_callsign(AltosPreferences.callsign());
477                                 run_display(thread);
478                         } catch (FileNotFoundException ee) {
479                                 JOptionPane.showMessageDialog(AltosUI.this,
480                                                               String.format("Cannot open device \"%s\"",
481                                                                             device.getPath()),
482                                                               "Cannot open target device",
483                                                               JOptionPane.ERROR_MESSAGE);
484                         } catch (IOException ee) {
485                                 JOptionPane.showMessageDialog(AltosUI.this,
486                                                               device.getPath(),
487                                                               "Unkonwn I/O error",
488                                                               JOptionPane.ERROR_MESSAGE);
489                         }
490                 }
491         }
492
493         void DisconnectFromDevice () {
494                 stop_display();
495         }
496
497         void ConfigureCallsign() {
498                 String  result;
499                 result = JOptionPane.showInputDialog(AltosUI.this,
500                                                      "Configure Callsign",
501                                                      AltosPreferences.callsign());
502                 if (result != null) {
503                         AltosPreferences.set_callsign(result);
504                         if (serial_line != null)
505                                 serial_line.set_callsign(result);
506                 }
507         }
508
509         void ConfigureTeleMetrum() {
510                 new AltosConfig(AltosUI.this);
511         }
512
513         void FlashImage() {
514                 new AltosFlashUI(AltosUI.this);
515         }
516
517         /*
518          * Open an existing telemetry file and replay it in realtime
519          */
520
521         class ReplayThread extends DisplayThread {
522                 AltosReader     reader;
523                 String          name;
524
525                 public AltosRecord read() {
526                         try {
527                                 return reader.read();
528                         } catch (IOException ie) {
529                                 JOptionPane.showMessageDialog(AltosUI.this,
530                                                               name,
531                                                               "error reading",
532                                                               JOptionPane.ERROR_MESSAGE);
533                         } catch (ParseException pe) {
534                         }
535                         return null;
536                 }
537
538                 public void close (boolean interrupted) {
539                         if (!interrupted)
540                                 report();
541                 }
542
543                 public ReplayThread(AltosReader in_reader, String in_name) {
544                         reader = in_reader;
545                 }
546                 void update(AltosState state) throws InterruptedException {
547                         /* Make it run in realtime after the rocket leaves the pad */
548                         if (state.state > Altos.ao_flight_pad)
549                                 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
550                 }
551         }
552
553         class ReplayTelemetryThread extends ReplayThread {
554                 ReplayTelemetryThread(FileInputStream in, String in_name) {
555                         super(new AltosTelemetryReader(in), in_name);
556                 }
557
558         }
559
560         class ReplayEepromThread extends ReplayThread {
561                 ReplayEepromThread(FileInputStream in, String in_name) {
562                         super(new AltosEepromReader(in), in_name);
563                 }
564         }
565
566         Thread          display_thread;
567
568         private void stop_display() {
569                 if (display_thread != null && display_thread.isAlive()) {
570                         display_thread.interrupt();
571                         try {
572                                 display_thread.join();
573                         } catch (InterruptedException ie) {}
574                 }
575                 display_thread = null;
576         }
577
578         private void run_display(Thread thread) {
579                 stop_display();
580                 display_thread = thread;
581                 display_thread.start();
582         }
583
584         /*
585          * Replay a flight from telemetry data
586          */
587         private void Replay() {
588                 AltosLogfileChooser chooser = new AltosLogfileChooser(
589                         AltosUI.this);
590                 AltosReader reader = chooser.runDialog();
591                 if (reader != null)
592                         run_display(new ReplayThread(reader,
593                                                      chooser.filename()));
594         }
595
596         /* Connect to TeleMetrum, either directly or through
597          * a TeleDongle over the packet link
598          */
599         private void SaveFlightData() {
600                 new AltosEepromDownload(AltosUI.this);
601         }
602
603         /* Load a flight log file and write out a CSV file containing
604          * all of the data in standard units
605          */
606
607         private void ExportData() {
608                 new AltosCSVUI(AltosUI.this);
609         }
610
611         /* Create the AltosUI menus
612          */
613         private void createMenu() {
614                 JMenuBar menubar = new JMenuBar();
615                 JMenu menu;
616                 JMenuItem item;
617                 JRadioButtonMenuItem radioitem;
618
619                 // File menu
620                 {
621                         menu = new JMenu("File");
622                         menu.setMnemonic(KeyEvent.VK_F);
623                         menubar.add(menu);
624
625                         item = new JMenuItem("Replay File",KeyEvent.VK_R);
626                         item.addActionListener(new ActionListener() {
627                                         public void actionPerformed(ActionEvent e) {
628                                                 Replay();
629                                         }
630                                 });
631                         menu.add(item);
632
633                         item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
634                         item.addActionListener(new ActionListener() {
635                                         public void actionPerformed(ActionEvent e) {
636                                                 SaveFlightData();
637                                         }
638                                 });
639                         menu.add(item);
640
641                         item = new JMenuItem("Flash Image",KeyEvent.VK_F);
642                         item.addActionListener(new ActionListener() {
643                                         public void actionPerformed(ActionEvent e) {
644                                                 FlashImage();
645                                         }
646                                 });
647                         menu.add(item);
648
649                         item = new JMenuItem("Export Data",KeyEvent.VK_F);
650                         item.addActionListener(new ActionListener() {
651                                         public void actionPerformed(ActionEvent e) {
652                                                 ExportData();
653                                         }
654                                 });
655                         menu.add(item);
656
657                         item = new JMenuItem("Quit",KeyEvent.VK_Q);
658                         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
659                                                                    ActionEvent.CTRL_MASK));
660                         item.addActionListener(new ActionListener() {
661                                         public void actionPerformed(ActionEvent e) {
662                                                 System.exit(0);
663                                         }
664                                 });
665                         menu.add(item);
666                 }
667
668                 // Device menu
669                 {
670                         menu = new JMenu("Device");
671                         menu.setMnemonic(KeyEvent.VK_D);
672                         menubar.add(menu);
673
674                         item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
675                         item.addActionListener(new ActionListener() {
676                                         public void actionPerformed(ActionEvent e) {
677                                                 ConnectToDevice();
678                                         }
679                                 });
680                         menu.add(item);
681
682                         item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
683                         item.addActionListener(new ActionListener() {
684                                         public void actionPerformed(ActionEvent e) {
685                                                 DisconnectFromDevice();
686                                         }
687                                 });
688                         menu.add(item);
689
690                         menu.addSeparator();
691
692                         item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
693                         item.addActionListener(new ActionListener() {
694                                         public void actionPerformed(ActionEvent e) {
695                                                 ConfigureCallsign();
696                                         }
697                                 });
698
699                         menu.add(item);
700
701                         item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
702                         item.addActionListener(new ActionListener() {
703                                         public void actionPerformed(ActionEvent e) {
704                                                 ConfigureTeleMetrum();
705                                         }
706                                 });
707
708                         menu.add(item);
709                 }
710                 // Log menu
711                 {
712                         menu = new JMenu("Log");
713                         menu.setMnemonic(KeyEvent.VK_L);
714                         menubar.add(menu);
715
716                         item = new JMenuItem("New Log",KeyEvent.VK_N);
717                         item.addActionListener(new ActionListener() {
718                                         public void actionPerformed(ActionEvent e) {
719                                         }
720                                 });
721                         menu.add(item);
722
723                         item = new JMenuItem("Configure Log",KeyEvent.VK_C);
724                         item.addActionListener(new ActionListener() {
725                                         public void actionPerformed(ActionEvent e) {
726                                                 AltosPreferences.ConfigureLog();
727                                         }
728                                 });
729                         menu.add(item);
730                 }
731                 // Voice menu
732                 {
733                         menu = new JMenu("Voice", true);
734                         menu.setMnemonic(KeyEvent.VK_V);
735                         menubar.add(menu);
736
737                         radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
738                         radioitem.addActionListener(new ActionListener() {
739                                         public void actionPerformed(ActionEvent e) {
740                                                 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
741                                                 boolean enabled = item.isSelected();
742                                                 AltosPreferences.set_voice(enabled);
743                                                 if (enabled)
744                                                         voice.speak_always("Enable voice.");
745                                                 else
746                                                         voice.speak_always("Disable voice.");
747                                         }
748                                 });
749                         menu.add(radioitem);
750                         item = new JMenuItem("Test Voice",KeyEvent.VK_T);
751                         item.addActionListener(new ActionListener() {
752                                         public void actionPerformed(ActionEvent e) {
753                                                 voice.speak("That's one small step for man; one giant leap for mankind.");
754                                         }
755                                 });
756                         menu.add(item);
757                 }
758
759                 // Channel menu
760                 {
761                         menu = new AltosChannelMenu(AltosPreferences.channel());
762                         menu.addActionListener(new ActionListener() {
763                                                 public void actionPerformed(ActionEvent e) {
764                                                         int new_channel = Integer.parseInt(e.getActionCommand());
765                                                         AltosPreferences.set_channel(new_channel);
766                                                         serial_line.set_channel(new_channel);
767                                                 }
768                                 });
769                         menu.setMnemonic(KeyEvent.VK_C);
770                         menubar.add(menu);
771                 }
772
773                 this.setJMenuBar(menubar);
774
775         }
776
777         static String replace_extension(String input, String extension) {
778                 int dot = input.lastIndexOf(".");
779                 if (dot > 0)
780                         input = input.substring(0,dot);
781                 return input.concat(extension);
782         }
783
784         static AltosReader open_logfile(String filename) {
785                 File file = new File (filename);
786                 try {
787                         FileInputStream in;
788
789                         in = new FileInputStream(file);
790                         if (filename.endsWith("eeprom"))
791                                 return new AltosEepromReader(in);
792                         else
793                                 return new AltosTelemetryReader(in);
794                 } catch (FileNotFoundException fe) {
795                         System.out.printf("Cannot open '%s'\n", filename);
796                         return null;
797                 }
798         }
799
800         static AltosCSV open_csv(String filename) {
801                 File file = new File (filename);
802                 try {
803                         return new AltosCSV(file);
804                 } catch (FileNotFoundException fe) {
805                         System.out.printf("Cannot open '%s'\n", filename);
806                         return null;
807                 }
808         }
809
810         static void process_file(String input) {
811                 String output = replace_extension(input,".csv");
812                 if (input.equals(output)) {
813                         System.out.printf("Not processing '%s'\n", input);
814                         return;
815                 }
816                 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
817                 AltosReader reader = open_logfile(input);
818                 if (reader == null)
819                         return;
820                 AltosCSV writer = open_csv(output);
821                 if (writer == null)
822                         return;
823                 writer.write(reader);
824                 reader.close();
825                 writer.close();
826         }
827
828         public static void main(final String[] args) {
829
830                 /* Handle batch-mode */
831                 if (args.length > 0) {
832                         for (int i = 0; i < args.length; i++)
833                                 process_file(args[i]);
834                 } else {
835                         AltosUI altosui = new AltosUI();
836                         altosui.setVisible(true);
837                 }
838         }
839 }