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