Remove GPS data missing from skytraq. Save max height/accel/speed
[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 gnu.io.CommPortIdentifier;
29
30 import altosui.AltosSerial;
31 import altosui.AltosSerialMonitor;
32 import altosui.AltosTelemetry;
33 import altosui.AltosState;
34
35 class AltosUIMonitor implements AltosSerialMonitor {
36         public void data(String data) {
37                 System.out.println(data);
38         }
39 }
40
41 class AltosFlightStatusTableModel extends AbstractTableModel {
42         private String[] columnNames = {"Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
43         private Object[] data = { 0, "idle", 0, 0 };
44
45         public int getColumnCount() { return columnNames.length; }
46         public int getRowCount() { return 2; }
47         public Object getValueAt(int row, int col) {
48                 if (row == 0)
49                         return columnNames[col];
50                 return data[col];
51         }
52
53         public void setValueAt(Object value, int col) {
54                 data[col] = value;
55                 fireTableCellUpdated(1, col);
56         }
57
58         public void setValueAt(Object value, int row, int col) {
59                 setValueAt(value, col);
60         }
61
62         public void set(AltosState state) {
63                 setValueAt(String.format("%1.0f", state.height), 0);
64                 setValueAt(state.data.state, 1);
65                 setValueAt(state.data.rssi, 2);
66                 double speed = state.baro_speed;
67                 if (state.ascent)
68                         speed = state.speed;
69                 setValueAt(String.format("%1.0f", speed), 3);
70         }
71 }
72
73 class AltosFlightStatusCellRenderer extends DefaultTableCellRenderer {
74
75         static Font statusFont = new Font("SansSerif", Font.BOLD, 24);
76
77         @Override public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected,
78                                                         boolean hasFocus, int row, int column)
79         {
80                 Component cell = super.getTableCellRendererComponent
81                         (table, value, isSelected, hasFocus, row, column);
82                 System.out.println("Selecting new font for cell " + row + " " + column + " " + statusFont);
83                 cell.setFont(statusFont);
84                 return cell;
85         }
86
87         public AltosFlightStatusCellRenderer () {
88                 super();
89                 System.out.println("Made a status cell renderer\n");
90         }
91 }
92
93 class AltosFlightInfoTableModel extends AbstractTableModel {
94         private String[] columnNames = {"Field", "Value"};
95
96         class InfoLine {
97                 String  name;
98                 String  value;
99
100                 public InfoLine(String n, String v) {
101                         name = n;
102                         value = v;
103                 }
104         }
105
106         private ArrayList<InfoLine> rows = new ArrayList<InfoLine>();
107
108         public int getColumnCount() { return columnNames.length; }
109         public String getColumnName(int col) { return columnNames[col]; }
110
111         public int getRowCount() { return 20; }
112
113         public Object getValueAt(int row, int col) {
114                 if (row >= rows.size())
115                         return "";
116                 if (col == 0)
117                         return rows.get(row).name;
118                 else
119                         return rows.get(row).value;
120         }
121
122         int     current_row = 0;
123         int     prev_num_rows = 0;
124
125         public void resetRow() {
126                 current_row = 0;
127         }
128         public void addRow(String name, String value) {
129                 if (current_row >= rows.size())
130                         rows.add(current_row, new InfoLine(name, value));
131                 else
132                         rows.set(current_row, new InfoLine(name, value));
133                 current_row++;
134         }
135         public void finish() {
136                 if (current_row > prev_num_rows) {
137                         fireTableRowsInserted(prev_num_rows, current_row - 1);
138                         prev_num_rows = current_row;
139                 }
140                 fireTableDataChanged();
141         }
142 }
143
144 public class AltosUI extends JFrame {
145         private int channel = -1;
146
147         private AltosFlightStatusTableModel flightStatusModel;
148         private JTable flightStatus;
149
150         static final int info_columns = 3;
151
152         private AltosFlightInfoTableModel[] flightInfoModel;
153         private JTable[] flightInfo;
154         private AltosSerial serialLine;
155         private Box[] ibox;
156         private Box vbox;
157         private Box hbox;
158
159         private Font statusFont = new Font("SansSerif", Font.BOLD, 24);
160         private Font infoLabelFont = new Font("SansSerif", Font.PLAIN, 14);
161         private Font infoValueFont = new Font("Monospaced", Font.PLAIN, 14);
162
163         public AltosUI() {
164
165                 String[] statusNames = { "Height (m)", "State", "RSSI (dBm)", "Speed (m/s)" };
166                 Object[][] statusData = { { "0", "pad", "-50", "0" } };
167
168                 vbox = Box.createVerticalBox();
169                 this.add(vbox);
170
171                 flightStatusModel = new AltosFlightStatusTableModel();
172                 flightStatus = new JTable(flightStatusModel);
173                 flightStatus.setFont(statusFont);
174                 TableColumnModel tcm = flightStatus.getColumnModel();
175                 for (int i = 0; i < flightStatusModel.getColumnCount(); i++) {
176                         DefaultTableCellRenderer       r = new DefaultTableCellRenderer();
177                         r.setFont(statusFont);
178                         r.setHorizontalAlignment(SwingConstants.CENTER);
179                         tcm.getColumn(i).setCellRenderer(r);
180                 }
181
182                 FontMetrics     statusMetrics = flightStatus.getFontMetrics(statusFont);
183                 int statusHeight = (statusMetrics.getHeight() + statusMetrics.getLeading()) * 15 / 10;
184                 flightStatus.setRowHeight(statusHeight);
185                 flightStatus.setShowGrid(false);
186
187                 vbox.add(flightStatus);
188
189                 hbox = Box.createHorizontalBox();
190                 vbox.add(hbox);
191
192                 flightInfo = new JTable[3];
193                 flightInfoModel = new AltosFlightInfoTableModel[3];
194                 ibox = new Box[3];
195                 FontMetrics     infoValueMetrics = flightStatus.getFontMetrics(infoValueFont);
196                 int infoHeight = (infoValueMetrics.getHeight() + infoValueMetrics.getLeading()) * 20 / 10;
197
198                 for (int i = 0; i < info_columns; i++) {
199                         ibox[i] = Box.createVerticalBox();
200                         flightInfoModel[i] = new AltosFlightInfoTableModel();
201                         flightInfo[i] = new JTable(flightInfoModel[i]);
202                         flightInfo[i].setFont(infoValueFont);
203                         flightInfo[i].setRowHeight(infoHeight);
204                         flightInfo[i].setShowGrid(true);
205                         ibox[i].add(flightInfo[i].getTableHeader());
206                         ibox[i].add(flightInfo[i]);
207                         hbox.add(ibox[i]);
208                 }
209
210                 setTitle("AltOS");
211
212                 createMenu();
213
214                 serialLine = new AltosSerial();
215                 serialLine.monitor(new AltosUIMonitor());
216                 int dpi = Toolkit.getDefaultToolkit().getScreenResolution();
217                 this.setSize(new Dimension (infoValueMetrics.charWidth('0') * 6 * 20,
218                                             statusHeight * 4 + infoHeight * 17));
219                 this.validate();
220                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
221                 addWindowListener(new WindowAdapter() {
222                         @Override
223                         public void windowClosing(WindowEvent e) {
224                                 System.exit(0);
225                         }
226                 });
227         }
228
229         public void info_reset() {
230                 for (int i = 0; i < info_columns; i++)
231                         flightInfoModel[i].resetRow();
232         }
233
234         public void info_add_row(int col, String name, String value) {
235                 flightInfoModel[col].addRow(name, value);
236         }
237
238         public void info_add_row(int col, String name, String format, Object value) {
239                 flightInfoModel[col].addRow(name, String.format(format, value));
240         }
241
242         public void info_add_row(int col, String name, String format, Object v1, Object v2) {
243                 flightInfoModel[col].addRow(name, String.format(format, v1, v2));
244         }
245
246         public void info_add_row(int col, String name, String format, Object v1, Object v2, Object v3) {
247                 flightInfoModel[col].addRow(name, String.format(format, v1, v2, v3));
248         }
249
250         public void info_add_deg(int col, String name, double v, int pos, int neg) {
251                 int     c = pos;
252                 if (v < 0) {
253                         c = neg;
254                         v = -v;
255                 }
256                 double  deg = Math.floor(v);
257                 double  min = (v - deg) * 60;
258
259                 flightInfoModel[col].addRow(name, String.format("%3.0f°%08.5f'", deg, min));
260         }
261
262         public void info_finish() {
263                 for (int i = 0; i < info_columns; i++)
264                         flightInfoModel[i].finish();
265         }
266
267         static final int MIN_PAD_SAMPLES = 10;
268
269         public void show(AltosState state) {
270                 flightStatusModel.set(state);
271
272                 info_reset();
273                 if (state.npad >= MIN_PAD_SAMPLES)
274                         info_add_row(0, "Ground state", "%s", "ready");
275                 else
276                         info_add_row(0, "Ground state", "wait (%d)",
277                                      MIN_PAD_SAMPLES - state.npad);
278                 info_add_row(0, "Rocket state", "%s", state.data.state);
279                 info_add_row(0, "Callsign", "%s", state.data.callsign);
280                 info_add_row(0, "Rocket serial", "%6d", state.data.serial);
281                 info_add_row(0, "Rocket flight", "%6d", state.data.flight);
282
283                 info_add_row(0, "RSSI", "%6d    dBm", state.data.rssi);
284                 info_add_row(0, "Height", "%6.0f    m", state.height);
285                 info_add_row(0, "Max height", "%6.0f    m", state.max_height);
286                 info_add_row(0, "Acceleration", "%8.1f  m/s²", state.acceleration);
287                 info_add_row(0, "Max acceleration", "%8.1f  m/s²", state.max_acceleration);
288                 info_add_row(0, "Speed", "%8.1f  m/s", state.ascent ? state.speed : state.baro_speed);
289                 info_add_row(0, "Max Speed", "%8.1f  m/s", state.max_speed);
290                 info_add_row(0, "Temperature", "%9.2f °C", state.temperature);
291                 info_add_row(0, "Battery", "%9.2f V", state.battery);
292                 info_add_row(0, "Drogue", "%9.2f V", state.drogue_sense);
293                 info_add_row(0, "Main", "%9.2f V", state.main_sense);
294                 info_add_row(0, "Pad altitude", "%6.0f    m", state.ground_altitude);
295                 if (state.gps == null) {
296                         info_add_row(1, "GPS", "not available");
297                 } else {
298                         if (state.data.gps.gps_locked)
299                                 info_add_row(1, "GPS", "   locked");
300                         else if (state.data.gps.gps_connected)
301                                 info_add_row(1, "GPS", " unlocked");
302                         else
303                                 info_add_row(1, "GPS", "  missing");
304                         info_add_row(1, "Satellites", "%6d", state.data.gps.nsat);
305                         info_add_deg(1, "Latitude", state.gps.lat, 'N', 'S');
306                         info_add_deg(1, "Longitude", state.gps.lon, 'E', 'W');
307                         info_add_row(1, "GPS altitude", "%6d", state.gps.alt);
308                         info_add_row(1, "GPS height", "%6.0f", state.gps_height);
309
310                         /* The SkyTraq GPS doesn't report these values */
311                         if (false) {
312                                 info_add_row(1, "GPS ground speed", "%8.1f m/s %3d°",
313                                              state.gps.ground_speed,
314                                              state.gps.course);
315                                 info_add_row(1, "GPS climb rate", "%8.1f m/s",
316                                              state.gps.climb_rate);
317                                 info_add_row(1, "GPS error", "%6d m(h)%3d m(v)",
318                                              state.gps.h_error, state.gps.v_error);
319                         }
320                         info_add_row(1, "GPS hdop", "%8.1f", state.gps.hdop);
321
322                         if (state.npad > 0) {
323                                 if (state.from_pad != null) {
324                                         info_add_row(1, "Distance from pad", "%6.0f m", state.from_pad.distance);
325                                         info_add_row(1, "Direction from pad", "%6.0f°", state.from_pad.bearing);
326                                 } else {
327                                         info_add_row(1, "Distance from pad", "unknown");
328                                         info_add_row(1, "Direction from pad", "unknown");
329                                 }
330                                 info_add_deg(1, "Pad latitude", state.pad_lat, 'N', 'S');
331                                 info_add_deg(1, "Pad longitude", state.pad_lon, 'E', 'W');
332                                 info_add_row(1, "Pad GPS alt", "%6.0f m", state.pad_alt);
333                         }
334                         info_add_row(1, "GPS date", "%04d-%02d-%02d",
335                                        state.gps.gps_time.year,
336                                        state.gps.gps_time.month,
337                                        state.gps.gps_time.day);
338                         info_add_row(1, "GPS time", "  %02d:%02d:%02d",
339                                        state.gps.gps_time.hour,
340                                        state.gps.gps_time.minute,
341                                        state.gps.gps_time.second);
342                         int     nsat_vis = 0;
343                         int     c;
344
345                         if (state.gps.cc_gps_sat == null)
346                                 info_add_row(2, "Satellites Visible", "%4d", 0);
347                         else {
348                                 info_add_row(2, "Satellites Visible", "%4d", state.gps.cc_gps_sat.length);
349                                 for (c = 0; c < state.gps.cc_gps_sat.length; c++) {
350                                         info_add_row(2, "Satellite id,C/N0",
351                                                      "%4d, %4d",
352                                                      state.gps.cc_gps_sat[c].svid,
353                                                      state.gps.cc_gps_sat[c].c_n0);
354                                 }
355                         }
356                 }
357                 info_finish();
358         }
359
360
361         final JFileChooser deviceChooser = new JFileChooser();
362         final JFileChooser logdirChooser = new JFileChooser();
363         final String logdirName = "TeleMetrum";
364         File logdir = null;
365
366         private void setLogdir() {
367                 if (logdir == null)
368                         logdir = new File(logdirChooser.getCurrentDirectory(), logdirName);
369                 logdirChooser.setCurrentDirectory(logdir);
370         }
371
372         private void makeLogdir() {
373                 setLogdir();
374                 if (!logdir.exists()) {
375                         if (!logdir.mkdirs())
376                                 JOptionPane.showMessageDialog(AltosUI.this,
377                                                               logdir.getName(),
378                                                               "Cannot create directory",
379                                                               JOptionPane.ERROR_MESSAGE);
380                 } else if (!logdir.isDirectory()) {
381                         JOptionPane.showMessageDialog(AltosUI.this,
382                                                       logdir.getName(),
383                                                       "Is not a directory",
384                                                       JOptionPane.ERROR_MESSAGE);
385                 }
386         }
387
388         private void PickSerialDevice() {
389                 java.util.Enumeration<CommPortIdentifier> port_list = CommPortIdentifier.getPortIdentifiers();
390                 while (port_list.hasMoreElements()) {
391                         CommPortIdentifier identifier = port_list.nextElement();
392                         System.out.println("Serial port " + identifier.getName());
393                 }
394         }
395
396         private void ConnectToDevice() {
397                 PickSerialDevice();
398                 int returnVal = deviceChooser.showOpenDialog(AltosUI.this);
399
400                 if (returnVal == JFileChooser.APPROVE_OPTION) {
401                         File file = deviceChooser.getSelectedFile();
402                         try {
403                                 serialLine.open(file);
404                         } catch (FileNotFoundException ee) {
405                                 JOptionPane.showMessageDialog(AltosUI.this,
406                                                               file.getName(),
407                                                               "Cannot open serial port",
408                                                               JOptionPane.ERROR_MESSAGE);
409                         }
410                 }
411         }
412
413         String readline(FileInputStream s) throws IOException {
414                 int c;
415                 String  line = "";
416
417                 while ((c = s.read()) != -1) {
418                         if (c == '\r')
419                                 continue;
420                         if (c == '\n')
421                                 return line;
422                         line = line + (char) c;
423                 }
424                 return null;
425         }
426
427         /*
428          * Open an existing telemetry file and replay it in realtime
429          */
430
431         class ReplayThread extends Thread {
432                 FileInputStream replay;
433                 String filename;
434
435                 ReplayThread(FileInputStream in, String name) {
436                         replay = in;
437                         filename = name;
438                 }
439
440                 public void run() {
441                         String  line;
442                         AltosState      state = null;
443                         try {
444                                 while ((line = readline(replay)) != null) {
445                                         try {
446                                                 AltosTelemetry  t = new AltosTelemetry(line);
447                                                 state = new AltosState(t, state);
448                                                 show(state);
449                                                 try {
450                                                         if (state.state > AltosTelemetry.ao_flight_pad)
451                                                                 Thread.sleep((int) (state.time_change * 1000));
452                                                 } catch (InterruptedException e) {}
453                                         } catch (ParseException pp) {
454                                                 JOptionPane.showMessageDialog(AltosUI.this,
455                                                                               line,
456                                                                               "error parsing",
457                                                                               JOptionPane.ERROR_MESSAGE);
458                                                 break;
459                                         }
460                                 }
461                         } catch (IOException ee) {
462                                 JOptionPane.showMessageDialog(AltosUI.this,
463                                                               filename,
464                                                               "error reading",
465                                                               JOptionPane.ERROR_MESSAGE);
466                         } finally {
467                                 try {
468                                         replay.close();
469                                 } catch (IOException e) {}
470                         }
471                 }
472         }
473
474         private void Replay() {
475                 setLogdir();
476                 logdirChooser.setDialogTitle("Select Telemetry File");
477                 logdirChooser.setFileFilter(new FileNameExtensionFilter("Telemetry file", "telem"));
478                 int returnVal = logdirChooser.showOpenDialog(AltosUI.this);
479
480                 if (returnVal == JFileChooser.APPROVE_OPTION) {
481                         File file = logdirChooser.getSelectedFile();
482                         if (file == null)
483                                 System.out.println("No file selected?");
484                         String  filename = file.getName();
485                         try {
486                                 FileInputStream replay = new FileInputStream(file);
487                                 ReplayThread    thread = new ReplayThread(replay, filename);
488                                 thread.start();
489                         } catch (FileNotFoundException ee) {
490                                 JOptionPane.showMessageDialog(AltosUI.this,
491                                                               filename,
492                                                               "Cannot open serial port",
493                                                               JOptionPane.ERROR_MESSAGE);
494                         }
495                 }
496         }
497
498         private void SaveFlightData() {
499         }
500
501         private void createMenu() {
502                 JMenuBar menubar = new JMenuBar();
503                 JMenu menu;
504                 JMenuItem item;
505                 JRadioButtonMenuItem radioitem;
506
507                 // File menu
508                 {
509                         menu = new JMenu("File");
510                         menu.setMnemonic(KeyEvent.VK_F);
511                         menubar.add(menu);
512
513                         item = new JMenuItem("Quit",KeyEvent.VK_Q);
514                         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
515                                                                    ActionEvent.CTRL_MASK));
516                         item.addActionListener(new ActionListener() {
517                                         public void actionPerformed(ActionEvent e) {
518                                                 System.exit(0);
519                                         }
520                                 });
521                         menu.add(item);
522                 }
523
524                 // Device menu
525                 {
526                         menu = new JMenu("Device");
527                         menu.setMnemonic(KeyEvent.VK_D);
528                         menubar.add(menu);
529
530                         item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
531                         item.addActionListener(new ActionListener() {
532                                         public void actionPerformed(ActionEvent e) {
533                                                 ConnectToDevice();
534                                         }
535                                 });
536                         menu.add(item);
537
538                         item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
539                         item.addActionListener(new ActionListener() {
540                                         public void actionPerformed(ActionEvent e) {
541                                                 serialLine.close();
542                                         }
543                                 });
544                         menu.add(item);
545
546                         menu.addSeparator();
547
548                         item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
549                         item.addActionListener(new ActionListener() {
550                                         public void actionPerformed(ActionEvent e) {
551                                                 SaveFlightData();
552                                         }
553                                 });
554                         menu.add(item);
555
556                         item = new JMenuItem("Replay",KeyEvent.VK_R);
557                         item.addActionListener(new ActionListener() {
558                                         public void actionPerformed(ActionEvent e) {
559                                                 Replay();
560                                         }
561                                 });
562                         menu.add(item);
563                 }
564                 // Log menu
565                 {
566                         menu = new JMenu("Log");
567                         menu.setMnemonic(KeyEvent.VK_L);
568                         menubar.add(menu);
569
570                         item = new JMenuItem("New Log",KeyEvent.VK_N);
571                         item.addActionListener(new ActionListener() {
572                                         public void actionPerformed(ActionEvent e) {
573                                         }
574                                 });
575                         menu.add(item);
576
577                         item = new JMenuItem("Configure Log",KeyEvent.VK_C);
578                         item.addActionListener(new ActionListener() {
579                                         public void actionPerformed(ActionEvent e) {
580                                         }
581                                 });
582                         menu.add(item);
583                 }
584                 // Voice menu
585                 {
586                         menu = new JMenu("Voice", true);
587                         menu.setMnemonic(KeyEvent.VK_V);
588                         menubar.add(menu);
589
590                         radioitem = new JRadioButtonMenuItem("Enable Voice");
591                         radioitem.addActionListener(new ActionListener() {
592                                         public void actionPerformed(ActionEvent e) {
593                                         }
594                                 });
595                         menu.add(radioitem);
596                 }
597
598                 // Channel menu
599                 {
600                         menu = new JMenu("Channel", true);
601                         menu.setMnemonic(KeyEvent.VK_C);
602                         menubar.add(menu);
603                         ButtonGroup group = new ButtonGroup();
604
605                         for (int c = 0; c <= 9; c++) {
606                                 radioitem = new JRadioButtonMenuItem(String.format("Channel %1d (%7.3fMHz)", c,
607                                                                                    434.550 + c * 0.1),
608                                                                      c == 0);
609                                 radioitem.setActionCommand(String.format("%d", c));
610                                 radioitem.addActionListener(new ActionListener() {
611                                                 public void actionPerformed(ActionEvent e) {
612                                                         System.out.println("Command: " + e.getActionCommand() + " param: " +
613                                                                            e.paramString());
614                                                 }
615                                         });
616                                 menu.add(radioitem);
617                                 group.add(radioitem);
618                         }
619                 }
620
621                 this.setJMenuBar(menubar);
622
623         }
624         public static void main(final String[] args) {
625                 AltosUI altosui = new AltosUI();
626                 altosui.setVisible(true);
627         }
628 }