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;
50 public class AltosUI extends JFrame {
51 private int channel = -1;
53 private AltosFlightStatusTableModel flightStatusModel;
54 private JTable flightStatus;
56 static final int info_columns = 3;
58 private AltosFlightInfoTableModel[] flightInfoModel;
59 private JTable[] flightInfo;
60 private AltosSerial serial_line;
61 private AltosLog altos_log;
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);
70 public AltosVoice voice = new AltosVoice();
74 String[] statusNames = { "Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
75 Object[][] statusData = { { "0", "pad", "-50", "0" } };
77 AltosPreferences.init(this);
79 vbox = Box.createVerticalBox();
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);
93 FontMetrics statusMetrics = flightStatus.getFontMetrics(statusFont);
94 int statusHeight = (statusMetrics.getHeight() + statusMetrics.getLeading()) * 15 / 10;
95 flightStatus.setRowHeight(statusHeight);
96 flightStatus.setShowGrid(false);
98 vbox.add(flightStatus);
100 hbox = Box.createHorizontalBox();
103 flightInfo = new JTable[3];
104 flightInfoModel = new AltosFlightInfoTableModel[3];
106 FontMetrics infoValueMetrics = flightStatus.getFontMetrics(infoValueFont);
107 int infoHeight = (infoValueMetrics.getHeight() + infoValueMetrics.getLeading()) * 20 / 10;
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]);
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));
131 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
132 addWindowListener(new WindowAdapter() {
134 public void windowClosing(WindowEvent e) {
138 voice.speak("Rocket flight monitor ready.");
141 public void info_reset() {
142 for (int i = 0; i < info_columns; i++)
143 flightInfoModel[i].resetRow();
146 public void info_add_row(int col, String name, String value) {
147 flightInfoModel[col].addRow(name, value);
150 public void info_add_row(int col, String name, String format, Object... parameters) {
151 flightInfoModel[col].addRow(name, String.format(format, parameters));
154 public void info_add_deg(int col, String name, double v, int pos, int neg) {
160 double deg = Math.floor(v);
161 double min = (v - deg) * 60;
163 flightInfoModel[col].addRow(name, String.format("%3.0f°%08.5f'", deg, min));
166 public void info_finish() {
167 for (int i = 0; i < info_columns; i++)
168 flightInfoModel[i].finish();
171 public void show(AltosState state, int crc_errors) {
172 flightStatusModel.set(state);
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);
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");
197 info_add_row(1, "GPS state", "%s", "ready");
199 info_add_row(1, "GPS state", "wait (%d)",
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");
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);
213 /* The SkyTraq GPS doesn't report these values */
215 info_add_row(1, "GPS ground speed", "%8.1f m/s %3d°",
216 state.gps.ground_speed,
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);
223 info_add_row(1, "GPS hdop", "%8.1f", state.gps.hdop);
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);
230 info_add_row(1, "Distance from pad", "unknown");
231 info_add_row(1, "Direction from pad", "unknown");
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);
237 info_add_row(1, "GPS date", "%04d-%02d-%02d",
241 info_add_row(1, "GPS time", " %02d:%02d:%02d",
248 if (state.gps.cc_gps_sat == null)
249 info_add_row(2, "Satellites Visible", "%4d", 0);
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",
255 state.gps.cc_gps_sat[c].svid,
256 state.gps.cc_gps_sat[c].c_n0);
263 class IdleThread extends Thread {
265 private AltosState state;
266 int reported_landing;
268 public synchronized void report(boolean last) {
272 /* reset the landing count once we hear about a new flight */
273 if (state.state < Altos.ao_flight_drogue)
274 reported_landing = 0;
276 /* Shut up once the rocket is on the ground */
277 if (reported_landing > 2) {
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 &&
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));
294 reported_landing = 0;
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
301 if (state.state >= Altos.ao_flight_drogue &&
303 System.currentTimeMillis() - state.report_time >= 15000 ||
304 state.state == Altos.ao_flight_landed))
306 if (Math.abs(state.baro_speed) < 20 && state.height < 100)
307 voice.speak("rocket landed safely");
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));
320 reported_landing = 0;
327 } catch (InterruptedException ie) {
331 public void notice(AltosState new_state) {
332 AltosState old_state = state;
334 if (old_state != null && old_state.state != state.state)
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));
352 if (old_state == null || old_state.gps_ready != state.gps_ready) {
354 voice.speak("GPS ready");
355 else if (old_state != null)
356 voice.speak("GPS lost");
361 class DisplayThread extends Thread {
362 IdleThread idle_thread;
370 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException { return null; }
374 void update(AltosState state) throws InterruptedException { }
378 AltosState state = null;
379 AltosState old_state = null;
381 idle_thread = new IdleThread();
389 AltosRecord record = read();
393 state = new AltosState(record, 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) {
402 show(state, crc_errors);
405 } catch (InterruptedException ee) {
408 idle_thread.interrupt();
412 public void report() {
413 if (idle_thread != null)
414 idle_thread.report(true);
418 class DeviceThread extends DisplayThread {
420 LinkedBlockingQueue<String> telem;
422 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException {
423 return new AltosTelemetry(telem.take());
428 serial.remove_monitor(telem);
431 public DeviceThread(AltosSerial s) {
433 telem = new LinkedBlockingQueue<String>();
434 serial.add_monitor(telem);
439 private void ConnectToDevice() {
440 AltosDevice device = AltosDeviceDialog.show(AltosUI.this, AltosDevice.BaseStation);
442 if (device != null) {
445 serial_line.open(device);
446 DeviceThread thread = new DeviceThread(serial_line);
447 serial_line.set_channel(AltosPreferences.channel());
448 serial_line.set_callsign(AltosPreferences.callsign());
450 } catch (FileNotFoundException ee) {
451 JOptionPane.showMessageDialog(AltosUI.this,
452 String.format("Cannot open device \"%s\"",
454 "Cannot open target device",
455 JOptionPane.ERROR_MESSAGE);
456 } catch (IOException ee) {
457 JOptionPane.showMessageDialog(AltosUI.this,
460 JOptionPane.ERROR_MESSAGE);
465 void DisconnectFromDevice () {
469 void ConfigureCallsign() {
471 result = JOptionPane.showInputDialog(AltosUI.this,
472 "Configure Callsign",
473 AltosPreferences.callsign());
474 if (result != null) {
475 AltosPreferences.set_callsign(result);
476 if (serial_line != null)
477 serial_line.set_callsign(result);
481 void ConfigureTeleMetrum() {
482 new AltosConfig(AltosUI.this);
486 new AltosFlashUI(AltosUI.this);
490 * Open an existing telemetry file and replay it in realtime
493 class ReplayThread extends DisplayThread {
497 public AltosRecord read() {
499 return reader.read();
500 } catch (IOException ie) {
501 JOptionPane.showMessageDialog(AltosUI.this,
504 JOptionPane.ERROR_MESSAGE);
505 } catch (ParseException pe) {
510 public void close () {
514 public ReplayThread(AltosReader in_reader, String in_name) {
517 void update(AltosState state) throws InterruptedException {
518 /* Make it run in realtime after the rocket leaves the pad */
519 if (state.state > Altos.ao_flight_pad)
520 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
524 class ReplayTelemetryThread extends ReplayThread {
525 ReplayTelemetryThread(FileInputStream in, String in_name) {
526 super(new AltosTelemetryReader(in), in_name);
531 class ReplayEepromThread extends ReplayThread {
532 ReplayEepromThread(FileInputStream in, String in_name) {
533 super(new AltosEepromReader(in), in_name);
537 Thread display_thread;
539 private void stop_display() {
540 if (display_thread != null && display_thread.isAlive()) {
541 display_thread.interrupt();
543 display_thread.join();
544 } catch (InterruptedException ie) {}
546 display_thread = null;
549 private void run_display(Thread thread) {
551 display_thread = thread;
552 display_thread.start();
556 * Replay a flight from telemetry data
558 private void Replay() {
559 AltosLogfileChooser chooser = new AltosLogfileChooser(
561 AltosReader reader = chooser.runDialog();
563 run_display(new ReplayThread(reader,
564 chooser.filename()));
567 /* Connect to TeleMetrum, either directly or through
568 * a TeleDongle over the packet link
570 private void SaveFlightData() {
571 new AltosEepromDownload(AltosUI.this);
574 /* Load a flight log file and write out a CSV file containing
575 * all of the data in standard units
578 private void ExportData() {
579 new AltosCSVUI(AltosUI.this);
582 /* Create the AltosUI menus
584 private void createMenu() {
585 JMenuBar menubar = new JMenuBar();
588 JRadioButtonMenuItem radioitem;
592 menu = new JMenu("File");
593 menu.setMnemonic(KeyEvent.VK_F);
596 item = new JMenuItem("Replay File",KeyEvent.VK_R);
597 item.addActionListener(new ActionListener() {
598 public void actionPerformed(ActionEvent e) {
604 item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
605 item.addActionListener(new ActionListener() {
606 public void actionPerformed(ActionEvent e) {
612 item = new JMenuItem("Flash Image",KeyEvent.VK_F);
613 item.addActionListener(new ActionListener() {
614 public void actionPerformed(ActionEvent e) {
620 item = new JMenuItem("Export Data",KeyEvent.VK_F);
621 item.addActionListener(new ActionListener() {
622 public void actionPerformed(ActionEvent e) {
628 item = new JMenuItem("Quit",KeyEvent.VK_Q);
629 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
630 ActionEvent.CTRL_MASK));
631 item.addActionListener(new ActionListener() {
632 public void actionPerformed(ActionEvent e) {
641 menu = new JMenu("Device");
642 menu.setMnemonic(KeyEvent.VK_D);
645 item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
646 item.addActionListener(new ActionListener() {
647 public void actionPerformed(ActionEvent e) {
653 item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
654 item.addActionListener(new ActionListener() {
655 public void actionPerformed(ActionEvent e) {
656 DisconnectFromDevice();
663 item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
664 item.addActionListener(new ActionListener() {
665 public void actionPerformed(ActionEvent e) {
672 item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
673 item.addActionListener(new ActionListener() {
674 public void actionPerformed(ActionEvent e) {
675 ConfigureTeleMetrum();
683 menu = new JMenu("Log");
684 menu.setMnemonic(KeyEvent.VK_L);
687 item = new JMenuItem("New Log",KeyEvent.VK_N);
688 item.addActionListener(new ActionListener() {
689 public void actionPerformed(ActionEvent e) {
694 item = new JMenuItem("Configure Log",KeyEvent.VK_C);
695 item.addActionListener(new ActionListener() {
696 public void actionPerformed(ActionEvent e) {
697 AltosPreferences.ConfigureLog();
704 menu = new JMenu("Voice", true);
705 menu.setMnemonic(KeyEvent.VK_V);
708 radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
709 radioitem.addActionListener(new ActionListener() {
710 public void actionPerformed(ActionEvent e) {
711 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
712 boolean enabled = item.isSelected();
713 AltosPreferences.set_voice(enabled);
715 voice.speak_always("Enable voice.");
717 voice.speak_always("Disable voice.");
721 item = new JMenuItem("Test Voice",KeyEvent.VK_T);
722 item.addActionListener(new ActionListener() {
723 public void actionPerformed(ActionEvent e) {
724 voice.speak("That's one small step for man; one giant leap for mankind.");
732 menu = new AltosChannelMenu(AltosPreferences.channel());
733 menu.addActionListener(new ActionListener() {
734 public void actionPerformed(ActionEvent e) {
735 int new_channel = Integer.parseInt(e.getActionCommand());
736 AltosPreferences.set_channel(new_channel);
737 serial_line.set_channel(new_channel);
740 menu.setMnemonic(KeyEvent.VK_C);
744 this.setJMenuBar(menubar);
748 static String replace_extension(String input, String extension) {
749 int dot = input.lastIndexOf(".");
751 input = input.substring(0,dot);
752 return input.concat(extension);
755 static AltosReader open_logfile(String filename) {
756 File file = new File (filename);
760 in = new FileInputStream(file);
761 if (filename.endsWith("eeprom"))
762 return new AltosEepromReader(in);
764 return new AltosTelemetryReader(in);
765 } catch (FileNotFoundException fe) {
766 System.out.printf("Cannot open '%s'\n", filename);
771 static AltosCSV open_csv(String filename) {
772 File file = new File (filename);
774 return new AltosCSV(file);
775 } catch (FileNotFoundException fe) {
776 System.out.printf("Cannot open '%s'\n", filename);
781 static void process_file(String input) {
782 String output = replace_extension(input,".csv");
783 if (input.equals(output)) {
784 System.out.printf("Not processing '%s'\n", input);
787 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
788 AltosReader reader = open_logfile(input);
791 AltosCSV writer = open_csv(output);
794 writer.write(reader);
799 public static void main(final String[] args) {
801 /* Handle batch-mode */
802 if (args.length > 0) {
803 for (int i = 0; i < args.length; i++)
804 process_file(args[i]);
806 AltosUI altosui = new AltosUI();
807 altosui.setVisible(true);