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