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();
73 public static boolean load_library(Frame frame) {
74 if (!AltosDevice.load_library()) {
75 JOptionPane.showMessageDialog(frame,
76 String.format("No AltOS library in \"%s\"",
77 System.getProperty("java.library.path","<undefined>")),
78 "Cannot load device access library",
79 JOptionPane.ERROR_MESSAGE);
89 String[] statusNames = { "Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
90 Object[][] statusData = { { "0", "pad", "-50", "0" } };
92 java.net.URL imgURL = AltosUI.class.getResource("/altus-metrum-16x16.jpg");
94 setIconImage(new ImageIcon(imgURL).getImage());
96 AltosPreferences.init(this);
98 vbox = Box.createVerticalBox();
101 flightStatusModel = new AltosFlightStatusTableModel();
102 flightStatus = new JTable(flightStatusModel);
103 flightStatus.setFont(statusFont);
104 TableColumnModel tcm = flightStatus.getColumnModel();
105 for (int i = 0; i < flightStatusModel.getColumnCount(); i++) {
106 DefaultTableCellRenderer r = new DefaultTableCellRenderer();
107 r.setFont(statusFont);
108 r.setHorizontalAlignment(SwingConstants.CENTER);
109 tcm.getColumn(i).setCellRenderer(r);
112 FontMetrics statusMetrics = flightStatus.getFontMetrics(statusFont);
113 int statusHeight = (statusMetrics.getHeight() + statusMetrics.getLeading()) * 15 / 10;
114 flightStatus.setRowHeight(statusHeight);
115 flightStatus.setShowGrid(false);
117 vbox.add(flightStatus);
119 hbox = Box.createHorizontalBox();
122 flightInfo = new JTable[3];
123 flightInfoModel = new AltosFlightInfoTableModel[3];
125 FontMetrics infoValueMetrics = flightStatus.getFontMetrics(infoValueFont);
126 int infoHeight = (infoValueMetrics.getHeight() + infoValueMetrics.getLeading()) * 20 / 10;
128 for (int i = 0; i < info_columns; i++) {
129 ibox[i] = Box.createVerticalBox();
130 flightInfoModel[i] = new AltosFlightInfoTableModel();
131 flightInfo[i] = new JTable(flightInfoModel[i]);
132 flightInfo[i].setFont(infoValueFont);
133 flightInfo[i].setRowHeight(infoHeight);
134 flightInfo[i].setShowGrid(true);
135 ibox[i].add(flightInfo[i].getTableHeader());
136 ibox[i].add(flightInfo[i]);
144 serial_line = new AltosSerial();
145 altos_log = new AltosLog(serial_line);
146 int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
147 this.setSize(new Dimension (infoValueMetrics.charWidth('0') * 6 * 20,
148 statusHeight * 4 + infoHeight * 17));
150 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
151 addWindowListener(new WindowAdapter() {
153 public void windowClosing(WindowEvent e) {
157 voice.speak("Rocket flight monitor ready.");
160 public void info_reset() {
161 for (int i = 0; i < info_columns; i++)
162 flightInfoModel[i].resetRow();
165 public void info_add_row(int col, String name, String value) {
166 flightInfoModel[col].addRow(name, value);
169 public void info_add_row(int col, String name, String format, Object... parameters) {
170 flightInfoModel[col].addRow(name, String.format(format, parameters));
173 public void info_add_deg(int col, String name, double v, int pos, int neg) {
179 double deg = Math.floor(v);
180 double min = (v - deg) * 60;
182 flightInfoModel[col].addRow(name, String.format("%3.0f°%08.5f'", deg, min));
185 public void info_finish() {
186 for (int i = 0; i < info_columns; i++)
187 flightInfoModel[i].finish();
190 public void show(AltosState state, int crc_errors) {
193 flightStatusModel.set(state);
196 info_add_row(0, "Rocket state", "%s", state.data.state());
197 info_add_row(0, "Callsign", "%s", state.data.callsign);
198 info_add_row(0, "Rocket serial", "%6d", state.data.serial);
199 info_add_row(0, "Rocket flight", "%6d", state.data.flight);
201 info_add_row(0, "RSSI", "%6d dBm", state.data.rssi);
202 info_add_row(0, "CRC Errors", "%6d", crc_errors);
203 info_add_row(0, "Height", "%6.0f m", state.height);
204 info_add_row(0, "Max height", "%6.0f m", state.max_height);
205 info_add_row(0, "Acceleration", "%8.1f m/s²", state.acceleration);
206 info_add_row(0, "Max acceleration", "%8.1f m/s²", state.max_acceleration);
207 info_add_row(0, "Speed", "%8.1f m/s", state.ascent ? state.speed : state.baro_speed);
208 info_add_row(0, "Max Speed", "%8.1f m/s", state.max_speed);
209 info_add_row(0, "Temperature", "%9.2f °C", state.temperature);
210 info_add_row(0, "Battery", "%9.2f V", state.battery);
211 info_add_row(0, "Drogue", "%9.2f V", state.drogue_sense);
212 info_add_row(0, "Main", "%9.2f V", state.main_sense);
213 info_add_row(0, "Pad altitude", "%6.0f m", state.ground_altitude);
214 if (state.gps == null) {
215 info_add_row(1, "GPS", "not available");
218 info_add_row(1, "GPS state", "%s", "ready");
220 info_add_row(1, "GPS state", "wait (%d)",
222 if (state.data.gps.locked)
223 info_add_row(1, "GPS", " locked");
224 else if (state.data.gps.connected)
225 info_add_row(1, "GPS", " unlocked");
227 info_add_row(1, "GPS", " missing");
228 info_add_row(1, "Satellites", "%6d", state.data.gps.nsat);
229 info_add_deg(1, "Latitude", state.gps.lat, 'N', 'S');
230 info_add_deg(1, "Longitude", state.gps.lon, 'E', 'W');
231 info_add_row(1, "GPS altitude", "%6d", state.gps.alt);
232 info_add_row(1, "GPS height", "%6.0f", state.gps_height);
234 /* The SkyTraq GPS doesn't report these values */
236 info_add_row(1, "GPS ground speed", "%8.1f m/s %3d°",
237 state.gps.ground_speed,
239 info_add_row(1, "GPS climb rate", "%8.1f m/s",
240 state.gps.climb_rate);
241 info_add_row(1, "GPS error", "%6d m(h)%3d m(v)",
242 state.gps.h_error, state.gps.v_error);
244 info_add_row(1, "GPS hdop", "%8.1f", state.gps.hdop);
246 if (state.npad > 0) {
247 if (state.from_pad != null) {
248 info_add_row(1, "Distance from pad", "%6d m",
249 (int) (state.from_pad.distance + 0.5));
250 info_add_row(1, "Direction from pad", "%6d°",
251 (int) (state.from_pad.bearing + 0.5));
252 info_add_row(1, "Elevation from pad", "%6d°",
253 (int) (state.elevation + 0.5));
254 info_add_row(1, "Range from pad", "%6d m",
255 (int) (state.range + 0.5));
257 info_add_row(1, "Distance from pad", "unknown");
258 info_add_row(1, "Direction from pad", "unknown");
259 info_add_row(1, "Elevation from pad", "unknown");
260 info_add_row(1, "Range from pad", "unknown");
262 info_add_deg(1, "Pad latitude", state.pad_lat, 'N', 'S');
263 info_add_deg(1, "Pad longitude", state.pad_lon, 'E', 'W');
264 info_add_row(1, "Pad GPS alt", "%6.0f m", state.pad_alt);
266 info_add_row(1, "GPS date", "%04d-%02d-%02d",
270 info_add_row(1, "GPS time", " %02d:%02d:%02d",
277 if (state.gps.cc_gps_sat == null)
278 info_add_row(2, "Satellites Visible", "%4d", 0);
280 info_add_row(2, "Satellites Visible", "%4d", state.gps.cc_gps_sat.length);
281 for (c = 0; c < state.gps.cc_gps_sat.length; c++) {
282 info_add_row(2, "Satellite id,C/N0",
284 state.gps.cc_gps_sat[c].svid,
285 state.gps.cc_gps_sat[c].c_n0);
292 class IdleThread extends Thread {
295 private AltosState state;
296 int reported_landing;
300 public synchronized void report(boolean last) {
304 /* reset the landing count once we hear about a new flight */
305 if (state.state < Altos.ao_flight_drogue)
306 reported_landing = 0;
308 /* Shut up once the rocket is on the ground */
309 if (reported_landing > 2) {
313 /* If the rocket isn't on the pad, then report height */
314 if (Altos.ao_flight_drogue <= state.state &&
315 state.state < Altos.ao_flight_landed &&
318 voice.speak("Height %d, bearing %d, elevation %d, range %d.\n",
319 (int) (state.height + 0.5),
320 (int) (state.from_pad.bearing + 0.5),
321 (int) (state.elevation + 0.5),
322 (int) (state.range + 0.5));
323 } else if (state.state > Altos.ao_flight_pad) {
324 voice.speak("%d meters", (int) (state.height + 0.5));
326 reported_landing = 0;
329 /* If the rocket is coming down, check to see if it has landed;
330 * either we've got a landed report or we haven't heard from it in
333 if (state.state >= Altos.ao_flight_drogue &&
335 System.currentTimeMillis() - state.report_time >= 15000 ||
336 state.state == Altos.ao_flight_landed))
338 if (Math.abs(state.baro_speed) < 20 && state.height < 100)
339 voice.speak("rocket landed safely");
341 voice.speak("rocket may have crashed");
342 if (state.from_pad != null)
343 voice.speak("Bearing %d degrees, range %d meters.",
344 (int) (state.from_pad.bearing + 0.5),
345 (int) (state.from_pad.distance + 0.5));
351 return System.currentTimeMillis();
354 void set_report_time() {
355 report_time = now() + report_interval;
360 reported_landing = 0;
362 report_interval = 10000;
368 synchronized (this) {
369 long sleep_time = report_time - now();
377 } catch (InterruptedException ie) {
380 } catch (InterruptedException iie) { }
384 public synchronized void notice(AltosState new_state, boolean spoken) {
385 AltosState old_state = state;
387 if (!started && state.state > Altos.ao_flight_pad) {
392 if (state.state < Altos.ao_flight_drogue)
393 report_interval = 10000;
395 report_interval = 20000;
396 if (old_state != null && old_state.state != state.state) {
404 private boolean tell(AltosState state, AltosState old_state) {
406 if (old_state == null || old_state.state != state.state) {
407 voice.speak(state.data.state());
408 if ((old_state == null || old_state.state <= Altos.ao_flight_boost) &&
409 state.state > Altos.ao_flight_boost) {
410 voice.speak("max speed: %d meters per second.",
411 (int) (state.max_speed + 0.5));
413 } else if ((old_state == null || old_state.state < Altos.ao_flight_drogue) &&
414 state.state >= Altos.ao_flight_drogue) {
415 voice.speak("max height: %d meters.",
416 (int) (state.max_height + 0.5));
420 if (old_state == null || old_state.gps_ready != state.gps_ready) {
421 if (state.gps_ready) {
422 voice.speak("GPS ready");
425 else if (old_state != null) {
426 voice.speak("GPS lost");
434 class DisplayThread extends Thread {
435 IdleThread idle_thread;
443 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException { return null; }
445 void close(boolean interrupted) { }
447 void update(AltosState state) throws InterruptedException { }
450 boolean interrupted = false;
452 AltosState state = null;
453 AltosState old_state = null;
456 idle_thread = new IdleThread();
463 AltosRecord record = read();
467 state = new AltosState(record, state);
469 show(state, crc_errors);
470 told = tell(state, old_state);
471 idle_thread.notice(state, told);
472 } catch (ParseException pp) {
473 System.out.printf("Parse error: %d \"%s\"\n", pp.getErrorOffset(), pp.getMessage());
474 } catch (AltosCRCException ce) {
476 show(state, crc_errors);
479 } catch (InterruptedException ee) {
481 } catch (IOException ie) {
482 JOptionPane.showMessageDialog(AltosUI.this,
483 String.format("Error reading from \"%s\"", name),
484 "Telemetry Read Error",
485 JOptionPane.ERROR_MESSAGE);
488 idle_thread.interrupt();
491 } catch (InterruptedException ie) {}
495 public void report() {
496 if (idle_thread != null)
497 idle_thread.report(true);
501 class DeviceThread extends DisplayThread {
503 LinkedBlockingQueue<AltosLine> telem;
505 AltosRecord read() throws InterruptedException, ParseException, AltosCRCException, IOException {
506 AltosLine l = telem.take();
508 throw new IOException("IO error");
509 return new AltosTelemetry(l.line);
512 void close(boolean interrupted) {
514 serial.remove_monitor(telem);
517 public DeviceThread(AltosSerial s, String in_name) {
519 telem = new LinkedBlockingQueue<AltosLine>();
520 serial.add_monitor(telem);
525 private void ConnectToDevice() {
526 AltosDevice device = AltosDeviceDialog.show(AltosUI.this,
527 AltosDevice.product_basestation);
529 if (device != null) {
532 serial_line.open(device);
533 DeviceThread thread = new DeviceThread(serial_line, device.getPath());
534 serial_line.set_channel(AltosPreferences.channel());
535 serial_line.set_callsign(AltosPreferences.callsign());
537 } catch (FileNotFoundException ee) {
538 JOptionPane.showMessageDialog(AltosUI.this,
539 String.format("Cannot open device \"%s\"",
541 "Cannot open target device",
542 JOptionPane.ERROR_MESSAGE);
543 } catch (IOException ee) {
544 JOptionPane.showMessageDialog(AltosUI.this,
547 JOptionPane.ERROR_MESSAGE);
552 void DisconnectFromDevice () {
556 void ConfigureCallsign() {
558 result = JOptionPane.showInputDialog(AltosUI.this,
559 "Configure Callsign",
560 AltosPreferences.callsign());
561 if (result != null) {
562 AltosPreferences.set_callsign(result);
563 if (serial_line != null)
564 serial_line.set_callsign(result);
568 void ConfigureTeleMetrum() {
569 new AltosConfig(AltosUI.this);
573 new AltosFlashUI(AltosUI.this);
577 * Open an existing telemetry file and replay it in realtime
580 class ReplayThread extends DisplayThread {
584 public AltosRecord read() {
586 return reader.read();
587 } catch (IOException ie) {
588 JOptionPane.showMessageDialog(AltosUI.this,
591 JOptionPane.ERROR_MESSAGE);
592 } catch (ParseException pe) {
597 public void close (boolean interrupted) {
602 public ReplayThread(AltosReader in_reader, String in_name) {
605 void update(AltosState state) throws InterruptedException {
606 /* Make it run in realtime after the rocket leaves the pad */
607 if (state.state > Altos.ao_flight_pad)
608 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
612 class ReplayTelemetryThread extends ReplayThread {
613 ReplayTelemetryThread(FileInputStream in, String in_name) {
614 super(new AltosTelemetryReader(in), in_name);
619 class ReplayEepromThread extends ReplayThread {
620 ReplayEepromThread(FileInputStream in, String in_name) {
621 super(new AltosEepromReader(in), in_name);
625 Thread display_thread;
627 private void stop_display() {
628 if (display_thread != null && display_thread.isAlive()) {
629 display_thread.interrupt();
631 display_thread.join();
632 } catch (InterruptedException ie) {}
634 display_thread = null;
637 private void run_display(Thread thread) {
639 display_thread = thread;
640 display_thread.start();
644 * Replay a flight from telemetry data
646 private void Replay() {
647 AltosLogfileChooser chooser = new AltosLogfileChooser(
649 AltosReader reader = chooser.runDialog();
651 run_display(new ReplayThread(reader,
652 chooser.filename()));
655 /* Connect to TeleMetrum, either directly or through
656 * a TeleDongle over the packet link
658 private void SaveFlightData() {
659 new AltosEepromDownload(AltosUI.this);
662 /* Load a flight log file and write out a CSV file containing
663 * all of the data in standard units
666 private void ExportData() {
667 new AltosCSVUI(AltosUI.this);
670 /* Load a flight log CSV file and display a pretty graph.
673 private void GraphData() {
674 new AltosGraphUI(AltosUI.this);
677 /* Create the AltosUI menus
679 private void createMenu() {
680 JMenuBar menubar = new JMenuBar();
683 JRadioButtonMenuItem radioitem;
687 menu = new JMenu("File");
688 menu.setMnemonic(KeyEvent.VK_F);
691 item = new JMenuItem("Replay File",KeyEvent.VK_R);
692 item.addActionListener(new ActionListener() {
693 public void actionPerformed(ActionEvent e) {
699 item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
700 item.addActionListener(new ActionListener() {
701 public void actionPerformed(ActionEvent e) {
707 item = new JMenuItem("Flash Image",KeyEvent.VK_F);
708 item.addActionListener(new ActionListener() {
709 public void actionPerformed(ActionEvent e) {
715 item = new JMenuItem("Export Data",KeyEvent.VK_F);
716 item.addActionListener(new ActionListener() {
717 public void actionPerformed(ActionEvent e) {
723 item = new JMenuItem("Graph Data",KeyEvent.VK_F);
724 item.addActionListener(new ActionListener() {
725 public void actionPerformed(ActionEvent e) {
731 item = new JMenuItem("Quit",KeyEvent.VK_Q);
732 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
733 ActionEvent.CTRL_MASK));
734 item.addActionListener(new ActionListener() {
735 public void actionPerformed(ActionEvent e) {
744 menu = new JMenu("Device");
745 menu.setMnemonic(KeyEvent.VK_D);
748 item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
749 item.addActionListener(new ActionListener() {
750 public void actionPerformed(ActionEvent e) {
756 item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
757 item.addActionListener(new ActionListener() {
758 public void actionPerformed(ActionEvent e) {
759 DisconnectFromDevice();
766 item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
767 item.addActionListener(new ActionListener() {
768 public void actionPerformed(ActionEvent e) {
775 item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
776 item.addActionListener(new ActionListener() {
777 public void actionPerformed(ActionEvent e) {
778 ConfigureTeleMetrum();
786 menu = new JMenu("Log");
787 menu.setMnemonic(KeyEvent.VK_L);
790 item = new JMenuItem("New Log",KeyEvent.VK_N);
791 item.addActionListener(new ActionListener() {
792 public void actionPerformed(ActionEvent e) {
797 item = new JMenuItem("Configure Log",KeyEvent.VK_C);
798 item.addActionListener(new ActionListener() {
799 public void actionPerformed(ActionEvent e) {
800 AltosPreferences.ConfigureLog();
807 menu = new JMenu("Voice", true);
808 menu.setMnemonic(KeyEvent.VK_V);
811 radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
812 radioitem.addActionListener(new ActionListener() {
813 public void actionPerformed(ActionEvent e) {
814 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
815 boolean enabled = item.isSelected();
816 AltosPreferences.set_voice(enabled);
818 voice.speak_always("Enable voice.");
820 voice.speak_always("Disable voice.");
824 item = new JMenuItem("Test Voice",KeyEvent.VK_T);
825 item.addActionListener(new ActionListener() {
826 public void actionPerformed(ActionEvent e) {
827 voice.speak("That's one small step for man; one giant leap for mankind.");
835 menu = new AltosChannelMenu(AltosPreferences.channel());
836 menu.addActionListener(new ActionListener() {
837 public void actionPerformed(ActionEvent e) {
838 int new_channel = Integer.parseInt(e.getActionCommand());
839 AltosPreferences.set_channel(new_channel);
840 serial_line.set_channel(new_channel);
843 menu.setMnemonic(KeyEvent.VK_C);
847 this.setJMenuBar(menubar);
851 static String replace_extension(String input, String extension) {
852 int dot = input.lastIndexOf(".");
854 input = input.substring(0,dot);
855 return input.concat(extension);
858 static AltosReader open_logfile(String filename) {
859 File file = new File (filename);
863 in = new FileInputStream(file);
864 if (filename.endsWith("eeprom"))
865 return new AltosEepromReader(in);
867 return new AltosTelemetryReader(in);
868 } catch (FileNotFoundException fe) {
869 System.out.printf("Cannot open '%s'\n", filename);
874 static AltosCSV open_csv(String filename) {
875 File file = new File (filename);
877 return new AltosCSV(file);
878 } catch (FileNotFoundException fe) {
879 System.out.printf("Cannot open '%s'\n", filename);
884 static void process_file(String input) {
885 String output = replace_extension(input,".csv");
886 if (input.equals(output)) {
887 System.out.printf("Not processing '%s'\n", input);
890 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
891 AltosReader reader = open_logfile(input);
894 AltosCSV writer = open_csv(output);
897 writer.write(reader);
902 public static void main(final String[] args) {
904 /* Handle batch-mode */
905 if (args.length > 0) {
906 for (int i = 0; i < args.length; i++)
907 process_file(args[i]);
909 AltosUI altosui = new AltosUI();
910 altosui.setVisible(true);