altosui: Complete split out of separate java library
[fw/altos] / altosui / AltosEepromDownload.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 java.util.prefs.*;
29 import java.util.concurrent.*;
30 import org.altusmetrum.AltosLib.*;
31
32 import libaltosJNI.*;
33
34 public class AltosEepromDownload implements Runnable {
35
36         JFrame                  frame;
37         AltosSerial             serial_line;
38         boolean                 remote;
39         Thread                  eeprom_thread;
40         AltosEepromMonitor      monitor;
41
42         int                     flight;
43         int                     serial;
44         int                     year, month, day;
45         boolean                 want_file;
46         FileWriter              eeprom_file;
47         LinkedList<String>      eeprom_pending;
48
49         AltosEepromList         flights;
50         ActionListener          listener;
51         boolean                 success;
52         ParseException          parse_exception;
53         String                  extension;
54
55         private void FlushPending() throws IOException {
56                 for (String s : flights.config_data) {
57                         eeprom_file.write(s);
58                         eeprom_file.write('\n');
59                 }
60
61                 for (String s : eeprom_pending)
62                         eeprom_file.write(s);
63         }
64
65         private void CheckFile(boolean force) throws IOException {
66                 if (eeprom_file != null)
67                         return;
68                 if (force || (flight != 0 && want_file)) {
69                         AltosFile               eeprom_name;
70
71                         if (extension == null)
72                                 extension = "data";
73                         if (year != 0 && month != 0 && day != 0)
74                                 eeprom_name = new AltosFile(year, month, day, serial, flight, extension);
75                         else
76                                 eeprom_name = new AltosFile(serial, flight, extension);
77
78                         eeprom_file = new FileWriter(eeprom_name);
79                         if (eeprom_file != null) {
80                                 monitor.set_file(eeprom_name.getName());
81                                 FlushPending();
82                                 eeprom_pending = null;
83                         }
84                 }
85         }
86
87         void Log(AltosEepromRecord r) throws IOException {
88                 if (r.cmd != Altos.AO_LOG_INVALID) {
89                         String log_line = String.format("%c %4x %4x %4x\n",
90                                                         r.cmd, r.tick, r.a, r.b);
91                         if (eeprom_file != null)
92                                 eeprom_file.write(log_line);
93                         else
94                                 eeprom_pending.add(log_line);
95                 }
96         }
97
98         void set_serial(int in_serial) {
99                 serial = in_serial;
100                 monitor.set_serial(serial);
101         }
102
103         void set_flight(int in_flight) {
104                 flight = in_flight;
105                 monitor.set_flight(flight);
106         }
107                 
108         boolean                 done;
109         int                     state;
110
111         void CaptureFull(AltosEepromChunk eechunk) throws IOException {
112                 boolean any_valid = false;
113
114                 extension = "eeprom";
115                 set_serial(flights.config_data.serial);
116                 for (int i = 0; i < eechunk.chunk_size && !done; i += AltosEepromRecord.record_length) {
117                         try {
118                                 AltosEepromRecord r = new AltosEepromRecord(eechunk, i);
119                                 if (r.cmd == Altos.AO_LOG_FLIGHT)
120                                         set_flight(r.b);
121
122                                 /* Monitor state transitions to update display */
123                                 if (r.cmd == Altos.AO_LOG_STATE && r.a <= Altos.ao_flight_landed) {
124                                         state = r.a;
125                                         if (state > Altos.ao_flight_pad)
126                                                 want_file = true;
127                                 }
128
129                                 if (r.cmd == Altos.AO_LOG_GPS_DATE) {
130                                         year = 2000 + (r.a & 0xff);
131                                         month = (r.a >> 8) & 0xff;
132                                         day = (r.b & 0xff);
133                                         want_file = true;
134                                 }
135                                 if (r.cmd == Altos.AO_LOG_STATE && r.a == Altos.ao_flight_landed)
136                                         done = true;
137                                 any_valid = true;
138                                 Log(r);
139                         } catch (ParseException pe) {
140                                 if (parse_exception == null)
141                                         parse_exception = pe;
142                         }
143                 }
144
145                 if (!any_valid)
146                         done = true;
147
148                 CheckFile(false);
149         }
150
151         boolean start;
152         int     tiny_tick;
153
154         void CaptureTiny (AltosEepromChunk eechunk) throws IOException {
155                 boolean any_valid = false;
156
157                 extension = "eeprom";
158                 set_serial(flights.config_data.serial);
159                 for (int i = 0; i < eechunk.data.length && !done; i += 2) {
160                         int                     v = eechunk.data16(i);
161                         AltosEepromRecord       r;
162
163                         if (i == 0 && start) {
164                                 tiny_tick = 0;
165                                 start = false;
166                                 set_flight(v);
167                                 r = new AltosEepromRecord(Altos.AO_LOG_FLIGHT, tiny_tick, 0, v);
168                                 any_valid = true;
169                         } else {
170                                 int     s = v ^ 0x8000;
171
172                                 if (Altos.ao_flight_startup <= s && s <= Altos.ao_flight_invalid) {
173                                         state = s;
174                                         r = new AltosEepromRecord(Altos.AO_LOG_STATE, tiny_tick, state, 0);
175                                         if (state == Altos.ao_flight_landed)
176                                                 done = true;
177                                         state = s;
178                                         any_valid = true;
179                                 } else {
180                                         if (v != 0xffff)
181                                                 any_valid = true;
182
183                                         r = new AltosEepromRecord(Altos.AO_LOG_PRESSURE, tiny_tick, 0, v);
184
185                                         /*
186                                          * The flight software records ascent data every 100ms, and descent
187                                          * data every 1s.
188                                          */
189                                         if (state < Altos.ao_flight_drogue)
190                                                 tiny_tick += 10;
191                                         else
192                                                 tiny_tick += 100;
193                                 }
194                         }
195                         Log(r);
196                 }
197                 CheckFile(false);
198                 if (!any_valid)
199                         done = true;
200         }
201
202         void LogTeleScience(AltosEepromTeleScience r) throws IOException {
203                 if (r.type != Altos.AO_LOG_INVALID) {
204                         String log_line = String.format("%c %4x %4x %d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d\n",
205                                                         r.type, r.tick, r.tm_tick, r.tm_state,
206                                                         r.data[0], r.data[1], r.data[2], r.data[3], 
207                                                         r.data[4], r.data[5], r.data[6], r.data[7], 
208                                                         r.data[8], r.data[9], r.data[10], r.data[11]);
209                         if (eeprom_file != null)
210                                 eeprom_file.write(log_line);
211                         else
212                                 eeprom_pending.add(log_line);
213                 }
214         }
215         
216         boolean telescience_start;
217
218         void CaptureTeleScience (AltosEepromChunk eechunk) throws IOException {
219                 boolean any_valid = false;
220
221                 extension = "science";
222                 for (int i = 0; i < eechunk.chunk_size && !done; i += AltosEepromTeleScience.record_length) {
223                         try {
224                                 AltosEepromTeleScience r = new AltosEepromTeleScience(eechunk, i);
225                                 if (r.type == AltosEepromTeleScience.AO_LOG_TELESCIENCE_START) {
226                                         if (telescience_start) {
227                                                 done = true;
228                                                 break;
229                                         }
230                                         set_serial(r.data[0]);
231                                         set_flight(r.data[1]);
232                                         telescience_start = true;
233                                 } else {
234                                         if (!telescience_start)
235                                                 break;
236                                 }
237                                 state = r.tm_state;
238                                 want_file =true;
239                                 any_valid = true;
240                                 LogTeleScience(r);
241                         } catch (ParseException pe) {
242                                 if (parse_exception == null)
243                                         parse_exception = pe;
244                         }
245                 }
246
247                 CheckFile(false);
248                 if (!any_valid)
249                         done = true;
250         }
251
252         void CaptureTelemetry(AltosEepromChunk eechunk) throws IOException {
253                 
254         }
255
256         void CaptureLog(AltosEepromLog log) throws IOException, InterruptedException, TimeoutException {
257                 int                     block, state_block = 0;
258                 int                     log_format = flights.config_data.log_format;
259
260                 state = 0;
261                 done = false;
262                 start = true;
263
264                 if (flights.config_data.serial == 0)
265                         throw new IOException("no serial number found");
266
267                 /* Reset per-capture variables */
268                 flight = 0;
269                 year = 0;
270                 month = 0;
271                 day = 0;
272                 want_file = false;
273                 eeprom_file = null;
274                 eeprom_pending = new LinkedList<String>();
275
276                 /* Set serial number in the monitor dialog window */
277                 /* Now scan the eeprom, reading blocks of data and converting to .eeprom file form */
278
279                 state = 0; state_block = log.start_block;
280                 for (block = log.start_block; !done && block < log.end_block; block++) {
281                         monitor.set_value(Altos.state_to_string[state], state, block - state_block);
282
283                         AltosEepromChunk        eechunk = new AltosEepromChunk(serial_line, block, block == log.start_block);
284
285                         /*
286                          * Guess what kind of data is there if the device
287                          * didn't tell us
288                          */
289
290                         if (log_format == Altos.AO_LOG_FORMAT_UNKNOWN) {
291                                 if (block == log.start_block) {
292                                         if (eechunk.data(0) == Altos.AO_LOG_FLIGHT)
293                                                 log_format = Altos.AO_LOG_FORMAT_FULL;
294                                         else
295                                                 log_format = Altos.AO_LOG_FORMAT_TINY;
296                                 }
297                         }
298
299                         switch (log_format) {
300                         case Altos.AO_LOG_FORMAT_FULL:
301                                 extension = "eeprom";
302                                 CaptureFull(eechunk);
303                                 break;
304                         case Altos.AO_LOG_FORMAT_TINY:
305                                 extension = "eeprom";
306                                 CaptureTiny(eechunk);
307                                 break;
308                         case Altos.AO_LOG_FORMAT_TELEMETRY:
309                                 extension = "telem";
310                                 CaptureTelemetry(eechunk);
311                                 break;
312                         case Altos.AO_LOG_FORMAT_TELESCIENCE:
313                                 extension = "science";
314                                 CaptureTeleScience(eechunk);
315                                 break;
316                         }
317                 }
318                 CheckFile(true);
319                 if (eeprom_file != null) {
320                         eeprom_file.flush();
321                         eeprom_file.close();
322                 }
323         }
324
325         private void show_message_internal(String message, String title, int message_type) {
326                 JOptionPane.showMessageDialog(frame,
327                                               message,
328                                               title,
329                                               message_type);
330         }
331
332         private void show_message(String in_message, String in_title, int in_message_type) {
333                 final String message = in_message;
334                 final String title = in_title;
335                 final int message_type = in_message_type;
336                 Runnable r = new Runnable() {
337                                 public void run() {
338                                         try {
339                                                 show_message_internal(message, title, message_type);
340                                         } catch (Exception ex) {
341                                         }
342                                 }
343                         };
344                 SwingUtilities.invokeLater(r);
345         }
346
347         public void run () {
348                 try {
349                         boolean failed = false;
350                         if (remote)
351                                 serial_line.start_remote();
352
353                         for (AltosEepromLog log : flights) {
354                                 parse_exception = null;
355                                 if (log.download) {
356                                         monitor.reset();
357                                         CaptureLog(log);
358                                 }
359                                 if (parse_exception != null) {
360                                         failed = true;
361                                         show_message(String.format("Flight %d download error\n%s\nValid log data saved",
362                                                                    log.flight,
363                                                                    parse_exception.getMessage()),
364                                                      serial_line.device.toShortString(),
365                                                      JOptionPane.WARNING_MESSAGE);
366                                 }
367                         }
368                         success = !failed;
369                 } catch (IOException ee) {
370                         show_message(ee.getLocalizedMessage(),
371                                      serial_line.device.toShortString(),
372                                      JOptionPane.ERROR_MESSAGE);
373                 } catch (InterruptedException ie) {
374                         System.out.printf("download interrupted\n");
375                 } catch (TimeoutException te) {
376                         show_message(String.format("Connection to \"%s\" failed",
377                                                    serial_line.device.toShortString()),
378                                      "Connection Failed",
379                                      JOptionPane.ERROR_MESSAGE);
380                 } finally {
381                         if (remote) {
382                                 try {
383                                         serial_line.stop_remote();
384                                 } catch (InterruptedException ie) {
385                                 }
386                         }
387                         serial_line.flush_output();
388                 }
389                 monitor.done();
390                 if (listener != null) {
391                         Runnable r = new Runnable() {
392                                         public void run() {
393                                                 try {
394                                                         listener.actionPerformed(new ActionEvent(this,
395                                                                                                  success ? 1 : 0,
396                                                                                                  "download"));
397                                                 } catch (Exception ex) {
398                                                 }
399                                         }
400                                 };
401                         SwingUtilities.invokeLater(r);
402                 }
403         }
404
405         public void start() {
406                 eeprom_thread = new Thread(this);
407                 eeprom_thread.start();
408         }
409
410         public void addActionListener(ActionListener l) {
411                 listener = l;
412         }
413
414         public AltosEepromDownload(JFrame given_frame,
415                                    AltosSerial given_serial_line,
416                                    boolean given_remote,
417                                    AltosEepromList given_flights) {
418
419                 frame = given_frame;
420                 serial_line = given_serial_line;
421                 serial_line.set_frame(frame);
422                 remote = given_remote;
423                 flights = given_flights;
424                 success = false;
425
426                 monitor = new AltosEepromMonitor(frame, Altos.ao_flight_boost, Altos.ao_flight_landed);
427                 monitor.addActionListener(new ActionListener() {
428                                 public void actionPerformed(ActionEvent e) {
429                                         if (eeprom_thread != null)
430                                                 eeprom_thread.interrupt();
431                                 }
432                         });
433         }
434 }