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, AltosDevice.BaseStation);
528 if (device != null) {
531 serial_line.open(device);
532 DeviceThread thread = new DeviceThread(serial_line, device.getPath());
533 serial_line.set_channel(AltosPreferences.channel());
534 serial_line.set_callsign(AltosPreferences.callsign());
536 } catch (FileNotFoundException ee) {
537 JOptionPane.showMessageDialog(AltosUI.this,
538 String.format("Cannot open device \"%s\"",
540 "Cannot open target device",
541 JOptionPane.ERROR_MESSAGE);
542 } catch (IOException ee) {
543 JOptionPane.showMessageDialog(AltosUI.this,
546 JOptionPane.ERROR_MESSAGE);
551 void DisconnectFromDevice () {
555 void ConfigureCallsign() {
557 result = JOptionPane.showInputDialog(AltosUI.this,
558 "Configure Callsign",
559 AltosPreferences.callsign());
560 if (result != null) {
561 AltosPreferences.set_callsign(result);
562 if (serial_line != null)
563 serial_line.set_callsign(result);
567 void ConfigureTeleMetrum() {
568 new AltosConfig(AltosUI.this);
572 new AltosFlashUI(AltosUI.this);
576 * Open an existing telemetry file and replay it in realtime
579 class ReplayThread extends DisplayThread {
583 public AltosRecord read() {
585 return reader.read();
586 } catch (IOException ie) {
587 JOptionPane.showMessageDialog(AltosUI.this,
590 JOptionPane.ERROR_MESSAGE);
591 } catch (ParseException pe) {
596 public void close (boolean interrupted) {
601 public ReplayThread(AltosReader in_reader, String in_name) {
604 void update(AltosState state) throws InterruptedException {
605 /* Make it run in realtime after the rocket leaves the pad */
606 if (state.state > Altos.ao_flight_pad)
607 Thread.sleep((int) (Math.min(state.time_change,10) * 1000));
611 class ReplayTelemetryThread extends ReplayThread {
612 ReplayTelemetryThread(FileInputStream in, String in_name) {
613 super(new AltosTelemetryReader(in), in_name);
618 class ReplayEepromThread extends ReplayThread {
619 ReplayEepromThread(FileInputStream in, String in_name) {
620 super(new AltosEepromReader(in), in_name);
624 Thread display_thread;
626 private void stop_display() {
627 if (display_thread != null && display_thread.isAlive()) {
628 display_thread.interrupt();
630 display_thread.join();
631 } catch (InterruptedException ie) {}
633 display_thread = null;
636 private void run_display(Thread thread) {
638 display_thread = thread;
639 display_thread.start();
643 * Replay a flight from telemetry data
645 private void Replay() {
646 AltosLogfileChooser chooser = new AltosLogfileChooser(
648 AltosReader reader = chooser.runDialog();
650 run_display(new ReplayThread(reader,
651 chooser.filename()));
654 /* Connect to TeleMetrum, either directly or through
655 * a TeleDongle over the packet link
657 private void SaveFlightData() {
658 new AltosEepromDownload(AltosUI.this);
661 /* Load a flight log file and write out a CSV file containing
662 * all of the data in standard units
665 private void ExportData() {
666 new AltosCSVUI(AltosUI.this);
669 /* Create the AltosUI menus
671 private void createMenu() {
672 JMenuBar menubar = new JMenuBar();
675 JRadioButtonMenuItem radioitem;
679 menu = new JMenu("File");
680 menu.setMnemonic(KeyEvent.VK_F);
683 item = new JMenuItem("Replay File",KeyEvent.VK_R);
684 item.addActionListener(new ActionListener() {
685 public void actionPerformed(ActionEvent e) {
691 item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
692 item.addActionListener(new ActionListener() {
693 public void actionPerformed(ActionEvent e) {
699 item = new JMenuItem("Flash Image",KeyEvent.VK_F);
700 item.addActionListener(new ActionListener() {
701 public void actionPerformed(ActionEvent e) {
707 item = new JMenuItem("Export Data",KeyEvent.VK_F);
708 item.addActionListener(new ActionListener() {
709 public void actionPerformed(ActionEvent e) {
715 item = new JMenuItem("Quit",KeyEvent.VK_Q);
716 item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
717 ActionEvent.CTRL_MASK));
718 item.addActionListener(new ActionListener() {
719 public void actionPerformed(ActionEvent e) {
728 menu = new JMenu("Device");
729 menu.setMnemonic(KeyEvent.VK_D);
732 item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
733 item.addActionListener(new ActionListener() {
734 public void actionPerformed(ActionEvent e) {
740 item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
741 item.addActionListener(new ActionListener() {
742 public void actionPerformed(ActionEvent e) {
743 DisconnectFromDevice();
750 item = new JMenuItem("Set Callsign",KeyEvent.VK_S);
751 item.addActionListener(new ActionListener() {
752 public void actionPerformed(ActionEvent e) {
759 item = new JMenuItem("Configure TeleMetrum device",KeyEvent.VK_T);
760 item.addActionListener(new ActionListener() {
761 public void actionPerformed(ActionEvent e) {
762 ConfigureTeleMetrum();
770 menu = new JMenu("Log");
771 menu.setMnemonic(KeyEvent.VK_L);
774 item = new JMenuItem("New Log",KeyEvent.VK_N);
775 item.addActionListener(new ActionListener() {
776 public void actionPerformed(ActionEvent e) {
781 item = new JMenuItem("Configure Log",KeyEvent.VK_C);
782 item.addActionListener(new ActionListener() {
783 public void actionPerformed(ActionEvent e) {
784 AltosPreferences.ConfigureLog();
791 menu = new JMenu("Voice", true);
792 menu.setMnemonic(KeyEvent.VK_V);
795 radioitem = new JRadioButtonMenuItem("Enable Voice", AltosPreferences.voice());
796 radioitem.addActionListener(new ActionListener() {
797 public void actionPerformed(ActionEvent e) {
798 JRadioButtonMenuItem item = (JRadioButtonMenuItem) e.getSource();
799 boolean enabled = item.isSelected();
800 AltosPreferences.set_voice(enabled);
802 voice.speak_always("Enable voice.");
804 voice.speak_always("Disable voice.");
808 item = new JMenuItem("Test Voice",KeyEvent.VK_T);
809 item.addActionListener(new ActionListener() {
810 public void actionPerformed(ActionEvent e) {
811 voice.speak("That's one small step for man; one giant leap for mankind.");
819 menu = new AltosChannelMenu(AltosPreferences.channel());
820 menu.addActionListener(new ActionListener() {
821 public void actionPerformed(ActionEvent e) {
822 int new_channel = Integer.parseInt(e.getActionCommand());
823 AltosPreferences.set_channel(new_channel);
824 serial_line.set_channel(new_channel);
827 menu.setMnemonic(KeyEvent.VK_C);
831 this.setJMenuBar(menubar);
835 static String replace_extension(String input, String extension) {
836 int dot = input.lastIndexOf(".");
838 input = input.substring(0,dot);
839 return input.concat(extension);
842 static AltosReader open_logfile(String filename) {
843 File file = new File (filename);
847 in = new FileInputStream(file);
848 if (filename.endsWith("eeprom"))
849 return new AltosEepromReader(in);
851 return new AltosTelemetryReader(in);
852 } catch (FileNotFoundException fe) {
853 System.out.printf("Cannot open '%s'\n", filename);
858 static AltosCSV open_csv(String filename) {
859 File file = new File (filename);
861 return new AltosCSV(file);
862 } catch (FileNotFoundException fe) {
863 System.out.printf("Cannot open '%s'\n", filename);
868 static void process_file(String input) {
869 String output = replace_extension(input,".csv");
870 if (input.equals(output)) {
871 System.out.printf("Not processing '%s'\n", input);
874 System.out.printf("Processing \"%s\" to \"%s\"\n", input, output);
875 AltosReader reader = open_logfile(input);
878 AltosCSV writer = open_csv(output);
881 writer.write(reader);
886 public static void main(final String[] args) {
888 /* Handle batch-mode */
889 if (args.length > 0) {
890 for (int i = 0; i < args.length; i++)
891 process_file(args[i]);
893 AltosUI altosui = new AltosUI();
894 altosui.setVisible(true);