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