66c75487638cbe2065df73bc2ea3a7b386c32d6f
[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 * 15,
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, "Satellites", "%6d", state.gps.nsat);
297                 else
298                         info_add_row(1, "Satellites", "%6d", 0);
299                 if (state.gps != null && state.gps.gps_locked) {
300                         info_add_row(1, "GPS", "locked");
301                 } else if (state.gps != null && state.gps.gps_connected) {
302                         info_add_row(1, "GPS", "unlocked");
303                 } else {
304                         info_add_row(1, "GPS", "not available");
305                 }
306                 if (state.gps != null) {
307                         info_add_deg(1, "Latitude", state.gps.lat, 'N', 'S');
308                         info_add_deg(1, "Longitude", state.gps.lon, 'E', 'W');
309                         info_add_row(1, "GPS altitude", "%d", state.gps.alt);
310                         info_add_row(1, "GPS height", "%d", state.gps_height);
311                         info_add_row(1, "GPS date", "%04d-%02d-%02d",
312                                        state.gps.gps_time.year,
313                                        state.gps.gps_time.month,
314                                        state.gps.gps_time.day);
315                         info_add_row(1, "GPS time", "%02d:%02d:%02d",
316                                        state.gps.gps_time.hour,
317                                        state.gps.gps_time.minute,
318                                        state.gps.gps_time.second);
319                         info_add_row(1, "GPS ground speed", "%7.1fm/s %d°",
320                                        state.gps.ground_speed,
321                                        state.gps.course);
322                         info_add_row(1, "GPS climb rate", "%7.1fm/s",
323                                      state.gps.climb_rate);
324                         info_add_row(1, "GPS precision", "%4.1f(hdop) %3dm(h) %3dm(v)",
325                                      state.gps.hdop, state.gps.h_error, state.gps.v_error);
326                 }
327                 if (state.npad > 0) {
328                         info_add_row(1, "Distance from pad", "%5.0fm", state.from_pad.distance);
329                         info_add_row(1, "Direction from pad", "%4.0f°", state.from_pad.bearing);
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", "%gm", state.pad_alt);
333                 }
334                 if (state.gps != null && state.gps.gps_connected) {
335                         int     nsat_vis = 0;
336                         int     c;
337
338                         if (state.gps.cc_gps_sat == null)
339                                 info_add_row(2, "Satellites Visible", "%d", 0);
340                         else {
341                                 info_add_row(2, "Satellites Visible", "%d", state.gps.cc_gps_sat.length);
342                                 for (c = 0; c < state.gps.cc_gps_sat.length; c++) {
343                                         info_add_row(2, "Satellite id,C/N0",
344                                                      "%3d,%2d",
345                                                      state.gps.cc_gps_sat[c].svid,
346                                                      state.gps.cc_gps_sat[c].c_n0);
347                                 }
348                         }
349                 }
350                 info_finish();
351         }
352
353
354         final JFileChooser deviceChooser = new JFileChooser();
355         final JFileChooser logdirChooser = new JFileChooser();
356         final String logdirName = "TeleMetrum";
357         File logdir = null;
358
359         private void setLogdir() {
360                 if (logdir == null)
361                         logdir = new File(logdirChooser.getCurrentDirectory(), logdirName);
362                 logdirChooser.setCurrentDirectory(logdir);
363         }
364
365         private void makeLogdir() {
366                 setLogdir();
367                 if (!logdir.exists()) {
368                         if (!logdir.mkdirs())
369                                 JOptionPane.showMessageDialog(AltosUI.this,
370                                                               logdir.getName(),
371                                                               "Cannot create directory",
372                                                               JOptionPane.ERROR_MESSAGE);
373                 } else if (!logdir.isDirectory()) {
374                         JOptionPane.showMessageDialog(AltosUI.this,
375                                                       logdir.getName(),
376                                                       "Is not a directory",
377                                                       JOptionPane.ERROR_MESSAGE);
378                 }
379         }
380
381         private void PickSerialDevice() {
382                 java.util.Enumeration<CommPortIdentifier> port_list = CommPortIdentifier.getPortIdentifiers();
383                 while (port_list.hasMoreElements()) {
384                         CommPortIdentifier identifier = port_list.nextElement();
385                         System.out.println("Serial port " + identifier.getName());
386                 }
387         }
388
389         private void ConnectToDevice() {
390                 PickSerialDevice();
391                 int returnVal = deviceChooser.showOpenDialog(AltosUI.this);
392
393                 if (returnVal == JFileChooser.APPROVE_OPTION) {
394                         File file = deviceChooser.getSelectedFile();
395                         try {
396                                 serialLine.open(file);
397                         } catch (FileNotFoundException ee) {
398                                 JOptionPane.showMessageDialog(AltosUI.this,
399                                                               file.getName(),
400                                                               "Cannot open serial port",
401                                                               JOptionPane.ERROR_MESSAGE);
402                         }
403                 }
404         }
405
406         String readline(FileInputStream s) throws IOException {
407                 int c;
408                 String  line = "";
409
410                 while ((c = s.read()) != -1) {
411                         if (c == '\r')
412                                 continue;
413                         if (c == '\n')
414                                 return line;
415                         line = line + (char) c;
416                 }
417                 return null;
418         }
419
420         /*
421          * Open an existing telemetry file and replay it in realtime
422          */
423
424         class ReplayThread extends Thread {
425                 FileInputStream replay;
426                 String filename;
427
428                 ReplayThread(FileInputStream in, String name) {
429                         replay = in;
430                         filename = name;
431                 }
432
433                 public void run() {
434                         String  line;
435                         AltosState      state = null;
436                         try {
437                                 while ((line = readline(replay)) != null) {
438                                         try {
439                                                 AltosTelemetry  t = new AltosTelemetry(line);
440                                                 state = new AltosState(t, state);
441                                                 show(state);
442                                                 try {
443                                                         if (state.state > AltosTelemetry.ao_flight_pad)
444                                                                 Thread.sleep((int) (state.time_change * 1000));
445                                                 } catch (InterruptedException e) {}
446                                         } catch (ParseException pp) {
447                                                 JOptionPane.showMessageDialog(AltosUI.this,
448                                                                               line,
449                                                                               "error parsing",
450                                                                               JOptionPane.ERROR_MESSAGE);
451                                                 break;
452                                         }
453                                 }
454                         } catch (IOException ee) {
455                                 JOptionPane.showMessageDialog(AltosUI.this,
456                                                               filename,
457                                                               "error reading",
458                                                               JOptionPane.ERROR_MESSAGE);
459                         } finally {
460                                 try {
461                                         replay.close();
462                                 } catch (IOException e) {}
463                         }
464                 }
465         }
466
467         private void Replay() {
468                 setLogdir();
469                 logdirChooser.setDialogTitle("Select Telemetry File");
470                 logdirChooser.setFileFilter(new FileNameExtensionFilter("Telemetry file", "telem"));
471                 int returnVal = logdirChooser.showOpenDialog(AltosUI.this);
472
473                 if (returnVal == JFileChooser.APPROVE_OPTION) {
474                         File file = logdirChooser.getSelectedFile();
475                         if (file == null)
476                                 System.out.println("No file selected?");
477                         String  filename = file.getName();
478                         try {
479                                 FileInputStream replay = new FileInputStream(file);
480                                 ReplayThread    thread = new ReplayThread(replay, filename);
481                                 thread.start();
482                         } catch (FileNotFoundException ee) {
483                                 JOptionPane.showMessageDialog(AltosUI.this,
484                                                               filename,
485                                                               "Cannot open serial port",
486                                                               JOptionPane.ERROR_MESSAGE);
487                         }
488                 }
489         }
490
491         private void SaveFlightData() {
492         }
493
494         private void createMenu() {
495                 JMenuBar menubar = new JMenuBar();
496                 JMenu menu;
497                 JMenuItem item;
498                 JRadioButtonMenuItem radioitem;
499
500                 // File menu
501                 {
502                         menu = new JMenu("File");
503                         menu.setMnemonic(KeyEvent.VK_F);
504                         menubar.add(menu);
505
506                         item = new JMenuItem("Quit",KeyEvent.VK_Q);
507                         item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
508                                                                    ActionEvent.CTRL_MASK));
509                         item.addActionListener(new ActionListener() {
510                                         public void actionPerformed(ActionEvent e) {
511                                                 System.exit(0);
512                                         }
513                                 });
514                         menu.add(item);
515                 }
516
517                 // Device menu
518                 {
519                         menu = new JMenu("Device");
520                         menu.setMnemonic(KeyEvent.VK_D);
521                         menubar.add(menu);
522
523                         item = new JMenuItem("Connect to Device",KeyEvent.VK_C);
524                         item.addActionListener(new ActionListener() {
525                                         public void actionPerformed(ActionEvent e) {
526                                                 ConnectToDevice();
527                                         }
528                                 });
529                         menu.add(item);
530
531                         item = new JMenuItem("Disconnect from Device",KeyEvent.VK_D);
532                         item.addActionListener(new ActionListener() {
533                                         public void actionPerformed(ActionEvent e) {
534                                                 serialLine.close();
535                                         }
536                                 });
537                         menu.add(item);
538
539                         menu.addSeparator();
540
541                         item = new JMenuItem("Save Flight Data",KeyEvent.VK_S);
542                         item.addActionListener(new ActionListener() {
543                                         public void actionPerformed(ActionEvent e) {
544                                                 SaveFlightData();
545                                         }
546                                 });
547                         menu.add(item);
548
549                         item = new JMenuItem("Replay",KeyEvent.VK_R);
550                         item.addActionListener(new ActionListener() {
551                                         public void actionPerformed(ActionEvent e) {
552                                                 Replay();
553                                         }
554                                 });
555                         menu.add(item);
556                 }
557                 // Log menu
558                 {
559                         menu = new JMenu("Log");
560                         menu.setMnemonic(KeyEvent.VK_L);
561                         menubar.add(menu);
562
563                         item = new JMenuItem("New Log",KeyEvent.VK_N);
564                         item.addActionListener(new ActionListener() {
565                                         public void actionPerformed(ActionEvent e) {
566                                         }
567                                 });
568                         menu.add(item);
569
570                         item = new JMenuItem("Configure Log",KeyEvent.VK_C);
571                         item.addActionListener(new ActionListener() {
572                                         public void actionPerformed(ActionEvent e) {
573                                         }
574                                 });
575                         menu.add(item);
576                 }
577                 // Voice menu
578                 {
579                         menu = new JMenu("Voice", true);
580                         menu.setMnemonic(KeyEvent.VK_V);
581                         menubar.add(menu);
582
583                         radioitem = new JRadioButtonMenuItem("Enable Voice");
584                         radioitem.addActionListener(new ActionListener() {
585                                         public void actionPerformed(ActionEvent e) {
586                                         }
587                                 });
588                         menu.add(radioitem);
589                 }
590
591                 // Channel menu
592                 {
593                         menu = new JMenu("Channel", true);
594                         menu.setMnemonic(KeyEvent.VK_C);
595                         menubar.add(menu);
596                         ButtonGroup group = new ButtonGroup();
597
598                         for (int c = 0; c <= 9; c++) {
599                                 radioitem = new JRadioButtonMenuItem(String.format("Channel %1d (%7.3fMHz)", c,
600                                                                                    434.550 + c * 0.1),
601                                                                      c == 0);
602                                 radioitem.setActionCommand(String.format("%d", c));
603                                 radioitem.addActionListener(new ActionListener() {
604                                                 public void actionPerformed(ActionEvent e) {
605                                                         System.out.println("Command: " + e.getActionCommand() + " param: " +
606                                                                            e.paramString());
607                                                 }
608                                         });
609                                 menu.add(radioitem);
610                                 group.add(radioitem);
611                         }
612                 }
613
614                 this.setJMenuBar(menubar);
615
616         }
617         public static void main(final String[] args) {
618                 AltosUI altosui = new AltosUI();
619                 altosui.setVisible(true);
620         }
621 }