doc: EasyMotor and EasyTimer have the same mounting geometry as EasyMini
[fw/altos] / altosuilib / AltosFlashUI.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; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.altosuilib_14;
20
21 import java.awt.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import javax.swing.filechooser.FileNameExtensionFilter;
25 import java.io.*;
26 import java.util.concurrent.*;
27 import org.altusmetrum.altoslib_14.*;
28
29 public class AltosFlashUI
30         extends AltosUIDialog
31         implements ActionListener
32 {
33         Container       pane;
34         Box             box;
35         JLabel          serial_label;
36         JLabel          serial_value;
37         JLabel          file_label;
38         JLabel          file_value;
39         JProgressBar    pbar;
40         JButton         cancel;
41
42         AltosUIFrame    frame;
43
44         // Hex file with rom image
45         File            file;
46
47         // Debug connection
48         AltosUSBDevice  device;
49
50         AltosLink       link;
51
52         // Desired Rom configuration
53         AltosRomconfig  rom_config;
54
55         // Flash controller
56         AltosProgrammer programmer;
57
58         private static final String[] pair_programmed_files = {
59                 "teleballoon",
60                 "telebt-v1",
61                 "teledongle-v0",
62                 "telefire-v0",
63                 "telemetrum-v0",
64                 "telemetrum-v1",
65                 "telemini-v1",
66                 "telenano",
67                 "teleshield"
68         };
69
70         private static final String[] pair_programmed_devices = {
71                 "TeleBalloon",
72                 "TeleBT-v1",
73                 "TeleDongle-v0",
74                 "TeleFire-v0",
75                 "TeleFire",
76                 "TeleMetrum-v0",
77                 "TeleMetrum-v1",
78                 "TeleMini-v1",
79                 "TeleNano",
80                 "TeleShield"
81         };
82
83         private boolean is_pair_programmed() {
84
85                 if (file != null) {
86                         String  name = file.getName();
87                         for (int i = 0; i < pair_programmed_files.length; i++) {
88                                 if (name.startsWith(pair_programmed_files[i]))
89                                         return true;
90                         }
91                 }
92                 if (device != null) {
93                         String  name = device.toString();
94                         for (int i = 0; i < pair_programmed_devices.length; i++) {
95                                 if (name.startsWith(pair_programmed_devices[i]))
96                                         return true;
97                         }
98                 }
99                 return false;
100         }
101
102         public void actionPerformed(ActionEvent e) {
103                 if (e.getSource() == cancel) {
104                         if (programmer != null)
105                                 programmer.abort();
106                         setVisible(false);
107                         dispose();
108                 } else {
109                         String  cmd = e.getActionCommand();
110                         if (e.getID() == -1) {
111                                 JOptionPane.showMessageDialog(frame,
112                                                               e.getActionCommand(),
113                                                               file.toString(),
114                                                               JOptionPane.ERROR_MESSAGE);
115                                 setVisible(false);
116                                 dispose();
117                         } else if (cmd.equals(AltosFlashListener.flash_done)) {
118                                 setVisible(false);
119                                 dispose();
120                         } else if (cmd.equals(AltosFlashListener.flash_start)) {
121                                 setVisible(true);
122                         } else {
123                                 pbar.setValue(e.getID());
124                                 pbar.setString(cmd);
125                         }
126                 }
127         }
128
129         public void build_dialog() {
130                 GridBagConstraints c;
131                 Insets il = new Insets(4,4,4,4);
132                 Insets ir = new Insets(4,4,4,4);
133
134                 pane = getContentPane();
135                 pane.setLayout(new GridBagLayout());
136
137                 c = new GridBagConstraints();
138                 c.gridx = 0; c.gridy = 0;
139                 c.fill = GridBagConstraints.NONE;
140                 c.anchor = GridBagConstraints.LINE_START;
141                 c.insets = il;
142                 serial_label = new JLabel("Serial:");
143                 pane.add(serial_label, c);
144
145                 c = new GridBagConstraints();
146                 c.gridx = 1; c.gridy = 0;
147                 c.fill = GridBagConstraints.HORIZONTAL;
148                 c.weightx = 1;
149                 c.anchor = GridBagConstraints.LINE_START;
150                 c.insets = ir;
151                 serial_value = new JLabel("");
152                 pane.add(serial_value, c);
153
154                 c = new GridBagConstraints();
155                 c.fill = GridBagConstraints.NONE;
156                 c.gridx = 0; c.gridy = 1;
157                 c.anchor = GridBagConstraints.LINE_START;
158                 c.insets = il;
159                 file_label = new JLabel("File:");
160                 pane.add(file_label, c);
161
162                 c = new GridBagConstraints();
163                 c.fill = GridBagConstraints.HORIZONTAL;
164                 c.weightx = 1;
165                 c.gridx = 1; c.gridy = 1;
166                 c.anchor = GridBagConstraints.LINE_START;
167                 c.insets = ir;
168                 file_value = new JLabel(file.toString());
169                 pane.add(file_value, c);
170
171                 pbar = new JProgressBar();
172                 pbar.setMinimum(0);
173                 pbar.setMaximum(100);
174                 pbar.setValue(0);
175                 pbar.setString("");
176                 pbar.setStringPainted(true);
177                 pbar.setPreferredSize(new Dimension(600, 20));
178                 c = new GridBagConstraints();
179                 c.fill = GridBagConstraints.HORIZONTAL;
180                 c.anchor = GridBagConstraints.CENTER;
181                 c.gridx = 0; c.gridy = 2;
182                 c.gridwidth = GridBagConstraints.REMAINDER;
183                 Insets ib = new Insets(4,4,4,4);
184                 c.insets = ib;
185                 pane.add(pbar, c);
186
187                 cancel = new JButton("Cancel");
188                 c = new GridBagConstraints();
189                 c.fill = GridBagConstraints.NONE;
190                 c.anchor = GridBagConstraints.CENTER;
191                 c.gridx = 0; c.gridy = 3;
192                 c.gridwidth = GridBagConstraints.REMAINDER;
193                 Insets ic = new Insets(4,4,4,4);
194                 c.insets = ic;
195                 pane.add(cancel, c);
196                 cancel.addActionListener(this);
197                 pack();
198                 setLocationRelativeTo(frame);
199         }
200
201         void set_serial(int serial_number) {
202                 serial_value.setText(String.format("%d", serial_number));
203         }
204
205         static class AltosHexfileFilter extends javax.swing.filechooser.FileFilter {
206                 String head;
207                 String description;
208
209                 public AltosHexfileFilter(String usb_product) {
210                         int l;
211
212                         /* Trim off any trailing variants (1.0a vs 1.0) */
213                         for (l = usb_product.length(); l > 0; l--) {
214                                 char c = usb_product.charAt(l-1);
215                                 if (c < 'a' || 'z' < c)
216                                         break;
217                         }
218                         head = usb_product.substring(0, l).toLowerCase();
219                         description = String.format("%s Image File", usb_product);
220                 }
221
222                 public boolean accept(File file) {
223                         return !file.isFile() || (file.getName().startsWith(head) && file.getName().endsWith(".ihx"));
224                 }
225
226                 public String getDescription() {
227                         return description;
228                 }
229         }
230
231         boolean select_source_file() {
232                 JFileChooser    hexfile_chooser = new JFileChooser();
233
234                 File firmwaredir = AltosUIPreferences.firmwaredir();
235                 if (firmwaredir != null)
236                         hexfile_chooser.setCurrentDirectory(firmwaredir);
237
238                 hexfile_chooser.setDialogTitle("Select Flash Image");
239
240                 javax.swing.filechooser.FileFilter ihx_filter = new FileNameExtensionFilter("Flash Image", "ihx");
241                 hexfile_chooser.addChoosableFileFilter(ihx_filter);
242                 hexfile_chooser.setFileFilter(ihx_filter);
243
244                 if (!is_pair_programmed() && !device.matchProduct(AltosLib.product_altusmetrum)) {
245                         AltosHexfileFilter filter = new AltosHexfileFilter(device.usb_product());
246                         hexfile_chooser.addChoosableFileFilter(filter);
247                         hexfile_chooser.setFileFilter(filter);
248                 }
249
250                 int returnVal = hexfile_chooser.showOpenDialog(frame);
251
252                 if (returnVal != JFileChooser.APPROVE_OPTION)
253                         return false;
254                 file = hexfile_chooser.getSelectedFile();
255                 if (file == null)
256                         return false;
257                 AltosUIPreferences.set_firmwaredir(file.getParentFile());
258
259                 return true;
260         }
261
262         boolean select_device() {
263                 int     product = AltosLib.product_any;
264
265                 device = AltosDeviceUIDialog.show_usb(frame, AltosLib.product_any);
266
267                 if (device == null)
268                         return false;
269                 return true;
270         }
271
272         boolean rom_config_matches (AltosRomconfig a, AltosRomconfig b) {
273                 if (a == null || b == null)
274                         return (a == null && b == null);
275
276                 if (!a.valid || !b.valid)
277                         return false;
278
279                 if (a.usb_id != null && b.usb_id != null &&
280                     (a.usb_id.vid != b.usb_id.vid ||
281                      a.usb_id.pid != b.usb_id.pid))
282                         return false;
283
284                 if (a.usb_product != null && b.usb_product != null &&
285                     !a.usb_product.equals(b.usb_product))
286                         return false;
287
288                 return true;
289         }
290
291         boolean update_rom_config_info(AltosRomconfig existing_config, AltosRomconfig image_config) {
292                 AltosRomconfig  new_config;
293
294                 if (!rom_config_matches(existing_config, image_config)) {
295                         int ret;
296                         if (existing_config == null || !existing_config.valid) {
297                                 ret = JOptionPane.showConfirmDialog(this,
298                                                                     String.format("Cannot determine target device type\nImage is %04x:%04x %s\nFlash anyways?",
299                                                                                   image_config.usb_id.vid,
300                                                                                   image_config.usb_id.pid,
301                                                                                   image_config.usb_product),
302                                                                     "Unknown Target Device",
303                                                                     JOptionPane.YES_NO_OPTION);
304                         } else {
305                                 ret = JOptionPane.showConfirmDialog(this,
306                                                                     String.format("Device is %04x:%04x %s\nImage is %04x:%04x %s\nFlash anyways?",
307                                                                                   existing_config.usb_id.vid,
308                                                                                   existing_config.usb_id.pid,
309                                                                                   existing_config.usb_product,
310                                                                                   image_config.usb_id.vid,
311                                                                                   image_config.usb_id.pid,
312                                                                                   image_config.usb_product),
313                                                                     "Image doesn't match Device",
314                                                                     JOptionPane.YES_NO_OPTION);
315                         }
316                         if (ret != JOptionPane.YES_OPTION)
317                                 return false;
318                 }
319
320                 if (existing_config != null && existing_config.radio_calibration_broken) {
321                         int ret = JOptionPane.showConfirmDialog(this,
322                                                                 String.format("Radio calibration value %d may be incorrect\nFlash anyways?",
323                                                                               existing_config.radio_calibration),
324                                                                 "Radio Calibration Invalid",
325                                                                 JOptionPane.YES_NO_OPTION);
326                         if (ret != JOptionPane.YES_OPTION)
327                                 return false;
328                 }
329
330
331                 new_config = AltosRomconfigUI.show(frame, existing_config);
332                 if (new_config == null)
333                         return false;
334                 rom_config = new_config;
335                 set_serial(rom_config.serial_number);
336                 setVisible(true);
337                 return true;
338         }
339
340         void exception (Exception e) {
341                 if (e instanceof FileNotFoundException) {
342                         JOptionPane.showMessageDialog(frame,
343                                                       ((FileNotFoundException) e).getMessage(),
344                                                       "Cannot open file",
345                                                       JOptionPane.ERROR_MESSAGE);
346                 } else if (e instanceof AltosSerialInUseException) {
347                         JOptionPane.showMessageDialog(frame,
348                                                       String.format("Device \"%s\" already in use",
349                                                                     device.toShortString()),
350                                                       "Device in use",
351                                                       JOptionPane.ERROR_MESSAGE);
352                 } else {
353                         JOptionPane.showMessageDialog(frame,
354                                                       e.getMessage(),
355                                                       file.toString(),
356                                                       JOptionPane.ERROR_MESSAGE);
357                 }
358         }
359
360         class flash_task implements Runnable, AltosFlashListener {
361                 AltosFlashUI    ui;
362                 Thread          t;
363                 AltosProgrammer programmer;
364
365                 public void position(String in_s, int in_percent) {
366                         final String s = in_s;
367                         final int percent = in_percent;
368                         Runnable r = new Runnable() {
369                                         public void run() {
370                                                 try {
371                                                         ui.actionPerformed(new ActionEvent(this,
372                                                                                            percent,
373                                                                                            s));
374                                                 } catch (Exception ex) {
375                                                 }
376                                         }
377                                 };
378                         SwingUtilities.invokeLater(r);
379                 }
380
381                 public void run () {
382                         try {
383                                 if (ui.is_pair_programmed())
384                                         programmer = new AltosFlash(ui.file, link, this);
385                                 else
386                                         programmer = new AltosSelfFlash(ui.file, link, this);
387
388                                 final AltosRomconfig    current_config = programmer.target_romconfig(device.usb_id(), device.usb_product());
389
390                                 final AltosRomconfig    image_config = programmer.image_romconfig();
391
392                                 System.out.printf("product %s current %s image %s\n", device.usb_product(), current_config, image_config);
393
394                                 final Semaphore await_rom_config = new Semaphore(0);
395                                 SwingUtilities.invokeLater(new Runnable() {
396                                                 public void run() {
397                                                         ui.programmer = programmer;
398                                                         ui.update_rom_config_info(current_config, image_config);
399                                                         await_rom_config.release();
400                                                 }
401                                         });
402                                 await_rom_config.acquire();
403
404                                 if (ui.rom_config != null) {
405                                         programmer.set_romconfig(ui.rom_config);
406                                         programmer.flash();
407                                 }
408                         } catch (InterruptedException ee) {
409                                 final Exception e = ee;
410                                 SwingUtilities.invokeLater(new Runnable() {
411                                                 public void run() {
412                                                         ui.exception(e);
413                                                 }
414                                         });
415                         } catch (IOException ee) {
416                                 final Exception e = ee;
417                                 SwingUtilities.invokeLater(new Runnable() {
418                                                 public void run() {
419                                                         ui.exception(e);
420                                                 }
421                                         });
422                         } finally {
423                                 if (programmer != null)
424                                         programmer.close();
425                         }
426                 }
427
428                 public flash_task(AltosFlashUI in_ui) {
429                         ui = in_ui;
430                         t = new Thread(this);
431                         t.start();
432                 }
433         }
434
435         flash_task      flasher;
436
437
438         class open_task implements Runnable {
439                 AltosDevice     device;
440                 Thread          t;
441                 open_dialog     dialog;
442
443                 public void do_exception(final Exception e) {
444                         SwingUtilities.invokeLater(
445                                 new Runnable() {
446                                         public void run() {
447                                                 try { dialog.open_exception(e); } catch (Exception ex) { }
448                                         }
449                                 });
450                 }
451
452                 public void do_success(final AltosLink link) {
453                         SwingUtilities.invokeLater(
454                                 new Runnable() {
455                                         public void run() {
456                                                 try { dialog.open_success(link); } catch (Exception ex) { }
457                                         }
458                                 });
459                 }
460
461                 public void do_failure() {
462                         SwingUtilities.invokeLater(
463                                 new Runnable() {
464                                         public void run() {
465                                                 try { dialog.open_failure(); } catch (Exception ex) { }
466                                         }
467                                 });
468                 }
469
470                 public void do_cancel() {
471                         SwingUtilities.invokeLater(
472                                 new Runnable() {
473                                         public void run() {
474                                                 try { dialog.open_cancel(); } catch (Exception ex) { }
475                                         }
476                                 });
477                 }
478
479                 public void run () {
480                         try {
481                                 AltosLink link = null;
482                                 boolean new_device = false;
483
484                                 for (;;) {
485                                         System.out.printf("Attempting to open %s\n", device.toShortString());
486
487                                         for (int i = 0; i < 20; i++) {
488                                                 link = new AltosSerial(device);
489
490                                                 if (link != null)
491                                                         break;
492
493                                                 if (!new_device)
494                                                         break;
495
496                                                 System.out.printf("Waiting for device to become ready\n");
497
498                                                 Thread.sleep(1000);
499                                         }
500                                         if (link == null)
501                                                 throw new IOException(String.format("%s: open failed",
502                                                                                     device.toShortString()));
503
504                                         /* See if the link is usable already */
505                                         if (is_pair_programmed() || link.is_loader()) {
506                                                 System.out.printf("Device ready for use\n");
507                                                 do_success(link);
508                                                 return;
509                                         }
510
511                                         java.util.List<AltosDevice> prev_devices =
512                                                 AltosUSBDevice.list(AltosLib.product_altusmetrum);
513
514                                         /* Nope, switch to loader and
515                                          * wait for it to re-appear
516                                          */
517
518                                         System.out.printf("Switch to loader\n");
519
520                                         link.to_loader();
521
522                                         /* This is a bit fragile, but
523                                          * I'm not sure what else to
524                                          * do other than ask the user.
525                                          *
526                                          * Search for a device which
527                                          * wasn't there before we
528                                          * asked the target to switch
529                                          * to loader mode
530                                          */
531
532                                         device = null;
533                                         for (;;) {
534                                                 Thread.sleep(100);
535                                                 java.util.List<AltosDevice> devices =
536                                                         AltosUSBDevice.list(AltosLib.product_altusmetrum);
537
538                                                 for (AltosDevice d : devices) {
539                                                         boolean matched = false;
540                                                         System.out.printf("\tfound device %s\n", d.toShortString());
541                                                         for (AltosDevice p : prev_devices)
542                                                                 if (d.equals(p)) {
543                                                                         matched = true;
544                                                                         break;
545                                                                 }
546                                                         if (!matched) {
547                                                                 System.out.printf("Identified new device %s\n", d.toShortString());
548                                                                 device = (AltosUSBDevice) d;
549                                                                 new_device = true;
550                                                                 break;
551                                                         }
552                                                 }
553                                                 if (device != null)
554                                                         break;
555                                         }
556                                 }
557                         } catch (AltosSerialInUseException ee) {
558                                 do_exception(ee);
559                         } catch (FileNotFoundException fe) {
560                                 do_exception(fe);
561                         } catch (IOException ie) {
562                                 do_exception (ie);
563                         } catch (InterruptedException ie) {
564                         }
565                 }
566
567                 public void cancel() {
568                         t.interrupt();
569                 }
570
571                 public open_task(AltosDevice device, open_dialog dialog) {
572                         this.device = device;
573                         this.dialog = dialog;
574                         t = new Thread(this);
575                         t.start();
576                 }
577         }
578
579         class open_dialog
580                 extends AltosUIDialog
581                 implements ActionListener
582         {
583                 AltosUIFrame owner;
584
585                 private JLabel  opening_label;
586                 private JButton cancel_button;
587
588                 boolean done = false;
589
590                 AltosLink link = null;
591
592                 open_task open = null;
593
594                 public void open_exception(Exception e) {
595                         System.out.printf("open_exception\n");
596                         setVisible(false);
597                         exception(e);
598                         done = true;
599                 }
600
601                 public void open_success(AltosLink link) {
602                         System.out.printf("open_success\n");
603                         setVisible(false);
604                         this.link = link;
605                         done = true;
606                 }
607
608                 public void open_failure() {
609                         System.out.printf("open_failure\n");
610                         setVisible(false);
611                         done = true;
612                 }
613
614                 public void open_cancel() {
615                         System.out.printf("open_cancel\n");
616                         setVisible(false);
617                         done = true;
618                 }
619
620                 public AltosLink do_open(open_task open) throws InterruptedException {
621                         this.open = open;
622                         setVisible(true);
623                         return link;
624                 }
625
626                 public void actionPerformed(ActionEvent e) {
627                         String cmd = e.getActionCommand();
628
629                         if (cmd.equals("cancel"))
630                                 if (open != null)
631                                         open.cancel();
632                         done = true;
633                         setVisible(false);
634                 }
635
636                 public open_dialog(AltosUIFrame in_owner) {
637                         super(in_owner, "Open Flash Target Device", true);
638                         owner = in_owner;
639
640                         Container               pane = getContentPane();
641                         GridBagConstraints      c = new GridBagConstraints();
642                         Insets                  i = new Insets(4,4,4,4);
643
644
645                         pane.setLayout(new GridBagLayout());
646
647                         opening_label = new JLabel("Opening Device");
648                         c.fill = GridBagConstraints.HORIZONTAL;
649                         c.anchor = GridBagConstraints.LINE_START;
650                         c.insets = i;
651                         c.weightx = 0;
652                         c.weighty = 0;
653
654                         c.gridx = 0;
655                         c.gridy = 0;
656
657                         pane.add(opening_label, c);
658
659                         cancel_button = new JButton("Cancel");
660                         cancel_button.addActionListener(this);
661                         cancel_button.setActionCommand("cancel");
662
663                         c.gridy = 1;
664                         pane.add(cancel_button, c);
665                         pack();
666                         setLocationRelativeTo(owner);
667                 }
668         }
669
670         private boolean open_device() throws InterruptedException {
671
672                 open_dialog     dialog = new open_dialog(frame);
673
674                 open_task       open = new open_task(device, dialog);
675
676                 link = dialog.do_open(open);
677
678                 return link != null;
679         }
680
681         /*
682          * Execute the steps for flashing
683          * a device. Note that this returns immediately;
684          * this dialog is not modal
685          */
686         void showDialog() {
687                 if (!select_device())
688                         return;
689                 if (!select_source_file())
690                         return;
691                 try {
692                         if (!open_device())
693                                 return;
694                 } catch (InterruptedException ie) {
695                         return;
696                 }
697                 build_dialog();
698                 flash_task      f = new flash_task(this);
699         }
700
701         public static void show(AltosUIFrame frame) {
702                 AltosFlashUI    ui = new AltosFlashUI(frame);
703                 ui.showDialog();
704         }
705
706         public AltosFlashUI(AltosUIFrame in_frame) {
707                 super(in_frame, "Program Altusmetrum Device", false);
708
709                 frame = in_frame;
710         }
711 }