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