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