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