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