Merge branch 'master' of ssh://git.gag.com/scm/git/fw/altos
[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_12;
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_12.*;
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",
63                 "telemetrum-v0",
64                 "telemetrum-v1",
65                 "telemini",
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",
76                 "TeleMetrum-v0",
77                 "TeleMetrum-v1",
78                 "TeleMini",
79                 "TeleNano",
80                 "TeleShield",
81                 "TeleTerra"
82         };
83
84         private boolean is_pair_programmed() {
85
86                 if (file != null) {
87                         String  name = file.getName();
88                         for (int i = 0; i < pair_programmed_files.length; i++) {
89                                 if (name.startsWith(pair_programmed_files[i]))
90                                         return true;
91                         }
92                 }
93                 if (device != null) {
94                         String  name = device.toString();
95                         for (int i = 0; i < pair_programmed_devices.length; i++) {
96                                 if (name.startsWith(pair_programmed_devices[i]))
97                                         return true;
98                         }
99                 }
100                 return false;
101         }
102
103         public void actionPerformed(ActionEvent e) {
104                 if (e.getSource() == cancel) {
105                         if (programmer != null)
106                                 programmer.abort();
107                         setVisible(false);
108                         dispose();
109                 } else {
110                         String  cmd = e.getActionCommand();
111                         if (e.getID() == -1) {
112                                 JOptionPane.showMessageDialog(frame,
113                                                               e.getActionCommand(),
114                                                               file.toString(),
115                                                               JOptionPane.ERROR_MESSAGE);
116                                 setVisible(false);
117                                 dispose();
118                         } else if (cmd.equals("done")) {
119                                 setVisible(false);
120                                 dispose();
121                         } else if (cmd.equals("start")) {
122                                 setVisible(true);
123                         } else {
124                                 pbar.setValue(e.getID());
125                                 pbar.setString(cmd);
126                         }
127                 }
128         }
129
130         public void build_dialog() {
131                 GridBagConstraints c;
132                 Insets il = new Insets(4,4,4,4);
133                 Insets ir = new Insets(4,4,4,4);
134
135                 pane = getContentPane();
136                 pane.setLayout(new GridBagLayout());
137
138                 c = new GridBagConstraints();
139                 c.gridx = 0; c.gridy = 0;
140                 c.fill = GridBagConstraints.NONE;
141                 c.anchor = GridBagConstraints.LINE_START;
142                 c.insets = il;
143                 serial_label = new JLabel("Serial:");
144                 pane.add(serial_label, c);
145
146                 c = new GridBagConstraints();
147                 c.gridx = 1; c.gridy = 0;
148                 c.fill = GridBagConstraints.HORIZONTAL;
149                 c.weightx = 1;
150                 c.anchor = GridBagConstraints.LINE_START;
151                 c.insets = ir;
152                 serial_value = new JLabel("");
153                 pane.add(serial_value, c);
154
155                 c = new GridBagConstraints();
156                 c.fill = GridBagConstraints.NONE;
157                 c.gridx = 0; c.gridy = 1;
158                 c.anchor = GridBagConstraints.LINE_START;
159                 c.insets = il;
160                 file_label = new JLabel("File:");
161                 pane.add(file_label, c);
162
163                 c = new GridBagConstraints();
164                 c.fill = GridBagConstraints.HORIZONTAL;
165                 c.weightx = 1;
166                 c.gridx = 1; c.gridy = 1;
167                 c.anchor = GridBagConstraints.LINE_START;
168                 c.insets = ir;
169                 file_value = new JLabel(file.toString());
170                 pane.add(file_value, c);
171
172                 pbar = new JProgressBar();
173                 pbar.setMinimum(0);
174                 pbar.setMaximum(100);
175                 pbar.setValue(0);
176                 pbar.setString("");
177                 pbar.setStringPainted(true);
178                 pbar.setPreferredSize(new Dimension(600, 20));
179                 c = new GridBagConstraints();
180                 c.fill = GridBagConstraints.HORIZONTAL;
181                 c.anchor = GridBagConstraints.CENTER;
182                 c.gridx = 0; c.gridy = 2;
183                 c.gridwidth = GridBagConstraints.REMAINDER;
184                 Insets ib = new Insets(4,4,4,4);
185                 c.insets = ib;
186                 pane.add(pbar, c);
187
188                 cancel = new JButton("Cancel");
189                 c = new GridBagConstraints();
190                 c.fill = GridBagConstraints.NONE;
191                 c.anchor = GridBagConstraints.CENTER;
192                 c.gridx = 0; c.gridy = 3;
193                 c.gridwidth = GridBagConstraints.REMAINDER;
194                 Insets ic = new Insets(4,4,4,4);
195                 c.insets = ic;
196                 pane.add(cancel, c);
197                 cancel.addActionListener(this);
198                 pack();
199                 setLocationRelativeTo(frame);
200         }
201
202         void set_serial(int serial_number) {
203                 serial_value.setText(String.format("%d", serial_number));
204         }
205
206         static class AltosHexfileFilter extends javax.swing.filechooser.FileFilter {
207                 int product;
208                 String head;
209                 String description;
210
211                 public AltosHexfileFilter(int product, String head, String description) {
212                         this.product = product;
213                         this.head = head;
214                         this.description = description;
215                 }
216
217                 public boolean accept(File file) {
218                         return !file.isFile() || (file.getName().startsWith(head) && file.getName().endsWith(".ihx"));
219                 }
220
221                 public String getDescription() {
222                         return description;
223                 }
224         }
225
226         static AltosHexfileFilter[] filters = {
227                 new AltosHexfileFilter(AltosLib.product_telemetrum, "telemetrum", "TeleMetrum Image"),
228                 new AltosHexfileFilter(AltosLib.product_teledongle, "teledongle", "TeleDongle Image"),
229                 new AltosHexfileFilter(AltosLib.product_telemega, "telemega", "TeleMega Image"),
230                 new AltosHexfileFilter(AltosLib.product_easymini, "easymini", "EasyMini Image"),
231                 new AltosHexfileFilter(AltosLib.product_easymega, "easymega", "EasyMega Image"),
232         };
233
234         boolean select_source_file() {
235                 JFileChooser    hexfile_chooser = new JFileChooser();
236
237                 File firmwaredir = AltosUIPreferences.firmwaredir();
238                 if (firmwaredir != null)
239                         hexfile_chooser.setCurrentDirectory(firmwaredir);
240
241                 hexfile_chooser.setDialogTitle("Select Flash Image");
242
243                 for (int i = 0; i < filters.length; i++) {
244                         hexfile_chooser.addChoosableFileFilter(filters[i]);
245                 }
246                 javax.swing.filechooser.FileFilter ihx_filter = new FileNameExtensionFilter("Flash Image", "ihx");
247                 hexfile_chooser.addChoosableFileFilter(ihx_filter);
248                 hexfile_chooser.setFileFilter(ihx_filter);
249
250                 if (!is_pair_programmed() && !device.matchProduct(AltosLib.product_altusmetrum)) {
251                         for (int i = 0; i < filters.length; i++) {
252                                 if (device != null && device.matchProduct(filters[i].product))
253                                         hexfile_chooser.setFileFilter(filters[i]);
254                         }
255                 }
256
257                 int returnVal = hexfile_chooser.showOpenDialog(frame);
258
259                 if (returnVal != JFileChooser.APPROVE_OPTION)
260                         return false;
261                 file = hexfile_chooser.getSelectedFile();
262                 if (file == null)
263                         return false;
264                 AltosUIPreferences.set_firmwaredir(file.getParentFile());
265
266                 return true;
267         }
268
269         boolean select_device() {
270                 int     product = AltosLib.product_any;
271
272                 device = AltosDeviceUIDialog.show(frame, AltosLib.product_any);
273
274                 if (device == null)
275                         return false;
276                 return true;
277         }
278
279         boolean rom_config_matches (AltosRomconfig a, AltosRomconfig b) {
280                 if (a.usb_id != null && b.usb_id != null &&
281                     (a.usb_id.vid != b.usb_id.vid ||
282                      a.usb_id.pid != b.usb_id.pid))
283                         return false;
284
285                 if (a.usb_product != null && b.usb_product != null &&
286                     !a.usb_product.equals(b.usb_product))
287                         return false;
288
289                 return true;
290         }
291
292         boolean update_rom_config_info(AltosRomconfig existing_config, AltosRomconfig image_config) {
293                 AltosRomconfig  new_config;
294
295                 if (!rom_config_matches(existing_config, image_config)) {
296                         int ret = JOptionPane.showConfirmDialog(this,
297                                                                 String.format("Device is %04x:%04x %s\nImage is %04x:%04x %s\nFlash anyways?",
298                                                                               existing_config.usb_id.vid,
299                                                                               existing_config.usb_id.pid,
300                                                                               existing_config.usb_product,
301                                                                               image_config.usb_id.vid,
302                                                                               image_config.usb_id.pid,
303                                                                               image_config.usb_product),
304                                                                 "Image doesn't match Device",
305                                                                 JOptionPane.YES_NO_OPTION);
306                         if (ret != JOptionPane.YES_OPTION)
307                                 return false;
308                 }
309
310                 new_config = AltosRomconfigUI.show(frame, existing_config);
311                 if (new_config == null)
312                         return false;
313                 rom_config = new_config;
314                 set_serial(rom_config.serial_number);
315                 setVisible(true);
316                 return true;
317         }
318
319         void exception (Exception e) {
320                 if (e instanceof FileNotFoundException) {
321                         JOptionPane.showMessageDialog(frame,
322                                                       ((FileNotFoundException) e).getMessage(),
323                                                       "Cannot open file",
324                                                       JOptionPane.ERROR_MESSAGE);
325                 } else if (e instanceof AltosSerialInUseException) {
326                         JOptionPane.showMessageDialog(frame,
327                                                       String.format("Device \"%s\" already in use",
328                                                                     device.toShortString()),
329                                                       "Device in use",
330                                                       JOptionPane.ERROR_MESSAGE);
331                 } else if (e instanceof IOException) {
332                         JOptionPane.showMessageDialog(frame,
333                                                       e.getMessage(),
334                                                       file.toString(),
335                                                       JOptionPane.ERROR_MESSAGE);
336                 }
337         }
338
339         class flash_task implements Runnable, AltosFlashListener {
340                 AltosFlashUI    ui;
341                 Thread          t;
342                 AltosProgrammer programmer;
343
344                 public void position(String in_s, int in_percent) {
345                         final String s = in_s;
346                         final int percent = in_percent;
347                         Runnable r = new Runnable() {
348                                         public void run() {
349                                                 try {
350                                                         ui.actionPerformed(new ActionEvent(this,
351                                                                                            percent,
352                                                                                            s));
353                                                 } catch (Exception ex) {
354                                                 }
355                                         }
356                                 };
357                         SwingUtilities.invokeLater(r);
358                 }
359
360                 public void run () {
361                         try {
362                                 if (ui.is_pair_programmed())
363                                         programmer = new AltosFlash(ui.file, link, this);
364                                 else
365                                         programmer = new AltosSelfFlash(ui.file, link, this);
366
367                                 final AltosRomconfig    current_config = programmer.target_romconfig();
368
369                                 final AltosRomconfig    image_config = programmer.image_romconfig();
370
371                                 final Semaphore await_rom_config = new Semaphore(0);
372                                 SwingUtilities.invokeLater(new Runnable() {
373                                                 public void run() {
374                                                         ui.programmer = programmer;
375                                                         ui.update_rom_config_info(current_config, image_config);
376                                                         await_rom_config.release();
377                                                 }
378                                         });
379                                 await_rom_config.acquire();
380
381                                 if (ui.rom_config != null) {
382                                         programmer.set_romconfig(ui.rom_config);
383                                         programmer.flash();
384                                 }
385                         } catch (InterruptedException ee) {
386                                 final Exception e = ee;
387                                 SwingUtilities.invokeLater(new Runnable() {
388                                                 public void run() {
389                                                         ui.exception(e);
390                                                 }
391                                         });
392                         } catch (IOException ee) {
393                                 final Exception e = ee;
394                                 SwingUtilities.invokeLater(new Runnable() {
395                                                 public void run() {
396                                                         ui.exception(e);
397                                                 }
398                                         });
399                         } finally {
400                                 if (programmer != null)
401                                         programmer.close();
402                         }
403                 }
404
405                 public flash_task(AltosFlashUI in_ui) {
406                         ui = in_ui;
407                         t = new Thread(this);
408                         t.start();
409                 }
410         }
411
412         flash_task      flasher;
413
414         private boolean open_device() throws InterruptedException {
415                 try {
416                         link = new AltosSerial(device);
417                         if (is_pair_programmed())
418                                 return true;
419
420                         if (link == null)
421                                 throw new IOException(String.format("%s: open failed", device.toShortString()));
422
423                         while (!link.is_loader()) {
424                                 link.to_loader();
425
426                                 java.util.List<AltosDevice> devices = null;
427
428                                 for (int tries = 0; tries < 10; tries++) {
429                                         Thread.sleep(100);
430                                         devices = AltosUSBDevice.list(AltosLib.product_altusmetrum);
431                                         if (devices.size() != 0)
432                                                 break;
433                                 }
434
435                                 if (devices.size() == 1)
436                                         device = devices.get(0);
437                                 else {
438                                         device = AltosDeviceUIDialog.show(frame, AltosLib.product_altusmetrum);
439                                         if (device == null)
440                                                 return false;
441                                 }
442                                 link = new AltosSerial(device);
443                         }
444                         return true;
445                 } catch (AltosSerialInUseException ee) {
446                         exception(ee);
447                 } catch (FileNotFoundException fe) {
448                         exception(fe);
449                 } catch (IOException ie) {
450                         exception (ie);
451                 }
452                 return false;
453         }
454
455         /*
456          * Execute the steps for flashing
457          * a device. Note that this returns immediately;
458          * this dialog is not modal
459          */
460         void showDialog() {
461                 if (!select_device())
462                         return;
463                 if (!select_source_file())
464                         return;
465                 try {
466                         if (!open_device())
467                                 return;
468                 } catch (InterruptedException ie) {
469                         return;
470                 }
471                 build_dialog();
472                 flash_task      f = new flash_task(this);
473         }
474
475         public static void show(AltosUIFrame frame) {
476                 AltosFlashUI    ui = new AltosFlashUI(frame);
477                 ui.showDialog();
478         }
479
480         public AltosFlashUI(AltosUIFrame in_frame) {
481                 super(in_frame, "Program Altusmetrum Device", false);
482
483                 frame = in_frame;
484         }
485 }