2 * Copyright © 2010 Keith Packard <keithp@keithp.com>
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.
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.
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.
21 import java.awt.event.*;
23 import javax.swing.filechooser.FileNameExtensionFilter;
24 import javax.swing.table.*;
28 import java.util.prefs.*;
29 import java.util.concurrent.LinkedBlockingQueue;
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;
51 public class AltosUI extends JFrame {
52 private int channel = -1;
54 private AltosFlightStatusTableModel flightStatusModel;
55 private JTable flightStatus;
57 static final int info_columns = 3;
59 private AltosFlightInfoTableModel[] flightInfoModel;
60 private JTable[] flightInfo;
61 private AltosSerial serial_line;
62 private AltosLog altos_log;
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);
71 public AltosVoice voice = new AltosVoice();
75 String[] statusNames = { "Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
76 Object[][] statusData = { { "0", "pad", "-50", "0" } };
78 AltosPreferences.init(this);
80 vbox = Box.createVerticalBox();
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);
94 FontMetrics statusMetrics = flightStatus.getFontMetrics(statusFont);
95 int statusHeight = (statusMetrics.getHeight() + statusMetrics.getLeading()) * 15 / 10;
96 flightStatus.setRowHeight(statusHeight);
97 flightStatus.setShowGrid(false);
99 vbox.add(flightStatus);
101 hbox = Box.createHorizontalBox();
104 flightInfo = new JTable[3];
105 flightInfoModel = new AltosFlightInfoTableModel[3];
107 FontMetrics infoValueMetrics = flightStatus.getFontMetrics(infoValueFont);
108 int infoHeight = (infoValueMetrics.getHeight() + infoValueMetrics.getLeading()) * 20 / 10;
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]);
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));
132 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
133 addWindowListener(new WindowAdapter() {
135 public void windowClosing(WindowEvent e) {
139 voice.speak("Rocket flight monitor ready.");
142 public void info_reset() {
143 for (int i = 0; i < info_columns; i++)
144 flightInfoModel[i].resetRow();
147 public void info_add_row(int col, String name, String value) {
148 flightInfoModel[col].addRow(name, value);
151 public void info_add_row(int col, String name, String format, Object... parameters) {
152 flightInfoModel[col].addRow(name, String.format(format, parameters));
155 public void info_add_deg(int col, String name, double v, int pos, int neg) {
161 double deg = Math.floor(v);
162 double min = (v - deg) * 60;
164 flightInfoModel[col].addRow(name, String.format("%3.0f°%08.5f'", deg, min));
167 public void info_finish() {
168 for (int i = 0; i < info_columns; i++)
169 flightInfoModel[i].finish();
172 public void show(AltosState state, int crc_errors) {
175 flightStatusModel.set(state);
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);
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");
200 info_add_row(1, "GPS state", "%s", "ready");
202 info_add_row(1, "GPS state", "wait (%d)",
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");
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);
216 /* The SkyTraq GPS doesn't report these values */
218 info_add_row(1, "GPS ground speed", "%8.1f m/s %3d°",
219 state.gps.ground_speed,
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);
226 info_add_row(1, "GPS hdop", "%8.1f", state.gps.hdop);
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);
233 info_add_row(1, "Distance from pad", "unknown");
234 info_add_row(1, "Direction from pad", "unknown");
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);
240 info_add_row(1, "GPS date", "%04d-%02d-%02d",
244 info_add_row(1, "GPS time", " %02d:%02d:%02d",
251 if (state.gps.cc_gps_sat == null)
252 info_add_row(2, "Satellites Visible", "%4d", 0);
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",
258 state.gps.cc_gps_sat[c].svid,
259 state.gps.cc_gps_sat[c].c_n0);
266 class IdleThread extends Thread {
268 private AltosState state;
269 int reported_landing;
271 public synchronized void report(boolean last) {
275 /* reset the landing count once we hear about a new flight */
276 if (state.state < Altos.ao_flight_drogue)
277 reported_landing = 0;
279 /* Shut up once the rocket is on the ground */
280 if (reported_landing > 2) {
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 &&
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));
297 reported_landing = 0;
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
304 if (state.state >= Altos.ao_flight_drogue &&
306 System.currentTimeMillis() - state.report_time >= 15000 ||
307 state.state == Altos.ao_flight_landed))
309 if (Math.abs(state.baro_speed) < 20 && state.height < 100)
310 voice.speak("rocket landed safely");
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));
323 reported_landing = 0;
330 } catch (InterruptedException ie) {
334 public void notice(AltosState new_state) {
335 AltosState old_state = state;
337 if (old_state != null && old_state.state != state.state)
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));
355 if (old_state == null || old_state.gps_ready != state.gps_ready) {
357 voice.speak("GPS ready");
358 else if (old_state != null)
359 voice.speak("GPS lost");
364 class DisplayThread extends Thread {
365 IdleThread idle_thread;
373 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException { return null; }
377 void update(AltosState state) throws InterruptedException { }
381 AltosState state = null;
382 AltosState old_state = null;
384 idle_thread = new IdleThread();
392 AltosRecord record = read();
396 state = new AltosState(record, 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) {
405 show(state, crc_errors);
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);
416 idle_thread.interrupt();
420 public void report() {
421 if (idle_thread != null)
422 idle_thread.report(true);
426 class DeviceThread extends DisplayThread {
428 LinkedBlockingQueue<AltosLine> telem;
430 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException {
431 AltosLine l = telem.take();
433 throw new IOException("IO error");
434 return new AltosTelemetry(l.line);
439 serial.remove_monitor(telem);
442 public DeviceThread(AltosSerial s, String in_name) {
444 telem = new LinkedBlockingQueue<AltosLine>();
445 serial.add_monitor(telem);
450 private void ConnectToDevice() {
451 AltosDevice device = AltosDeviceDialog.show(AltosUI.this, AltosDevice.BaseStation);
453 if (device != null) {
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());
461 } catch (FileNotFoundException ee) {
462 JOptionPane.showMessageDialog(AltosUI.this,
463 String.format("Cannot open device \"%s\"",
465 "Cannot open target device",
466 JOptionPane.ERROR_MESSAGE);
467 } catch (IOException ee) {
468 JOptionPane.showMessageDialog(AltosUI.this,
471 JOptionPane.ERROR_MESSAGE);
476 void DisconnectFromDevice () {
480 void ConfigureCallsign() {
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);
492 void ConfigureTeleMetrum() {
493 new AltosConfig(AltosUI.this);
497 new AltosFlashUI(AltosUI.this);
501 * Open an existing telemetry file and replay it in realtime
504 class ReplayThread extends DisplayThread {
508 public AltosRecord read() {
510 return reader.read();
511 } catch (IOException ie) {
512 JOptionPane.showMessageDialog(AltosUI.this,
515 JOptionPane.ERROR_MESSAGE);
516 } catch (ParseException pe) {
521 public void close () {
525 public ReplayThread(AltosReader in_reader, String in_name) {
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));
535 class ReplayTelemetryThread extends ReplayThread {
536 ReplayTelemetryThread(FileInputStream in, String in_name) {
537 super(new AltosTelemetryReader(in), in_name);
542 class ReplayEepromThread extends ReplayThread {
543 ReplayEepromThread(FileInputStream in, String in_name) {
544 super(new AltosEepromReader(in), in_name);
548 Thread display_thread;
550 private void stop_display() {
551 if (display_thread != null && display_thread.isAlive()) {
552 display_thread.interrupt();
554 display_thread.join();
555 } catch (InterruptedException ie) {}
557 display_thread = null;
560 private void run_display(Thread thread) {
562 display_thread = thread;
563 display_thread.start();
567 * Replay a flight from telemetry data
569 private void Replay() {
570 AltosLogfileChooser chooser = new AltosLogfileChooser(
572 AltosReader reader = chooser.runDialog();
574 run_display(new ReplayThread(reader,
575 chooser.filename()));
578 /* Connect to TeleMetrum, either directly or through
579 * a TeleDongle over the packet link
581 private void SaveFlightData() {
582 new AltosEepromDownload(AltosUI.this);
585 /* Load a flight log file and write out a CSV file containing
586 * all of the data in standard units
589 private void ExportData() {
590 new AltosCSVUI(AltosUI.this);
593 /* Create the AltosUI menus
595 private void createMenu() {
596 JMenuBar menubar = new JMenuBar();
599 JRadioButtonMenuItem radioitem;
603 menu = new JMenu("File");
604 menu.setMnemonic(KeyEvent.VK_F);
607 item = new JMenuItem("Replay File",KeyEvent.VK_R);
608 item.addActionListener(new ActionListener() {
609 public void actionPerformed(ActionEvent e) {
615 item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
616 item.addActionListener(new ActionListener() {
617 public void actionPerformed(ActionEvent e) {
623 item = new JMenuItem("Flash Image",KeyEvent.VK_F);
624 item.addActionListener(new ActionListener() {
625 public void actionPerformed(ActionEvent e) {
631 item = new JMenuItem("Export Data",KeyEvent.VK_F);
632 item.addActionListener(new ActionListener() {
633 public void actionPerformed(ActionEvent e) {
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) {
652 menu = new JMenu("Device");
653 menu.setMnemonic(KeyEvent.VK_D);
656 item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
657 item.addActionListener(new ActionListener() {
658 public void actionPerformed(ActionEvent e) {
664 item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
665 item.addActionListener(new ActionListener() {
666 public void actionPerformed(ActionEvent e) {
667 DisconnectFromDevice();
674 item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
675 item.addActionListener(new ActionListener() {
676 public void actionPerformed(ActionEvent e) {
683 item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
684 item.addActionListener(new ActionListener() {
685 public void actionPerformed(ActionEvent e) {
686 ConfigureTeleMetrum();
694 menu = new JMenu("Log");
695 menu.setMnemonic(KeyEvent.VK_L);
698 item = new JMenuItem("New Log",KeyEvent.VK_N);
699 item.addActionListener(new ActionListener() {
700 public void actionPerformed(ActionEvent e) {
705 item = new JMenuItem("Configure Log",KeyEvent.VK_C);
706 item.addActionListener(new ActionListener() {
707 public void actionPerformed(ActionEvent e) {
708 AltosPreferences.ConfigureLog();
715 menu = new JMenu("Voice", true);
716 menu.setMnemonic(KeyEvent.VK_V);
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);
726 voice.speak_always("Enable voice.");
728 voice.speak_always("Disable voice.");
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.");
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);
751 menu.setMnemonic(KeyEvent.VK_C);
755 this.setJMenuBar(menubar);
759 static String replace_extension(String input, String extension) {
760 int dot = input.lastIndexOf(".");
762 input = input.substring(0,dot);
763 return input.concat(extension);
766 static AltosReader open_logfile(String filename) {
767 File file = new File (filename);
771 in = new FileInputStream(file);
772 if (filename.endsWith("eeprom"))
773 return new AltosEepromReader(in);
775 return new AltosTelemetryReader(in);
776 } catch (FileNotFoundException fe) {
777 System.out.printf("Cannot open '%s'\n", filename);
782 static AltosCSV open_csv(String filename) {
783 File file = new File (filename);
785 return new AltosCSV(file);
786 } catch (FileNotFoundException fe) {
787 System.out.printf("Cannot open '%s'\n", filename);
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);
798 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
799 AltosReader reader = open_logfile(input);
802 AltosCSV writer = open_csv(output);
805 writer.write(reader);
810 public static void main(final String[] args) {
812 /* Handle batch-mode */
813 if (args.length > 0) {
814 for (int i = 0; i < args.length; i++)
815 process_file(args[i]);
817 AltosUI altosui = new AltosUI();
818 altosui.setVisible(true);