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