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