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