OpenCores
URL https://opencores.org/ocsvn/usb_fpga_1_11/usb_fpga_1_11/trunk

Subversion Repositories usb_fpga_1_11

[/] [usb_fpga_1_11/] [trunk/] [java/] [ztex/] [Ztex1v1.java] - Blame information for rev 5

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 ZTEX
/*!
2 5 ZTEX
   Java host software API of ZTEX EZ-USB FX2 SDK
3
   Copyright (C) 2009-2011 ZTEX GmbH.
4 2 ZTEX
   http://www.ztex.de
5
 
6
   This program is free software; you can redistribute it and/or modify
7
   it under the terms of the GNU General Public License version 3 as
8
   published by the Free Software Foundation.
9
 
10
   This program is distributed in the hope that it will be useful, but
11
   WITHOUT ANY WARRANTY; without even the implied warranty of
12
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
   General Public License for more details.
14
 
15
   You should have received a copy of the GNU General Public License
16
   along with this program; if not, see http://www.gnu.org/licenses/.
17
!*/
18
 
19
/*
20
    Functions for USB devices with ZTEX descriptor 1, Interface 1
21
    Interface capabilities and vendor requests (VR) / commands (VC):
22
    0.0  : EEPROM support
23
        VR 0x38 : read from EEPROM
24
            Returns:
25
                EEPROM data
26
        VC 0x39 : write to EEPROM
27
        VR 0x3a : EEPROM state
28
            Returns:
29
                Offs    Description
30
                0-1     bytes written
31
                2       checksum
32
                3       0:idle, 1:busy or error
33
 
34
    0.1  : FPGA Configuration
35
        VR 0x30 : get FPGA state
36
            Returns:
37
                Offs    Description
38
 
39
                1       checksum
40
                2-5     transferred bytes
41
                6       INIT_B state
42
        VC 0x31 : reset FPGA
43
        VC 0x32 : send FPGA configuration data (Bitstream)
44
 
45
    0.2  : Flash memory support
46 3 ZTEX
        VR 0x40 : read Flash state
47 2 ZTEX
            Returns:
48
                Offs    Description
49
 
50
                1-2     Sector size
51
                3-6     Number of sectors
52
                7       Error code
53
        VR 0x41 : read from Flash
54 5 ZTEX
        VC 0x42 : write to Flash
55 3 ZTEX
    0.3  : Debug helper support
56
        VR 0x28 : read debug data
57
            Returns:
58
                Offs    Description
59
                0-1     number of messages
60
                2       stack size in messages
61
                3       message size in bytes
62
                >=4     message stack
63 5 ZTEX
    0.4  : XMEGA support
64
        VR 0x48 : read XMEGA status information
65
            Returns:
66
                Offs    Description
67
 
68
                1-2     Flash size in pages
69
                3-4     EEPROM size in pages
70
                5       Flash page size as power of two (e.g. 9 means 512 bytes)
71
                6       EEPROM page size as power of two
72
        VC 0x49 : reset XMEGA
73
        VR 0x4A,0x4B,0x4C,0x4D : read XMEGA NVM using PDI address space / relative to Flash address base / EEPROM address base / Fuse address base
74
        VC 0x4B,0x4C : write exactly one Flash / EEPROM page
75
        VC 0x4D : write Fuse
76
 
77
    0.5  : High speed FPGA configuration support
78
        VR 0x33 : Return Endpoint settings
79
            Returns:
80
                Offs    Description
81
 
82
                1       Interface number
83
        VC 0x34 : Start high speed FPGA configuration
84
        VC 0x35 : Finish high speed FPGA configuration
85
 
86
    0.6  : MAC EEPROM support
87
        VR 0x3B : read from MAC EEPROM
88
            Returns:
89
                MAC EEPROM data
90
        VC 0x3C : write to MAC EEPROM
91
        VR 0x3D : MAC EEPROM state
92
            Returns:
93
                Offs    Description
94
 
95
 
96 2 ZTEX
*/
97
package ztex;
98
 
99
import java.io.*;
100
import java.util.*;
101
 
102
import ch.ntb.usb.*;
103
 
104
/**
105
  * This class implements the communication protocol of the interface version 1 for the interaction with the ZTEX firmware.
106
  * <p>
107
  * The features supported by this interface can be accessed via vendor commands and vendor requests via Endpoint 0.
108
  * Each feature can be enabled or disabled by the firmware and also depends from the hardware.
109
  * The presence of a feature is indicated by a 1 in the corresponding feature bit of the ZTEX descriptor 1, see {@link ZtexDevice1}.
110
  * The following table gives an overview about the features
111
  * <table bgcolor="#404040" cellspacing=1 cellpadding=10>
112
  *   <tr>
113
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Capability bit</b></td>
114
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
115
  *   </tr>
116
  *   <tr>
117
  *     <td bgcolor="#ffffff" valign="top">0.0</td>
118
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
119
  *       EEPROM support<p>
120
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
121
  *         <tr>
122
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
123
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
124
  *         </tr>
125
  *         <tr>
126
  *           <td bgcolor="#ffffff" valign="top">VR 0x38</td>
127
  *           <td bgcolor="#ffffff" valign="top">Read from EEPROM</td>
128
  *         </tr>
129
  *         <tr>
130
  *           <td bgcolor="#ffffff" valign="top">VC 0x39</td>
131
  *           <td bgcolor="#ffffff" valign="top">Write to EEPROM</td>
132
  *         </tr>
133
  *         <tr>
134
  *           <td bgcolor="#ffffff" valign="top">VR 0x3a</td>
135
  *           <td bgcolor="#ffffff" valign="top">Get EEPROM state. Returns:
136
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
137
  *               <tr>
138
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
139
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
140
  *               </tr>
141
  *               <tr>
142
  *                 <td bgcolor="#ffffff" valign="top">0-1</td>
143
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes written.</td>
144
  *               </tr>
145
  *               <tr>
146
  *                 <td bgcolor="#ffffff" valign="top">2</td>
147
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
148
  *               </tr>
149
  *               <tr>
150
  *                 <td bgcolor="#ffffff" valign="top">3</td>
151
  *                 <td bgcolor="#ffffff" valign="top">0:idle, 1:busy or error</td>
152
  *               </tr>
153
  *             </table>
154
  *           </td>
155
  *         </tr>
156
  *       </table>
157
  *     </td>
158
  *   </tr>
159
  *   <tr>
160
  *     <td bgcolor="#ffffff" valign="top">0.1</td>
161
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
162
  *       FPGA Configuration<p>
163
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
164
  *         <tr>
165
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
166
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
167
  *         </tr>
168
  *         <tr>
169
  *           <td bgcolor="#ffffff" valign="top">VR 0x30</td>
170
  *           <td bgcolor="#ffffff" valign="top">Get FPGA state. Returns:
171
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
172
  *               <tr>
173
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
174
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
175
  *               </tr>
176
  *               <tr>
177
  *                 <td bgcolor="#ffffff" valign="top">0</td>
178
  *                 <td bgcolor="#ffffff" valign="top">1: unconfigured, 0:configured</td>
179
  *               </tr>
180
  *               <tr>
181
  *                 <td bgcolor="#ffffff" valign="top">1</td>
182
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
183
  *               </tr>
184
  *               <tr>
185
  *                 <td bgcolor="#ffffff" valign="top">2-5</td>
186
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes transferred.</td>
187
  *               </tr>
188
  *               <tr>
189
  *                 <td bgcolor="#ffffff" valign="top">6</td>
190 5 ZTEX
  *                 <td bgcolor="#ffffff" valign="top">INIT_B states.</td>
191 2 ZTEX
  *               </tr>
192
  *             </table>
193
  *           </td>
194
  *         </tr>
195
  *         <tr>
196
  *           <td bgcolor="#ffffff" valign="top">VC 0x31</td>
197
  *           <td bgcolor="#ffffff" valign="top">Reset FPGA</td>
198
  *         </tr>
199
  *         <tr>
200
  *           <td bgcolor="#ffffff" valign="top">VR 0x32</td>
201
  *           <td bgcolor="#ffffff" valign="top">Send Bitstream</td>
202
  *         </tr>
203
  *       </table>
204
  *     </td>
205
  *   </tr>
206
  *   <tr>
207
  *     <td bgcolor="#ffffff" valign="top">0.2</td>
208
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
209
  *       Flash memory support<p>
210
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
211
  *         <tr>
212
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
213
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
214
  *         </tr>
215
  *         <tr>
216
  *           <td bgcolor="#ffffff" valign="top">VR 0x40</td>
217
  *           <td bgcolor="#ffffff" valign="top">Get Flash state. Returns:
218
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
219
  *               <tr>
220
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
221
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
222
  *               </tr>
223
  *               <tr>
224
  *                 <td bgcolor="#ffffff" valign="top">0</td>
225
  *                 <td bgcolor="#ffffff" valign="top">1:enabled, 0:disabled</td>
226
  *               </tr>
227
  *               <tr>
228
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
229
  *                 <td bgcolor="#ffffff" valign="top">Sector size</td>
230
  *               </tr>
231
  *               <tr>
232
  *                 <td bgcolor="#ffffff" valign="top">3-6</td>
233
  *                 <td bgcolor="#ffffff" valign="top">Number of sectors</td>
234
  *               </tr>
235
  *               <tr>
236
  *                 <td bgcolor="#ffffff" valign="top">7</td>
237
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
238
  *               </tr>
239
  *             </table>
240
  *           </td>
241
  *         </tr>
242
  *         <tr>
243
  *           <td bgcolor="#ffffff" valign="top">VR 0x41</td>
244
  *           <td bgcolor="#ffffff" valign="top">Read one sector from Flash</td>
245
  *         </tr>
246
  *         <tr>
247
  *           <td bgcolor="#ffffff" valign="top">VC 0x42</td>
248
  *           <td bgcolor="#ffffff" valign="top">Write one sector to Flash</td>
249
  *         </tr>
250
  *       </table>
251
  *     </td>
252
  *   </tr>
253 3 ZTEX
  *   <tr>
254
  *     <td bgcolor="#ffffff" valign="top">0.3</td>
255
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
256
  *       Debug helper support<p>
257
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
258
  *         <tr>
259
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
260
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
261
  *         </tr>
262
  *         <tr>
263
  *           <td bgcolor="#ffffff" valign="top">VR 0x28</td>
264
  *           <td bgcolor="#ffffff" valign="top">Get debug data. Returns:
265
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
266
  *               <tr>
267
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
268
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
269
  *               </tr>
270
  *               <tr>
271
  *                 <td bgcolor="#ffffff" valign="top">0-1</td>
272
  *                 <td bgcolor="#ffffff" valign="top">Number of the last message</td>
273
  *               </tr>
274
  *               <tr>
275
  *                 <td bgcolor="#ffffff" valign="top">2</td>
276
  *                 <td bgcolor="#ffffff" valign="top">Stack size in messages</td>
277
  *               </tr>
278
  *               <tr>
279
  *                 <td bgcolor="#ffffff" valign="top">3</td>
280
  *                 <td bgcolor="#ffffff" valign="top">Message size in bytes</td>
281
  *               </tr>
282
  *               <tr>
283
  *                 <td bgcolor="#ffffff" valign="top">&ge;4</td>
284
  *                 <td bgcolor="#ffffff" valign="top">Message stack</td>
285
  *               </tr>
286
  *             </table>
287
  *           </td>
288
  *         </tr>
289
  *       </table>
290
  *     </td>
291
  *   </tr>
292 5 ZTEX
  *   <tr>
293
  *     <td bgcolor="#ffffff" valign="top">0.4</td>
294
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
295
  *       XMEGA support<p>
296
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
297
  *         <tr>
298
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
299
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
300
  *         </tr>
301
  *         <tr>
302
  *           <td bgcolor="#ffffff" valign="top">VR 0x48</td>
303
  *           <td bgcolor="#ffffff" valign="top">Read XMEGA status information. Returns:
304
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
305
  *               <tr>
306
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
307
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
308
  *               </tr>
309
  *               <tr>
310
  *                 <td bgcolor="#ffffff" valign="top">0</td>
311
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
312
  *               </tr>
313
  *               <tr>
314
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
315
  *                 <td bgcolor="#ffffff" valign="top">Flash size in pages</td>
316
  *               </tr>
317
  *               <tr>
318
  *                 <td bgcolor="#ffffff" valign="top">3-4</td>
319
  *                 <td bgcolor="#ffffff" valign="top">EEPROM sie in pages</td>
320
  *               </tr>
321
  *               <tr>
322
  *                 <td bgcolor="#ffffff" valign="top">5</td>
323
  *                 <td bgcolor="#ffffff" valign="top">Flash page size as power of two  (e.g. 9 means 512 bytes)</td>
324
  *               </tr>
325
  *               <tr>
326
  *                 <td bgcolor="#ffffff" valign="top">6</td>
327
  *                 <td bgcolor="#ffffff" valign="top">EEPROM page size as power of two</td>
328
  *               </tr>
329
  *             </table>
330
  *           </td>
331
  *         </tr>
332
  *         <tr>
333
  *           <td bgcolor="#ffffff" valign="top">VC 0x49</td>
334
  *           <td bgcolor="#ffffff" valign="top">Reset XMEGA</td>
335
  *         </tr>
336
  *         <tr>
337
  *           <td bgcolor="#ffffff" valign="top">VRs 0x4A, 0x4B, 0x4C, 0x4D</td>
338
  *           <td bgcolor="#ffffff" valign="top">Read XMEGA NVM using PDI address space / relative to Flash address base / EEPROM address base / Fuse address base</td>
339
  *         </tr>
340
  *         <tr>
341
  *           <td bgcolor="#ffffff" valign="top">VCs 0x4B, 0x4C</td>
342
  *           <td bgcolor="#ffffff" valign="top">Write exactly one Flash / EEPROM page</td>
343
  *         </tr>
344
  *         <tr>
345
  *           <td bgcolor="#ffffff" valign="top">VCs 0x4D</td>
346
  *           <td bgcolor="#ffffff" valign="top">Write Fuse</td>
347
  *         </tr>
348
  *       </table>
349
  *     </td>
350
  *   </tr>
351
  *   <tr>
352
  *     <td bgcolor="#ffffff" valign="top">0.5</td>
353
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
354
  *       High speed FPGA configuration support<p>
355
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
356
  *         <tr>
357
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
358
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
359
  *         </tr>
360
  *         <tr>
361
  *           <td bgcolor="#ffffff" valign="top">VR 0x33</td>
362
  *           <td bgcolor="#ffffff" valign="top">Read Endpoint settings. Returns:
363
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
364
  *               <tr>
365
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
366
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
367
  *               </tr>
368
  *               <tr>
369
  *                 <td bgcolor="#ffffff" valign="top">0</td>
370
  *                 <td bgcolor="#ffffff" valign="top">Endpoint number</td>
371
  *               </tr>
372
  *               <tr>
373
  *                 <td bgcolor="#ffffff" valign="top">1</td>
374
  *                 <td bgcolor="#ffffff" valign="top">Interface number</td>
375
  *               </tr>
376
  *             </table>
377
  *           </td>
378
  *         </tr>
379
  *         <tr>
380
  *           <td bgcolor="#ffffff" valign="top">VR 0x34</td>
381
  *           <td bgcolor="#ffffff" valign="top">Start FPGA configuration</td>
382
  *         </tr>
383
  *         <tr>
384
  *           <td bgcolor="#ffffff" valign="top">VC 0x35</td>
385
  *           <td bgcolor="#ffffff" valign="top">Finish FPGA configuration</td>
386
  *         </tr>
387
  *       </table>
388
  *     </td>
389
  *   </tr>
390
  *   <tr>
391
  *     <td bgcolor="#ffffff" valign="top">0.6</td>
392
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
393
  *       MAC EEPROM support<p>
394
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
395
  *         <tr>
396
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
397
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
398
  *         </tr>
399
  *         <tr>
400
  *           <td bgcolor="#ffffff" valign="top">VR 0x3B</td>
401
  *           <td bgcolor="#ffffff" valign="top">Read from MAC EEPROM</td>
402
  *         </tr>
403
  *         <tr>
404
  *           <td bgcolor="#ffffff" valign="top">VC 0x3C</td>
405
  *           <td bgcolor="#ffffff" valign="top">Write to MAC EEPROM</td>
406
  *         </tr>
407
  *         <tr>
408
  *           <td bgcolor="#ffffff" valign="top">VR 0x3D</td>
409
  *           <td bgcolor="#ffffff" valign="top">Get MAC EEPROM state. Returns:
410
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
411
  *               <tr>
412
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
413
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
414
  *               </tr>
415
  *               <tr>
416
  *                 <td bgcolor="#ffffff" valign="top">0</td>
417
  *                 <td bgcolor="#ffffff" valign="top">0:idle, 1:busy or error</td>
418
  *               </tr>
419
  *             </table>
420
  *           </td>
421
  *         </tr>
422
  *       </table>
423
  *     </td>
424
  *   </tr>
425 2 ZTEX
  * </table>
426
  * @see ZtexDevice1
427
  * @see Ztex1
428
  */
429
 
430 5 ZTEX
 
431 2 ZTEX
public class Ztex1v1 extends Ztex1 {
432 3 ZTEX
    /** * Capability index for EEPROM support. */
433
    public static final int CAPABILITY_EEPROM = 0;
434
    /** * Capability index for FPGA configuration support. */
435
    public static final int CAPABILITY_FPGA = 1;
436
    /** * Capability index for FLASH memory support. */
437
    public static final int CAPABILITY_FLASH = 2;
438
    /** * Capability index for DEBUG helper support. */
439
    public static final int CAPABILITY_DEBUG = 3;
440
    /** * Capability index for AVR XMEGA support. */
441
    public static final int CAPABILITY_XMEGA = 4;
442 5 ZTEX
    /** * Capability index for AVR XMEGA support. */
443
    public static final int CAPABILITY_HS_FPGA = 5;
444
    /** * Capability index for AVR XMEGA support. */
445
    public static final int CAPABILITY_MAC_EEPROM = 6;
446 3 ZTEX
 
447 2 ZTEX
    /** * The names of the capabilities */
448
    public static final String capabilityStrings[] = {
449
        "EEPROM read/write" ,
450
        "FPGA configuration" ,
451 3 ZTEX
        "Flash memory support",
452
        "Debug helper",
453 5 ZTEX
        "XMEGA support",
454
        "High speed FPGA configuration",
455
        "MAC EEPROM read/write"
456 2 ZTEX
    };
457
 
458
    private boolean fpgaConfigured = false;
459
    private int fpgaChecksum = 0;
460
    private int fpgaBytes = 0;
461
    private int fpgaInitB = 0;
462
    private int fpgaFlashResult = 255;
463
    private boolean fpgaFlashBitSwap = false;
464
 
465
    /** * Number of bytes written to EEPROM. (Obtained by {@link #eepromState()}.) */
466
    public int eepromBytes = 0;
467
    /** * Checksum of the last EEPROM transfer. (Obtained by {@link #eepromState()}.) */
468
    public int eepromChecksum = 0;
469
 
470
    private int flashEnabled = -1;
471
    private int flashSectorSize = -1;
472
    private int flashSectors = -1;
473
 
474
    /** * Last Flash error code obtained by {@link #flashState()}. See FLASH_EC_* for possible error codes. */
475
    public int flashEC = 0;
476
    /** * Means no error. */
477
    public static final int FLASH_EC_NO_ERROR = 0;
478
    /** * Signals an error while attempting to execute a command. */
479
    public static final int FLASH_EC_CMD_ERROR = 1;
480
    /** * Signals that a timeout occurred. */
481
    public static final int FLASH_EC_TIMEOUT = 2;
482
    /** * Signals that Flash memory it busy. */
483
    public static final int FLASH_EC_BUSY = 3;
484
    /** * Signals that another Flash operation is pending. */
485
    public static final int FLASH_EC_PENDING = 4;
486
    /** * Signals an error while attempting to read from Flash. */
487
    public static final int FLASH_EC_READ_ERROR = 5;
488
    /** * Signals an error while attempting to write to Flash. */
489
    public static final int FLASH_EC_WRITE_ERROR = 6;
490 5 ZTEX
    /** * Signals the the installed Flash memory is not supported. */
491 2 ZTEX
    public static final int FLASH_EC_NOTSUPPORTED = 7;
492 3 ZTEX
 
493
    private int debugStackSize = -1;
494
    private int debugMsgSize = -1;
495
    private int debugLastMsg = 0;
496 5 ZTEX
    /** * Is set by {@link #debugReadMessages(boolean,byte[])} and contains the number of new messages. */
497 3 ZTEX
    public int debugNewMessages = 0;
498 2 ZTEX
 
499 5 ZTEX
    private int xmegaFlashPages = -1;
500
    private int xmegaEepromPages = -1;
501
    private int xmegaFlashPageSize;
502
    private int xmegaEepromPageSize;
503
 
504
    /** * Last ATxmega error code obtained by {@link #xmegaState()}. See XMEGA_EC_* for possible error codes. */
505
    public int xmegaEC = 0;
506
    /** * Means no error. */
507
    public static final int XMEGA_EC_NO_ERROR = 0;
508
    /** * Signals a PDI read error. */
509
    public static final int XMEGA_EC_PDI_READ_ERROR = 1;
510
    /** * Signals that an NVM timeout occurred. */
511
    public static final int XMEGA_EC_NVM_TIMEOUT = 2;
512
    /** * Signals that the ATxmega controller is not supported. */
513
    public static final int XMEGA_EC_INVALID_DEVICE = 3;
514
    /** * Signals an address error (invalid address or wrong page size). */
515
    public static final int XMEGA_EC_ADDRESS_ERROR = 4;
516
    /** * Signals that the NVM is busy. */
517
    public static final int XMEGA_EC_NVM_BUSY = 5;
518
 
519
 
520 2 ZTEX
// ******* Ztex1v1 *************************************************************
521
/**
522
  * Constructs an instance from a given device.
523
  * @param pDev The given device.
524
  * @throws UsbException if an communication error occurred.
525
  */
526
    public Ztex1v1 ( ZtexDevice1 pDev ) throws UsbException {
527
        super ( pDev );
528
    }
529
 
530
// ******* valid ***************************************************************
531
/**
532
  * Returns true if ZTEX interface 1 is available.
533
  * @return true if ZTEX interface 1 is available.
534
  */
535
    public boolean valid ( ) {
536
        return dev().valid() && dev().interfaceVersion()==1;
537
    }
538
 
539
/**
540
  * Returns true if ZTEX interface 1 and capability i.j are available.
541
  * @param i byte index of the capability
542
  * @param j bit index of the capability
543
  * @return true if ZTEX interface 1 and capability i.j are available.
544
  */
545
    public boolean valid ( int i, int j) {
546
        return dev().valid() && dev().interfaceVersion()==1 && dev().interfaceCapabilities(i,j);
547
    }
548
 
549
// ******* compatible **********************************************************
550
/**
551
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.<br>
552
  * The given product ID is compatible
553
  * <pre>if ( this.productId(0)==0 || productId0<=0 || this.productId(0)==productId0 ) &&
554
   ( this.productId(0)==0 || productId1<=0 || this.productId(1)==productId1 ) &&
555
   ( this.productId(2)==0 || productId2<=0 || this.productId(2)==productId2 ) &&
556
   ( this.productId(3)==0 || productId3<=0 || this.productId(3)==productId3 ) </pre>
557
  * @param productId0 Byte 0 of the given product ID
558
  * @param productId1 Byte 1 of the given product ID
559
  * @param productId2 Byte 2 of the given product ID
560
  * @param productId3 Byte 3 of the given product ID
561
  * @return true if the given product ID is compatible and interface 1 is supported.
562
  */
563
    public boolean compatible ( int productId0, int productId1, int productId2, int productId3 ) {
564
        return dev().valid() && dev().compatible ( productId0, productId1, productId2, productId3 ) && dev().interfaceVersion()==1;
565
    }
566
 
567
// ******* checkValid **********************************************************
568
/**
569
  * Checks whether ZTEX descriptor 1 is available and interface 1 is supported.
570
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
571
  */
572
    public void checkValid () throws InvalidFirmwareException {
573
        super.checkValid();
574
        if ( dev().interfaceVersion() != 1 )
575
            throw new InvalidFirmwareException(this, "Wrong interface: " + dev().interfaceVersion() + ", expected: 1" );
576
    }
577
 
578
// ******* checkCapability *****************************************************
579
/**
580
  * Checks whether ZTEX descriptor 1 is available and interface 1 and a given capability are supported.
581
  * @param i byte index of the capability
582
  * @param j bit index of the capability
583
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
584
  * @throws CapabilityException if the given capability is not supported.
585
  */
586
    public void checkCapability ( int i, int j ) throws InvalidFirmwareException, CapabilityException {
587
        checkValid();
588
        if ( ! dev().interfaceCapabilities(i,j) ) {
589
            int k = i*8 + j;
590
            if ( k>=0 && k<capabilityStrings.length )
591
            throw new CapabilityException( this, ( k>=0 && k<=capabilityStrings.length ) ? capabilityStrings[k] : ("Capabilty " + i + "," + j) );
592
        }
593
    }
594
 
595 3 ZTEX
/**
596
  * Checks whether ZTEX descriptor 1 is available and interface 1 and a given capability are supported.
597
  * @param i capability index (0..47)
598
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
599
  * @throws CapabilityException if the given capability is not supported.
600
  */
601
    public void checkCapability ( int i ) throws InvalidFirmwareException, CapabilityException {
602
        checkCapability(i/8, i%8);
603
    }
604
 
605 2 ZTEX
// ******* checkCompatible *****************************************************
606
/**
607
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.
608
  * See {@link #compatible(int,int,int,int)}.
609
  * @param productId0 Byte 0 of the given product ID
610
  * @param productId1 Byte 1 of the given product ID
611
  * @param productId2 Byte 2 of the given product ID
612
  * @param productId3 Byte 3 of the given product ID
613
  * @throws InvalidFirmwareException if the given product ID is not compatible or interface 1 is not supported.
614
  */
615
    public void checkCompatible ( int productId0, int productId1, int productId2, int productId3 ) throws InvalidFirmwareException {
616
        checkValid();
617
        if ( ! dev().compatible ( productId0, productId1, productId2, productId3 ) )
618
            throw new InvalidFirmwareException(this, "Incompatible Product ID");
619
    }
620
 
621
// ******* getFpgaState ********************************************************
622
    private void getFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
623
        byte[] buffer = new byte[9];
624 3 ZTEX
        checkCapability(CAPABILITY_FPGA);
625 2 ZTEX
        vendorRequest2(0x30, "getFpgaState", buffer, 9);
626
        fpgaConfigured = buffer[0] == 0;
627
        fpgaChecksum = buffer[1] & 0xff;
628
        fpgaBytes = ((buffer[5] & 0xff)<<24) | ((buffer[4] & 0xff)<<16) | ((buffer[3] & 0xff)<<8) | (buffer[2] & 0xff);
629
        fpgaInitB = buffer[6] & 0xff;
630
        fpgaFlashResult = buffer[7];
631
        fpgaFlashBitSwap = buffer[8] != 0;
632
    }
633
 
634
// ******* printFpgaState ******************************************************
635
/**
636
  * Prints out the FPGA state.
637
  * @throws InvalidFirmwareException if interface 1 is not supported.
638
  * @throws UsbException if a communication error occurs.
639
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
640
  */
641
    public void printFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
642 5 ZTEX
 
643
        final String flashResultStr[] = {
644
         "Configuration successful",
645
         "FPGA already configured",
646
         "Flash error",
647
         "No bitstream found",
648
         "Configuration error"
649
        };
650
 
651 2 ZTEX
        getFpgaState();
652 5 ZTEX
        System.out.println( "size=" + fpgaBytes + ";  checksum=" + fpgaChecksum + "; INIT_B_HIST=" + fpgaInitB +"; flash_configuration_result=" + fpgaFlashResult +
653
          (fpgaFlashResult>=0 && fpgaFlashResult<flashResultStr.length ? " ("+flashResultStr[fpgaFlashResult]+")" : "" )
654
        );
655 2 ZTEX
    }
656
 
657
// ******* getFpgaConfiguration ************************************************
658
/**
659
  * Returns true if the FPGA is configured.
660
  * @return true if the FPGA is configured.
661
  * @throws InvalidFirmwareException if interface 1 is not supported.
662
  * @throws UsbException if a communication error occurs.
663
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
664
  */
665
    public boolean getFpgaConfiguration () throws UsbException, InvalidFirmwareException, CapabilityException {
666
        getFpgaState ();
667
        return fpgaConfigured;
668
    }
669
 
670
// ******* getFpgaConfigurationStr *********************************************
671
/**
672
  * Returns a string that indicates the FPGA configuration status.
673
  * @return a string that indicates the FPGA configuration status.
674
  * @throws InvalidFirmwareException if interface 1 is not supported.
675
  * @throws UsbException if a communication error occurs.
676
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
677
  */
678
    public String getFpgaConfigurationStr () throws UsbException, InvalidFirmwareException, CapabilityException {
679
        getFpgaState ();
680
        return fpgaConfigured ? "FPGA configured" : "FPGA unconfigured";
681
    }
682
 
683
// ******* resetFGPA ***********************************************************
684
/**
685
  * Resets the FPGA.
686
  * @throws InvalidFirmwareException if interface 1 is not supported.
687
  * @throws UsbException if a communication error occurs.
688
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
689
  */
690
    public void resetFpga () throws UsbException, InvalidFirmwareException, CapabilityException {
691 3 ZTEX
        checkCapability(CAPABILITY_FPGA);
692 2 ZTEX
        vendorCommand(0x31, "resetFpga" );
693
    }
694
 
695 3 ZTEX
 
696
// ******* detectBitstreamBitOrder *********************************************
697
    private int detectBitstreamBitOrder ( byte[] buf ) {
698
        for ( int i=0; i<buf.length-3; i++ ) {
699
            if ( ((buf[i] & 255)==0xaa) && ((buf[i+1] & 255)==0x99) && ((buf[i+2] & 255)==0x55) && ((buf[i+3] & 255)==0x66) )
700
                return 1;
701
            if ( ((buf[i] & 255)==0x55) && ((buf[i+1] & 255)==0x99) && ((buf[i+2] & 255)==0xaa) && ((buf[i+3] & 255)==0x66) )
702
                return 0;
703
        }
704
        System.err.println("Warning: Unable to determine bitstream bit order: no signature found");
705
        return 0;
706
    }
707
 
708
// ******* swapBits ************************************************************
709
    private void swapBits ( byte[][] buf, int size ) {
710
        int j=0, k=0;
711
        for (int i=0; i<size; i++ ) {
712
            while ( k >= buf[j].length ) {
713
                j++;
714
                k=0;
715
            }
716
            byte b = buf[j][k];
717
            buf[j][k] = (byte) ( ((b & 128) >> 7) |
718
                                 ((b &  64) >> 5) |
719
                                 ((b &  32) >> 3) |
720
                                 ((b &  16) >> 1) |
721
                                 ((b &   8) << 1) |
722
                                 ((b &   4) << 3) |
723
                                 ((b &   2) << 5) |
724
                                 ((b &   1) << 7) );
725
            k++;
726
        }
727
    }
728
 
729 5 ZTEX
// ******* configureFpgaLS *****************************************************
730 2 ZTEX
//  returns configuration time in ms
731
/**
732 5 ZTEX
  * Upload a Bitstream to the FPGA using low speed mode.
733 2 ZTEX
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
734
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
735 3 ZTEX
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
736 2 ZTEX
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
737
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
738
  * @throws AlreadyConfiguredException if the FPGA is already configured.
739
  * @throws InvalidFirmwareException if interface 1 is not supported.
740
  * @throws UsbException if a communication error occurs.
741
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
742
  */
743 5 ZTEX
    public long configureFpgaLS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
744 2 ZTEX
        final int transactionBytes = certainWorkarounds ? 256 : 2048;
745
        long t0 = 0;
746
 
747 3 ZTEX
        checkCapability(CAPABILITY_FPGA);
748 2 ZTEX
 
749
        if ( !force && getFpgaConfiguration() )
750
            throw new AlreadyConfiguredException();
751
 
752
// read the Bitstream file      
753 3 ZTEX
        byte[][] buffer = new byte[16*1024*1024/transactionBytes][];
754 2 ZTEX
        int size = 0;
755
        try {
756
            InputStream inputStream = JInputStream.getInputStream( fwFileName );
757
            int j = transactionBytes;
758
            for ( int i=0; i<buffer.length && j==transactionBytes; i++ ) {
759
                buffer[i] = new byte[transactionBytes];
760 5 ZTEX
                int k;
761
                j = 0;
762
                do {
763
                    k = inputStream.read( buffer[i], j, transactionBytes-j );
764
                    if ( k < 0 )
765
                        k = 0;
766
                    j += k;
767
                }
768
                while ( j<transactionBytes && k>0 );
769
 
770 2 ZTEX
                if ( j < transactionBytes && j % 64 == 0 )       // ensures size % 64 != 0
771
                    j+=1;
772
                size += j;
773
            }
774
 
775
            try {
776
                inputStream.close();
777
            }
778
            catch ( Exception e ) {
779
                System.err.println( "Warning: Error closing file " + fwFileName + ": " + e.getLocalizedMessage() );
780
            }
781
        }
782
        catch (IOException e) {
783
            throw new BitstreamReadException(e.getLocalizedMessage());
784
        }
785
        if ( size < 64 || size % 64 == 0 )
786
            throw new BitstreamReadException("Invalid file size: " + size );
787 3 ZTEX
 
788
// detect bitstream bit order and swap bits if necessary 
789
        if ( bs<0 || bs>1 )
790
            bs = detectBitstreamBitOrder ( buffer[0] );
791
        if ( bs == 1 )
792
            swapBits(buffer,size);
793 2 ZTEX
 
794
// upload the Bitstream file    
795
        for ( int tries=10; tries>0; tries-- ) {
796
 
797
            resetFpga();
798
 
799
            try {
800
                t0 = -new Date().getTime();
801
                int cs = 0;
802 3 ZTEX
                bs = 0;
803 2 ZTEX
 
804
                for ( int i=0; i<buffer.length && i*transactionBytes < size; i++ ) {
805
                    int j = size-i*transactionBytes;
806
                    if (j>transactionBytes)
807
                        j = transactionBytes;
808
                    vendorCommand2(0x32, "sendFpgaData", 0,0, buffer[i], j);
809
 
810
                    bs+=j;
811
                    for ( int k=0; k<buffer[i].length; k++ )
812
                        cs = ( cs + (buffer[i][k] & 0xff) ) & 0xff;
813
                }
814
 
815
                getFpgaState();
816
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+bs+")   fpgaChecksum="+fpgaChecksum + " ("+cs+")   fpgaInitB="+fpgaInitB );
817
                if ( ! fpgaConfigured ) {
818
                    throw new BitstreamUploadException( "FPGA configuration failed: DONE pin does not go high (size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes went lost;  checksum="
819 5 ZTEX
                        + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB +")" );
820 2 ZTEX
                }
821 5 ZTEX
//              System.out.println( "FPGA configuration: size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes went lost;  checksum=" + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB );
822 2 ZTEX
 
823
                tries = 0;
824
                t0 += new Date().getTime();
825
 
826
            }
827
            catch ( BitstreamUploadException e ) {
828
                if ( tries>1 )
829
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
830
                else
831
                    throw e;
832
            }
833
        }
834
 
835
        try {
836
            Thread.sleep( 200 );
837
        }
838
        catch ( InterruptedException e) {
839
        }
840
 
841
        return t0;
842
    }
843
 
844 3 ZTEX
 
845 2 ZTEX
// ******* eepromState *********************************************************
846
// returns true if EEPROM is ready
847
/**
848
  * Reads the current EEPROM status.
849
  * This method also sets the varibles {@link #eepromBytes} and {@link #eepromChecksum}.
850
  * @throws InvalidFirmwareException if interface 1 is not supported.
851
  * @throws UsbException if a communication error occurs.
852
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
853
  * @return true if EEPROM is ready.
854
  */
855
    public boolean eepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
856
        byte[] buf = new byte[4];
857 3 ZTEX
        checkCapability(CAPABILITY_EEPROM);
858 2 ZTEX
        vendorRequest2(0x3A, "EEPROM State", 0, 0, buf, 4);
859
        eepromBytes = (buf[0] & 255) | (buf[1] & 255)<<8;
860
        eepromChecksum = buf[2] & 255;
861
        return buf[3] == 0;
862
    }
863
 
864
// ******* eepromWrite *********************************************************
865
/**
866
  * Writes data to the EEPROM.
867
  * @param addr The destination address of the EEPROM.
868
  * @param buf The data.
869
  * @param length The amount of bytes to be sent.
870
  * @throws InvalidFirmwareException if interface 1 is not supported.
871
  * @throws UsbException if a communication error occurs.
872
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
873
  */
874
    public void eepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
875 3 ZTEX
        checkCapability(CAPABILITY_EEPROM);
876 5 ZTEX
        if ( (addr & 63) != 0 ) {
877
            int i = Math.min(length, 64-(addr & 63));
878
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, i );
879
            try {
880
                Thread.sleep( 10 );
881
            }
882
            catch ( InterruptedException e) {
883
            }
884
            addr+=i;
885
            length-=i;
886
            if ( length > 0 ) {
887
                byte[] buf2 = new byte[length];
888
                for (int j=0; j<length; j++ )
889
                    buf2[j] = buf[i+j];
890
                vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf2, length );
891
            }
892
        }
893
        else {
894
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, length );
895
        }
896
 
897
        try {
898
                Thread.sleep( 10 );
899
        }
900
            catch ( InterruptedException e) {
901
        }
902 2 ZTEX
    }
903
 
904
// ******* eepromRead **********************************************************
905
/**
906
  * Reads data from the EEPROM.
907
  * @param addr The source address of the EEPROM.
908
  * @param buf A buffer for the storage of the data.
909
  * @param length The amount of bytes to be read.
910
  * @throws InvalidFirmwareException if interface 1 is not supported.
911
  * @throws UsbException if a communication error occurs.
912
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
913
  */
914
    public void eepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
915 3 ZTEX
        checkCapability(CAPABILITY_EEPROM);
916 2 ZTEX
        vendorRequest2( 0x38, "EEPROM Read", addr, 0, buf, length );             // sometimes a little bit slow
917
        try {
918
            Thread.sleep( 10 );
919
        }
920
        catch ( InterruptedException e) {
921
        }
922
    }
923
 
924
// ******* eepromUpload ********************************************************
925
//  returns upload time in ms
926
/**
927
  * Upload the firmware to the EEPROM.
928
  * In order to start the uploaded firmware the device must be reset.
929 5 ZTEX
  * @param ihxFile The firmware image.
930 2 ZTEX
  * @param force Skips the compatibility check if true.
931
  * @throws IncompatibleFirmwareException if the given firmware is not compatible to the installed one, see {@link #compatible(int,int,int,int)} (Upload can be enforced using the <tt>force</tt> parameter.)
932
  * @throws InvalidFirmwareException if interface 1 is not supported.
933
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
934
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
935
  */
936 5 ZTEX
    public long eepromUpload ( ZtexIhxFile1 ihxFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
937 2 ZTEX
        final int pagesMax = 256;
938
        final int pageSize = 256;
939
        int pages = 0;
940
        byte[][] buffer = new byte[pagesMax][];
941
 
942 3 ZTEX
        checkCapability(CAPABILITY_EEPROM);
943 5 ZTEX
 
944 2 ZTEX
//      ihxFile.dataInfo(System.out);
945
//      System.out.println(ihxFile);
946 5 ZTEX
 
947 2 ZTEX
// check for compatibility
948
        if ( ! force && dev().valid() ) {
949
            if ( ihxFile.interfaceVersion() != 1 )
950
                throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ihxFile.interfaceVersion() );
951
 
952
            if ( ! dev().compatible ( ihxFile.productId(0), ihxFile.productId(1), ihxFile.productId(2), ihxFile.productId(3) ) )
953
                throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev().productId())
954
                    + "  Ihx File: " + ZtexDevice1.byteArrayString(ihxFile.productId()) );
955
        }
956
 
957
        Usb_Device_Descriptor dd = dev().dev().getDescriptor();
958
        int vid = dd.getIdVendor() & 65535;
959
        int pid = dd.getIdProduct() & 65535;
960
 
961
        buffer[0] = new byte[pageSize];
962
        buffer[0][0] = (byte) 0xc2;
963
        buffer[0][1] = (byte) (vid & 255);
964
        buffer[0][2] = (byte) ((vid >> 8) & 255);
965
        buffer[0][3] = (byte) (pid & 255);
966
        buffer[0][4] = (byte) ((pid >> 8) & 255);
967
        buffer[0][5] = 0;
968
        buffer[0][6] = 0;
969
        buffer[0][7] = 0;
970
 
971
        int ptr = 8, i = 0;
972
 
973
        while ( i < ihxFile.ihxData.length ) {
974
            if ( ihxFile.ihxData[i]>=0 && ihxFile.ihxData[i]<256 ) {                     // new data block
975
                int j = 1;
976 5 ZTEX
                while ( i+j<ihxFile.ihxData.length && ihxFile.ihxData[i+j]>=0 && ihxFile.ihxData[i+j]<256 )
977 2 ZTEX
                    j++;
978
 
979 5 ZTEX
                for (int k=ptr/pageSize + 1; k < (ptr+j+9)/pageSize + 1; k++ )  // also considers 5 bytes for the last data block
980 2 ZTEX
                    buffer[k] = new byte[pageSize];
981
 
982
                buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) ((j >> 8) & 255);
983
                buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) (j & 255);                // length
984
                buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((i >> 8) & 255);
985
                buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) (i & 255);                // address
986
                ptr+=4;
987
                for ( int k=0; k<j; k++ )                                        // data
988
                    buffer[(ptr+k)/pageSize][(ptr+k) % pageSize] = (byte) ihxFile.ihxData[i+k];
989
                ptr+=j;
990
                i+=j;
991
            }
992
            else {
993
                i+=1;
994
            }
995
        }
996
 
997
        buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) 0x80;               // last data block
998
        buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) 0x01;
999
        buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) 0xe6;
1000
        buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) 0x00;
1001
        buffer[(ptr+3)/pageSize][(ptr+4) % pageSize] = (byte) 0x00;
1002
        ptr+=5;
1003
 
1004
 
1005
        long t0 = new Date().getTime();
1006
        byte[] rbuf = new byte[pageSize];
1007
 
1008
        for ( i=(ptr-1)/pageSize; i>=0; i-- ) {
1009
 
1010
            int k = (i+1)*pageSize < ptr ? pageSize : ptr-i*pageSize;
1011
            int cs = 0;
1012
            for (int j=0; j<k; j++ ) {
1013
                cs = ( cs + (buffer[i][j] & 255) ) & 255;
1014
            }
1015
 
1016
            for ( int tries=3; tries>0; tries-- ) {
1017
                try {
1018
                    eepromWrite(i*pageSize, buffer[i], k);
1019
                    eepromState();
1020
                    if ( eepromBytes!=k )
1021
                        throw new FirmwareUploadException("Error writing data to EEPROM: Wrote " + eepromBytes + " bytes instead of "  + k + " bytes" );
1022
                    if ( eepromChecksum!=cs )
1023
                        throw new FirmwareUploadException("Error writing data to EEPROM: Checksum error");
1024
 
1025
                    eepromRead(i*pageSize, rbuf, k);
1026
                    for (int j=0; j<k; j++ ) {
1027
                        if ( rbuf[j] != buffer[i][j] )
1028
                            throw new FirmwareUploadException("Error writing data to EEPROM: Verification failed");
1029
                    }
1030
                    tries = 0;
1031
                }
1032
                catch ( Exception e ) {
1033
                    if ( tries > 1 ) {
1034
                        System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1035
                    }
1036
                    else {
1037
                        throw new FirmwareUploadException(e.getLocalizedMessage());
1038
                    }
1039
                }
1040
            }
1041
        }
1042
 
1043
        return new Date().getTime() - t0;
1044
    }
1045
 
1046 5 ZTEX
//  returns upload time in ms
1047
/**
1048
  * Upload the firmware to the EEPROM.
1049
  * In order to start the uploaded firmware the device must be reset.
1050
  * @param ihxFileName The file name of the firmware image in ihx format. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
1051
  * @param force Skips the compatibility check if true.
1052
  * @throws IncompatibleFirmwareException if the given firmware is not compatible to the installed one, see {@link #compatible(int,int,int,int)} (Upload can be enforced using the <tt>force</tt> parameter.)
1053
  * @throws InvalidFirmwareException if interface 1 is not supported.
1054
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1055
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1056
  */
1057
    public long eepromUpload ( String ihxFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1058
        checkCapability(CAPABILITY_EEPROM);
1059
 
1060
// load the ihx file
1061
        ZtexIhxFile1 ihxFile;
1062
        try {
1063
            ihxFile = new ZtexIhxFile1( ihxFileName );
1064
        }
1065
        catch ( IOException e ) {
1066
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1067
        }
1068
        catch ( IhxFileDamagedException e ) {
1069
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1070
        }
1071
 
1072
        return eepromUpload( ihxFile, force );
1073
    }
1074
 
1075
 
1076 2 ZTEX
// ******* eepromDisable ********************************************************
1077
/**
1078
  * Disables the firmware stored in the EEPROM.
1079
  * This is achived by writing a "0" to the address 0 of the EEPROM.
1080
  * @throws InvalidFirmwareException if interface 1 is not supported.
1081
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1082
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
1083
  */
1084
    public void eepromDisable ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1085
        byte[] buf = { 0 };
1086
 
1087
        for ( int tries=3; tries>0; tries-- ) {
1088
            try {
1089
                eepromWrite(0, buf, 1);
1090
 
1091
                eepromRead(0, buf, 1);
1092
                if ( buf[0] != 0 )
1093
                    throw new FirmwareUploadException("Error disabeling EEPROM firmware: Verification failed");
1094
                tries = 0;
1095
 
1096
            }
1097
            catch ( Exception e ) {
1098
                if ( tries > 1 ) {
1099
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1100
                }
1101
                else {
1102
                    throw new FirmwareUploadException(e.getLocalizedMessage());
1103
                }
1104
            }
1105
        }
1106
    }
1107
 
1108
// ******* flashStrError *******************************************************
1109
/**
1110
  * Converts a given error code into a String.
1111
  * @param errNum The error code.
1112
  * @return an error message.
1113
  */
1114
    public static String flashStrError ( int errNum ) {
1115
        switch ( errNum ) {
1116
            case FLASH_EC_NO_ERROR:
1117
                return "USB error: " + LibusbJava.usb_strerror();
1118
            case FLASH_EC_CMD_ERROR:
1119
                return "Command error";
1120
            case FLASH_EC_TIMEOUT:
1121
                return "Timeout error";
1122
            case FLASH_EC_BUSY:
1123
                return "Busy";
1124
            case FLASH_EC_PENDING:
1125
                return "Another operation is pending";
1126
            case FLASH_EC_READ_ERROR:
1127
                return "Read error";
1128
            case FLASH_EC_WRITE_ERROR:
1129
                return "Write error";
1130
            case FLASH_EC_NOTSUPPORTED:
1131
                return "Not supported";
1132
        }
1133
        return "Error " + errNum;
1134
    }
1135
 
1136
/**
1137
  * Gets the last Flash error from the device.
1138
  * @return an error message.
1139
  */
1140
    public String flashStrError ( ) {
1141
        try {
1142
            return flashStrError( getFlashEC() );
1143
        }
1144
        catch ( Exception e ) {
1145
            return "Unknown error (Error receiving errorcode: "+e.getLocalizedMessage() +")";
1146
        }
1147
    }
1148
 
1149
// ******* flashState **********************************************************
1150
/**
1151
  * Reads the the Flash memory status and information.
1152 5 ZTEX
  * This method also sets the variables {@link #flashEnabled()}, {@link #flashSectorSize()} and {@link #flashSectors()}.
1153 2 ZTEX
  * @return true if Flash memory is installed.
1154
  * @throws InvalidFirmwareException if interface 1 is not supported.
1155
  * @throws UsbException if a communication error occurs.
1156
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1157
  */
1158
    public boolean flashState () throws UsbException, InvalidFirmwareException, CapabilityException {
1159
        byte[] buf = new byte[8];
1160 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1161 2 ZTEX
 
1162
        // device may be busy due to initialization, we try it up to up to 4s
1163
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1164
        flashEC = buf[7] & 255;
1165
        int tries=20;
1166
        while ( flashEC==FLASH_EC_BUSY && tries>0 )
1167
        {
1168
            try {
1169
                Thread.sleep( 200 );
1170
            }
1171
            catch ( InterruptedException e) {
1172
            }
1173
            tries-=1;
1174
            vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1175
            flashEC = buf[7] & 255;
1176
        }
1177
        flashEnabled = buf[0] & 255;
1178
        flashSectorSize = flashEnabled == 1 ? ((buf[2] & 255) << 8) | (buf[1] & 255) : 0;
1179
        flashSectors = flashEnabled == 1 ? ((buf[6] & 255) << 24) | ((buf[5] & 255) << 16) | ((buf[4] & 255) << 8) | (buf[3] & 255) : 0;
1180
        return flashEnabled == 1;
1181
    }
1182
 
1183
// ******* getFlashEC **********************************************************
1184
// reads the current error code
1185
/**
1186
  * Gets the last Flash error from the device.
1187 3 ZTEX
  * @return The last error code.
1188 2 ZTEX
  * @throws InvalidFirmwareException if interface 1 is not supported.
1189
  * @throws UsbException if a communication error occurs.
1190
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1191
  */
1192
    public int getFlashEC () throws UsbException, InvalidFirmwareException, CapabilityException {
1193
        byte[] buf = new byte[8];
1194 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1195 2 ZTEX
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1196
        flashEC = buf[7] & 255;
1197
        return flashEC;
1198
    }
1199
 
1200
// ******* flashReadSector ****************************************************
1201
// read exactly one sector
1202
/**
1203
  * Reads one sector from the Flash.
1204
  * @param sector The sector number to be read.
1205
  * @param buf A buffer for the storage of the data.
1206
  * @throws InvalidFirmwareException if interface 1 is not supported.
1207
  * @throws UsbException if a communication error occurs.
1208
  * @throws CapabilityException if Flash memory access is not possible.
1209 5 ZTEX
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
1210 2 ZTEX
  */
1211 5 ZTEX
    public void flashReadSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1212
        if ( buf.length < flashSectorSize() )
1213
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash sector size: " + buf.length + " < " + flashSectorSize());
1214
 
1215 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1216 2 ZTEX
        if ( ! flashEnabled() )
1217
            throw new CapabilityException(this, "No Flash memory installed or");
1218
 
1219
        try {
1220
            vendorRequest2( 0x41, "Flash Read", sector, sector >> 16, buf, flashSectorSize );
1221
        }
1222
        catch ( UsbException e ) {
1223
            throw new UsbException( dev().dev(), "Flash Read: " + flashStrError() );
1224
        }
1225
    }
1226
 
1227 5 ZTEX
// read a integer number of sectors
1228
/**
1229
  * Reads a integer number of sectors from the Flash.
1230
  * @param sector The number of the first sector to be read.
1231
  * @param num The number of sectors to be read.
1232
  * @param buf A buffer for the storage of the data.
1233
  * @throws InvalidFirmwareException if interface 1 is not supported.
1234
  * @throws UsbException if a communication error occurs.
1235
  * @throws CapabilityException if Flash memory access is not possible.
1236
  * @throws IndexOutOfBoundsException If the buffer is to small.
1237
  */
1238
    public void flashReadSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1239
        if ( buf.length < flashSectorSize() )
1240
            throw new IndexOutOfBoundsException( "Buffer is to small: " + buf.length + " < " + (num*flashSectorSize()) );
1241
 
1242
        checkCapability(CAPABILITY_FLASH);
1243
        if ( ! flashEnabled() )
1244
            throw new CapabilityException(this, "No Flash memory installed or");
1245
 
1246
        try {
1247
            vendorRequest2( 0x41, "Flash Read", sector, sector >> 16, buf, flashSectorSize*num );
1248
        }
1249
        catch ( UsbException e ) {
1250
            throw new UsbException( dev().dev(), "Flash Read: " + flashStrError() );
1251
        }
1252
    }
1253
 
1254 2 ZTEX
// ******* flashWriteSector ***************************************************
1255
// write exactly one sector
1256
/**
1257
  * Writes one sector to the Flash.
1258
  * @param sector The sector number to be written.
1259
  * @param buf The data.
1260
  * @throws InvalidFirmwareException if interface 1 is not supported.
1261
  * @throws UsbException if a communication error occurs.
1262
  * @throws CapabilityException if Flash memory access is not possible.
1263 5 ZTEX
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
1264 2 ZTEX
  */
1265 5 ZTEX
    public void flashWriteSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1266
        if ( buf.length < flashSectorSize() )
1267
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash sector size: " + buf.length + " < " + flashSectorSize());
1268
 
1269 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1270 2 ZTEX
        if ( ! flashEnabled() )
1271
            throw new CapabilityException(this, "No Flash memory installed or");
1272
 
1273
        try {
1274
            vendorCommand2( 0x42, "Flash Write", sector, sector >> 16, buf, flashSectorSize );
1275
        }
1276
        catch ( UsbException e ) {
1277
            throw new UsbException( dev().dev(), "Flash Write: " + flashStrError() );
1278
        }
1279
    }
1280
 
1281 5 ZTEX
// ******* flashWriteSector ***************************************************
1282
// write integer number of sectors
1283
/**
1284
  * Writes a integer number of sectors to the Flash.
1285
  * @param sector The sector number to be written.
1286
  * @param num The number of sectors to be read.
1287
  * @param buf The data.
1288
  * @throws InvalidFirmwareException if interface 1 is not supported.
1289
  * @throws UsbException if a communication error occurs.
1290
  * @throws CapabilityException if Flash memory access is not possible.
1291
  * @throws IndexOutOfBoundsException If the buffer is to small.
1292
  */
1293
    public void flashWriteSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1294
        if ( buf.length < flashSectorSize() )
1295
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash sector size: " + buf.length + " < " + (num*flashSectorSize()));
1296
 
1297
        checkCapability(CAPABILITY_FLASH);
1298
        if ( ! flashEnabled() )
1299
            throw new CapabilityException(this, "No Flash memory installed or");
1300
 
1301
        try {
1302
            vendorCommand2( 0x42, "Flash Write", sector, sector >> 16, buf, flashSectorSize*num );
1303
        }
1304
        catch ( UsbException e ) {
1305
            throw new UsbException( dev().dev(), "Flash Write: " + flashStrError() );
1306
        }
1307
    }
1308
 
1309 2 ZTEX
// ******* flashEnabled ********************************************************
1310
// returns enabled / disabled state 
1311
/**
1312
  * Returns true if Flash memory is installed.
1313
  * @return true if Flash memory is installed.
1314
  * @throws InvalidFirmwareException if interface 1 is not supported.
1315
  * @throws UsbException if a communication error occurs.
1316
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1317
  */
1318
    public boolean flashEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
1319
        if ( flashEnabled < 0 ) // init variable
1320
            flashState();
1321
        return flashEnabled == 1;
1322
    }
1323
 
1324
// ******* flashSectorSize *****************************************************
1325
// returns sector size of Flash memory, if available
1326
/**
1327
  * Returns the sector size of the Flash memory or 0, if no flash memory is installed.
1328
  * If required, the sector size is determined form the device first.
1329
  * @return the sector size of the Flash memory.
1330
  * @throws InvalidFirmwareException if interface 1 is not supported.
1331
  * @throws UsbException if a communication error occurs.
1332
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1333
  */
1334
    public int flashSectorSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1335
        if ( flashSectorSize < 0 ) // init variable
1336
            flashState();
1337
        return flashSectorSize;
1338
    }
1339
 
1340
// ******* flashSectors ********************************************************
1341
// returns number of sectors of Flash memory, if available
1342
/**
1343
  * Returns the number of sectors of the Flash memory or 0, if no Flash memory is installed.
1344
  * If required, the number of sectors is determined form the device first.
1345
  * @return the number of sectors of the Flash memory.
1346
  * @throws InvalidFirmwareException if interface 1 is not supported.
1347
  * @throws UsbException if a communication error occurs.
1348
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1349
  */
1350
    public int flashSectors () throws UsbException, InvalidFirmwareException, CapabilityException {
1351
        if ( flashSectors < 0 ) // init variable
1352
            flashState();
1353
        return flashSectors;
1354
    }
1355
 
1356
// ******* flashSize ***********************************************************
1357
// returns size of Flash memory, if available
1358
/**
1359
  * Returns the size of Flash memory or 0, if no Flash memory is installed.
1360
  * If required, the Flash size is determined form the device first.
1361
  * @return the size of Flash memory.
1362
  * @throws InvalidFirmwareException if interface 1 is not supported.
1363
  * @throws UsbException if a communication error occurs.
1364
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1365
  */
1366
    public long flashSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1367
        return flashSectorSize() * (long)flashSectors();
1368
    }
1369
 
1370
// ******* printMmcState *******************************************************
1371
// returns true if Flash is available
1372
/**
1373
  * Prints out some debug information about *SD/MMC Flash cards in SPI mode.<br>
1374
  * <b>Only use this method if such kind of Flash is installed.</b>
1375
  * @throws InvalidFirmwareException if interface 1 is not supported.
1376
  * @throws UsbException if a communication error occurs.
1377
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1378
  */
1379
    public boolean printMmcState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1380
        byte[] buf = new byte[23];
1381 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1382 2 ZTEX
        vendorRequest2(0x43, "MMC State", 0, 0, buf, 23);
1383
        System.out.println("status=" + Integer.toBinaryString(256+(buf[0] & 255)).substring(1) + "." + Integer.toBinaryString(256+(buf[1] & 255)).substring(1) +
1384
                "   lastCmd=" + buf[3] +
1385
                "   lastCmdResponse=" + Integer.toBinaryString(256+(buf[4] & 255)).substring(1) +
1386
                "   ec=" + buf[2] +
1387
                "   BUSY=" + buf[22] +
1388
                "   SDHC=" + buf[5] +
1389
                "   buf=" + (buf[6] & 255)+" "+(buf[7] & 255)+" "+(buf[8] & 255)+" "+(buf[9] & 255)+" "+(buf[10] & 255)+" "+(buf[11] & 255)+"  "+(buf[12] & 255)); // +" "+(buf[13] & 255)+" "+(buf[14] & 255)+" "+(buf[15] & 255)+" "+(buf[16] & 255)+" "+(buf[17] & 255));
1390
 
1391
        return flashEnabled == 1;
1392
    }
1393
 
1394
// ******* flashUploadBitstream ************************************************
1395
/*
1396
    Returns configuration time in ms.
1397
    The format of the boot sector (sector 0 of the Flash memory) is
1398
        0..7
1399
        8..9    Number of sectors, or 0 is disabled
1400
        10..11  Number of bytes in the last sector, i.e. th total size of Bitstream is ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
1401
*/
1402
/**
1403
  * Uploads a Bitstream to the Flash.
1404
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
1405
  * it is possible to construct fully autonomous devices.
1406
  * <p>
1407
  * Information about the bitstream is stored in sector 0.
1408
  * This so called boot sector has the following format:
1409
  * <table bgcolor="#404040" cellspacing=1 cellpadding=4>
1410
  *   <tr>
1411
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
1412
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
1413
  *   </tr>
1414
  *   <tr>
1415
  *     <td bgcolor="#ffffff" valign="top">0..7</td>
1416
  *     <td bgcolor="#ffffff" valign="top">ID, must be "ZTEXBS",1,1</td>
1417
  *   </tr>
1418
  *   <tr>
1419
  *     <td bgcolor="#ffffff" valign="top">8..9</td>
1420
  *     <td bgcolor="#ffffff" valign="top">The number of sectors used to store the Bitstream. 0 means no Bitstream.</td>
1421
  *   </tr>
1422
  *   <tr>
1423
  *     <td bgcolor="#ffffff" valign="top">10..11</td>
1424
  *     <td bgcolor="#ffffff" valign="top">The number of bytes in the last sector.</td>
1425
  *   </tr>
1426
  *   <tr>
1427
  *     <td bgcolor="#ffffff" valign="top">12..sectorSize-1</td>
1428
  *     <td bgcolor="#ffffff" valign="top">This data is reserved for future use and preserved by this method.</td>
1429
  *   </tr>
1430
  * </table>
1431
  * <p>
1432
  * The total size of the Bitstream is computed as ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
1433
  * where bs[i] denotes byte i of the boot sector.
1434
  * <p>
1435
  * The first sector of the Bitstream is sector 1.
1436
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
1437 3 ZTEX
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1438 2 ZTEX
  * @throws InvalidFirmwareException if interface 1 is not supported.
1439
  * @throws UsbException if a communication error occurs.
1440
  * @throws CapabilityException if Flash memory access is not possible.
1441
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1442
  */
1443 3 ZTEX
    public long flashUploadBitstream ( String fwFileName, int bs ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1444 5 ZTEX
        int secNum = 2048 / flashSectorSize;
1445
        final int bufferSize = secNum * flashSectorSize;
1446 3 ZTEX
        checkCapability(CAPABILITY_FPGA);
1447
        checkCapability(CAPABILITY_FLASH);
1448 2 ZTEX
        if ( ! flashEnabled() )
1449
            throw new CapabilityException(this, "No Flash memory installed or");
1450
        getFpgaState();
1451
 
1452
// read the Bitstream file      
1453 3 ZTEX
        byte[][] buffer = new byte[32768][];
1454 5 ZTEX
        int i,j,k;
1455 2 ZTEX
        try {
1456
            InputStream inputStream = JInputStream.getInputStream( fwFileName );
1457 5 ZTEX
            j = bufferSize;
1458
            for ( i=0; i<buffer.length && j==bufferSize; i++ ) {
1459
                buffer[i] = new byte[bufferSize];
1460
                j = 0;
1461
                do {
1462
                    k = inputStream.read( buffer[i], j, bufferSize-j );
1463
                    if ( k < 0 )
1464
                        k = 0;
1465
                    j += k;
1466
                }
1467
                while ( j<bufferSize && k>0 );
1468 2 ZTEX
            }
1469
 
1470
            try {
1471
                inputStream.close();
1472
            }
1473
            catch ( Exception e ) {
1474
                System.err.println( "Warning: Error closing file " + fwFileName + ": " + e.getLocalizedMessage() );
1475
            }
1476
        }
1477
        catch (IOException e) {
1478
            throw new BitstreamReadException(e.getLocalizedMessage());
1479
        }
1480
 
1481 3 ZTEX
// detect bitstream bit order and swap bits if necessary 
1482
        if ( bs<0 || bs>1 )
1483
            bs = detectBitstreamBitOrder(buffer[0]);
1484
        if ( fpgaFlashBitSwap != (bs==1) )
1485 5 ZTEX
            swapBits( buffer, bufferSize*i );
1486 3 ZTEX
 
1487 2 ZTEX
// upload the Bitstream file    
1488
        byte[] sector = new byte[flashSectorSize];
1489
        byte[] ID = new String("ZTEXBS").getBytes();
1490
 
1491 5 ZTEX
        flashReadSector(0,sector);                               // read the boot sector (only the first 16 bytes are overwritten)
1492
        for (k=0; k<6; k++)
1493 2 ZTEX
            sector[k]=ID[k];
1494
        sector[6] = 1;
1495
        sector[7] = 1;
1496 5 ZTEX
        k = (i-1)*secNum + (j-1)/flashSectorSize + 1;
1497
        sector[8] = (byte) (k & 255);
1498
        sector[9] = (byte) ((k>>8) & 255);
1499
        k = ((j-1) % flashSectorSize) + 1;
1500
        sector[10] = (byte) (k & 255);
1501
        sector[11] = (byte) ((k>>8) & 255);
1502 2 ZTEX
        long t0 = new Date().getTime();
1503 5 ZTEX
        flashWriteSector(0,sector);                              // write the boot sector
1504
        for (k=0; k<i-1; k++)
1505
            flashWriteSector( 1+k*secNum, secNum, buffer[k] );  // write the Bitstream sectors
1506
        flashWriteSector( 1+k*secNum, (j-1)/flashSectorSize + 1, buffer[k] );
1507 2 ZTEX
 
1508
        return new Date().getTime() - t0;
1509
    }
1510
 
1511 3 ZTEX
/**
1512
  * Uploads a Bitstream to the Flash.
1513
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
1514
  * it is possible to construct fully autonomous devices.
1515
  * See {@link #flashUploadBitstream(String,int)} for further details.
1516
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
1517
  * @throws InvalidFirmwareException if interface 1 is not supported.
1518
  * @throws UsbException if a communication error occurs.
1519
  * @throws CapabilityException if Flash memory access is not possible.
1520
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1521
  */
1522
    public long flashUploadBitstream ( String fwFileName ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1523
        return flashUploadBitstream(fwFileName, -1);
1524
    }
1525
 
1526 2 ZTEX
// ******* flashResetBitstream *************************************************
1527
// Clears a Bitstream from the Flash.
1528
/**
1529
  * Clears a Bitstream from the Flash.
1530
  * This is achieved by writing 0 to bytes 8..9 of the boot sector, see {@link #flashUploadBitstream(String)}.
1531
  * If no boot sector is installed the method returns without any write action.
1532
  * @throws InvalidFirmwareException if interface 1 is not supported.
1533
  * @throws UsbException if a communication error occurs.
1534
  * @throws CapabilityException if Flash memory access is not possible.
1535
  */
1536
    public void flashResetBitstream ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1537 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1538 2 ZTEX
        if ( ! flashEnabled() )
1539
            throw new CapabilityException(this, "No Flash memory installed or");
1540
        byte[] sector = new byte[flashSectorSize];
1541
        byte[] ID = new String("ZTEXBS").getBytes();
1542
 
1543
        flashReadSector(0,sector);                       // read the boot sector
1544
        for (int k=0; k<6; k++)
1545
            if ( sector[k] != ID[k] )
1546
                return;
1547
        if (sector[6]!=1 || sector[7]!=1 )
1548
            return;
1549
        sector[8] = 0;
1550
        sector[9] = 0;
1551
        flashWriteSector(0,sector);                      // write the boot sector
1552
    }
1553
 
1554
// ******* flashFirstFreeSector ************************************************
1555
// Returns the first free sector of the Flash memory, i.e. the first sector behind the Bitstream
1556
/**
1557
  * Returns the first free sector of the Flash memory.
1558
  * This is the first sector behind the Bitstream, or 0 if no boot sector is installed (or 1 if a boot sector but no Bitstream is installed).
1559
  * @return the first free sector of the Flash memory.
1560
  * @throws InvalidFirmwareException if interface 1 is not supported.
1561
  * @throws UsbException if a communication error occurs.
1562
  * @throws CapabilityException if Flash memory access is not possible.
1563
  */
1564
    public int flashFirstFreeSector ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1565 3 ZTEX
        checkCapability(CAPABILITY_FLASH);
1566 2 ZTEX
        if ( ! flashEnabled() )
1567
            throw new CapabilityException(this, "No Flash memory installed or");
1568
 
1569
        byte[] sector = new byte[flashSectorSize];
1570
        byte[] ID = new String("ZTEXBS").getBytes();
1571
 
1572
        flashReadSector(0,sector);                       // read the boot sector
1573
        for (int k=0; k<6; k++)
1574
            if ( sector[k] != ID[k] )
1575
                return 0;
1576
        if (sector[6]!=1 || sector[7]!=1 )
1577
            return 0;
1578
        return (sector[8] & 255) + ((sector[9] & 255) << 8) + 1;
1579
    }
1580
 
1581 3 ZTEX
 
1582
// ******* debugStackSize ******************************************************
1583
/**
1584
  * Returns the size of message stack in messages.
1585
  * @return the size of message stack in messages.
1586
  * @throws InvalidFirmwareException if interface 1 is not supported.
1587
  * @throws UsbException if a communication error occurs.
1588
  * @throws CapabilityException if Flash memory access is not possible.
1589
  */
1590
    public int debugStackSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1591
        checkCapability(CAPABILITY_DEBUG);
1592
        if ( debugStackSize<=0 || debugMsgSize<=0 ) {
1593
            byte[] buf = new byte[7];
1594
            vendorRequest2(0x28, "Read debug data", 0, 0, buf, 4);
1595
            debugStackSize = buf[2] & 255;
1596
            debugMsgSize = buf[3] & 255;
1597
        }
1598
        return debugStackSize;
1599
    }
1600
 
1601
// ******* debugMsgSize ********************************************************
1602
/**
1603
  * Returns the size of messages in bytes.
1604
  * @return the size of messages in bytes.
1605
  * @throws InvalidFirmwareException if interface 1 is not supported.
1606
  * @throws UsbException if a communication error occurs.
1607
  * @throws CapabilityException if Flash memory access is not possible.
1608
  */
1609
    public int debugMsgSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1610
        checkCapability(CAPABILITY_DEBUG);
1611
        if ( debugMsgSize<=0 )
1612
            debugStackSize();
1613
 
1614
        return debugMsgSize;
1615
    }
1616
 
1617
// ******* debugLastMsg ********************************************************
1618
/**
1619
  * Returns the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
1620
  * @return the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
1621
  */
1622
    public final int debugLastMsg ( )  {
1623
        return debugLastMsg;
1624
    }
1625
 
1626
// ******* debugReadMessages ***************************************************
1627
/**
1628
  * Reads debug messages from message stack.
1629
  * The number of messages stored in buf is returned. The total number of new messages is stored in {@link #debugNewMessages}.
1630
  * The number of the latest message is returned by {@link #debugLastMsg()}.
1631
  * @param all If true, all messages from stack are written to buf. If it is false, only the new messages are written to buf.
1632
  * @param buf The buffer to store the messages.
1633
  * @return the size of messages stored in buffer.
1634
  * @throws InvalidFirmwareException if interface 1 is not supported.
1635
  * @throws UsbException if a communication error occurs.
1636
  * @throws CapabilityException if Flash memory access is not possible.
1637
  */
1638
    public int debugReadMessages ( boolean all, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException {
1639
        checkCapability(CAPABILITY_DEBUG);
1640
        byte buf2[] = new byte[ debugStackSize()*debugMsgSize() + 4 ];
1641
        vendorRequest2(0x28, "Read debug data", 0, 0, buf2, buf2.length);
1642
        int lm = (buf2[0] & 255) | ((buf2[1] & 255) << 8);
1643
        debugNewMessages = lm - debugLastMsg;
1644
 
1645
        int r = Math.min( Math.min( buf.length/debugMsgSize() , debugStackSize ), lm);
1646
        if ( !all ) r = Math.min(r,debugNewMessages);
1647
        for (int i = 0; i<r; i++) {
1648
            int k=(lm-r+i) % debugStackSize;
1649
            for (int j=0; j<debugMsgSize; j++ )
1650
                buf[i*debugMsgSize+j] = buf2[k*debugMsgSize+j+4];
1651
        }
1652
 
1653
        debugLastMsg = lm;
1654
        return r;
1655
    }
1656
 
1657 5 ZTEX
// ******* xmegaStrError *******************************************************
1658
/**
1659
  * Converts a given error code into a String.
1660
  * @param errNum The error code.
1661
  * @return an error message.
1662
  */
1663
    public String xmegaStrError ( int errNum ) {
1664
        switch ( errNum ) {
1665
            case XMEGA_EC_NO_ERROR:
1666
                return "USB error: " + LibusbJava.usb_strerror();
1667
            case XMEGA_EC_PDI_READ_ERROR:
1668
                return "PDI read error";
1669
            case XMEGA_EC_NVM_TIMEOUT:
1670
                return "NVM timeout error";
1671
            case XMEGA_EC_INVALID_DEVICE:
1672
                return "Invalid or unsupported ATxmega";
1673
            case XMEGA_EC_ADDRESS_ERROR:
1674
                return "Address error (invalid address or wrong page size)";
1675
            case XMEGA_EC_NVM_BUSY:
1676
                return "NVM busy";
1677
        }
1678
        return "Error " + errNum;
1679
    }
1680
 
1681
/**
1682
  * Gets the last ATxmega error from the device.
1683
  * @return an error message.
1684
  */
1685
    public String xmegaStrError ( ) {
1686
        try {
1687
            return xmegaStrError( xmegaState() );
1688
        }
1689
        catch ( Exception e ) {
1690
            return "Unknown error (Error receiving error code: "+e.getLocalizedMessage() +")";
1691
        }
1692
    }
1693
 
1694
// ******* xmegaState **********************************************************
1695
/**
1696
  * Read ATxmega error and status information from the device.
1697
  * @return The last error code.
1698
  * @throws InvalidFirmwareException if interface 1 is not supported.
1699
  * @throws UsbException if a communication error occurs.
1700
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
1701
  */
1702
    public int xmegaState () throws UsbException, InvalidFirmwareException, CapabilityException {
1703
        byte[] buf = new byte[7];
1704
        checkCapability(CAPABILITY_XMEGA);
1705
        vendorRequest2(0x48, "Xmega state", 0, 0, buf, 7);
1706
        xmegaEC = buf[0] & 255;
1707
 
1708
        xmegaFlashPages = ((buf[2] & 255) << 8) | (buf[1] & 255);
1709
        xmegaEepromPages = ((buf[4] & 255) << 8) | (buf[3] & 255);
1710
        xmegaFlashPageSize = 1 << (buf[5] & 15);
1711
        xmegaEepromPageSize = 1 << (buf[6] & 15);
1712
        return xmegaEC;
1713
    }
1714
 
1715
// ******* xmegaEnabled ********************************************************
1716
/**
1717
  * Returns true if ATxmega controller is available.
1718
  * @return true if ATxmega controller is available.
1719
  * @throws InvalidFirmwareException if interface 1 is not supported.
1720
  * @throws UsbException if a communication error occurs.
1721
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
1722
  */
1723
    public boolean xmegaEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
1724
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
1725
            xmegaState();
1726
        return xmegaFlashPages > 0 && xmegaEepromPages > 0;
1727
    }
1728
 
1729
// ******* xmegaFlashPages *****************************************************
1730
/**
1731
  * Returns the number of the ATxmega Flash pages.
1732
  * @return The number of the ATxmega Flash pages.
1733
  * @throws InvalidFirmwareException if interface 1 is not supported.
1734
  * @throws UsbException if a communication error occurs.
1735
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
1736
  */
1737
    public int xmegaFlashPages () throws UsbException, InvalidFirmwareException, CapabilityException {
1738
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
1739
            xmegaState();
1740
        return xmegaFlashPages;
1741
    }
1742
 
1743
// ******* xmegaEepromPages ****************************************************
1744
/**
1745
  * Returns the number of the ATxmega EEPROM pages.
1746
  * @return The number of the ATxmega EEPROM pages.
1747
  * @throws InvalidFirmwareException if interface 1 is not supported.
1748
  * @throws UsbException if a communication error occurs.
1749
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
1750
  */
1751
    public int xmegaEepromPages () throws UsbException, InvalidFirmwareException, CapabilityException {
1752
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
1753
            xmegaState();
1754
        return xmegaEepromPages;
1755
    }
1756
 
1757
// ******* xmegaFlashPageSize **************************************************
1758
/**
1759
  * Returns the size of the ATxmega Flash pages.
1760
  * @return The size of the ATxmega Flash pages.
1761
  * @throws InvalidFirmwareException if interface 1 is not supported.
1762
  * @throws UsbException if a communication error occurs.
1763
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
1764
  */
1765
    public int xmegaFlashPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1766
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
1767
            xmegaState();
1768
        return xmegaFlashPageSize;
1769
    }
1770
 
1771
// ******* xmegaEEpromPageSize *************************************************
1772
/**
1773
  * Returns the size of the ATXmega EEPROM pages.
1774
  * @return The size of the ATXmega EEPROM pages.
1775
  * @throws InvalidFirmwareException if interface 1 is not supported.
1776
  * @throws UsbException if a communication error occurs.
1777
  * @throws CapabilityException if ATXmega controllers are not supported by the firmware.
1778
  */
1779
    public int xmegaEepromPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1780
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
1781
            xmegaState();
1782
        return xmegaEepromPageSize;
1783
    }
1784
 
1785
// ******* xmegaReset **********************************************************
1786
/**
1787
  * Resets the ATxmega.
1788
  * @throws InvalidFirmwareException if interface 1 is not supported.
1789
  * @throws UsbException if a communication error occurs.
1790
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
1791
  */
1792
    public void xmegaReset () throws UsbException, InvalidFirmwareException, CapabilityException {
1793
        checkCapability(CAPABILITY_XMEGA);
1794
        try {
1795
            vendorCommand( 0x49, "XMEGA Reset" );
1796
        }
1797
        catch ( UsbException e ) {
1798
            throw new UsbException( dev().dev(), "NVM Reset: " + xmegaStrError() );
1799
        }
1800
    }
1801
 
1802
 
1803
// ******* xmegaNvmRead ********************************************************
1804
/**
1805
  * Reads data from the NVM of ATxmega.
1806
  * @param addr The source address of the NVM (PDI address space).
1807
  * @param buf A buffer for the storage of the data.
1808
  * @param length The amount of bytes to be read.
1809
  * @throws InvalidFirmwareException if interface 1 is not supported.
1810
  * @throws UsbException if a communication error occurs.
1811
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
1812
  */
1813
    public void xmegaNvmRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1814
        checkCapability(CAPABILITY_XMEGA);
1815
 
1816
        try {
1817
            vendorRequest2( 0x4a, "XMEGA NVM Read", addr, addr>> 16, buf, length );
1818
        }
1819
        catch ( UsbException e ) {
1820
            throw new UsbException( dev().dev(), "NVM Read: " + xmegaStrError() );
1821
        }
1822
        try {
1823
            Thread.sleep( 3 );
1824
        }
1825
        catch ( InterruptedException e) {
1826
        }
1827
    }
1828
 
1829
 
1830
// ******* xmegaFlashRead ******************************************************
1831
/**
1832
  * Reads data from Flash memory of ATxmega.
1833
  * @param addr The source address relative to the Flash memory base.
1834
  * @param buf A buffer for the storage of the data.
1835
  * @param length The amount of bytes to be read.
1836
  * @throws InvalidFirmwareException if interface 1 is not supported.
1837
  * @throws UsbException If a communication error occurs.
1838
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
1839
  */
1840
    public void xmegaFlashRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1841
        checkCapability(CAPABILITY_XMEGA);
1842
 
1843
        try {
1844
            vendorRequest2( 0x4b, "XMEGA Flash Read", addr, addr>> 16, buf, length );
1845
        }
1846
        catch ( UsbException e ) {
1847
            throw new UsbException( dev().dev(), "XMEGA Flash Read: " + xmegaStrError() );
1848
        }
1849
        try {
1850
            Thread.sleep( 3 );
1851
        }
1852
        catch ( InterruptedException e) {
1853
        }
1854
    }
1855
 
1856
 
1857
 
1858
// ******* xmegaEepromRead *****************************************************
1859
/**
1860
  * Reads data from EEPROM memory of ATxmega.
1861
  * @param addr The source address relative to the EEPROM memory base.
1862
  * @param buf A buffer for the storage of the data.
1863
  * @param length The amount of bytes to be read.
1864
  * @throws InvalidFirmwareException if interface 1 is not supported.
1865
  * @throws UsbException If a communication error occurs.
1866
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
1867
  */
1868
    public void xmegaEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1869
        checkCapability(CAPABILITY_XMEGA);
1870
 
1871
        try {
1872
            vendorRequest2( 0x4c, "XMEGA EEPROM Read", addr, addr>> 16, buf, length );
1873
        }
1874
        catch ( UsbException e ) {
1875
            throw new UsbException( dev().dev(), "XMEGA EEPROM Read: " + xmegaStrError() );
1876
        }
1877
        try {
1878
            Thread.sleep( 3 );
1879
        }
1880
        catch ( InterruptedException e) {
1881
        }
1882
    }
1883
 
1884
 
1885
// ******* xmegaFuseRead *******************************************************
1886
/**
1887
  * Reads data from Fuse memory of ATxmega.
1888
  * @param addr The source address relative to the Fuse memory base.
1889
  * @param buf A buffer for the storage of the data.
1890
  * @param length The amount of bytes to be read.
1891
  * @throws InvalidFirmwareException if interface 1 is not supported.
1892
  * @throws UsbException If a communication error occurs.
1893
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
1894
  */
1895
    public void xmegaFuseRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1896
        checkCapability(CAPABILITY_XMEGA);
1897
 
1898
        try {
1899
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, addr>> 16, buf, length );
1900
        }
1901
        catch ( UsbException e ) {
1902
            throw new UsbException( dev().dev(), "XMEGA Fuse Read: " + xmegaStrError() );
1903
        }
1904
        try {
1905
            Thread.sleep( 3 );
1906
        }
1907
        catch ( InterruptedException e) {
1908
        }
1909
    }
1910
 
1911
/**
1912
  * Reads data one Fuse of ATxmega.
1913
  * @param addr The index of th Fuse.
1914
  * @return The Fuse read.
1915
  * @throws InvalidFirmwareException if interface 1 is not supported.
1916
  * @throws UsbException If a communication error occurs.
1917
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
1918
  */
1919
    public int xmegaFuseRead ( int addr ) throws UsbException, InvalidFirmwareException, CapabilityException {
1920
        byte[] buf = new byte[1];
1921
        checkCapability(CAPABILITY_XMEGA);
1922
        try {
1923
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, 0, buf, 1 );
1924
        }
1925
        catch ( UsbException e ) {
1926
            throw new UsbException( dev().dev(), "XMEGA Fuse Read: " + xmegaStrError() );
1927
        }
1928
        try {
1929
            Thread.sleep( 3 );
1930
        }
1931
        catch ( InterruptedException e) {
1932
        }
1933
        return buf[0] & 255;
1934
    }
1935
 
1936
 
1937
// ******* xmegaFlashPageWrite *************************************************
1938
/**
1939
  * Writes data to Flash memory of ATxmega.
1940
  * @param addr The source address relative to the Flash memory base.
1941
  * @param buf A buffer that stores the data.
1942
  * @throws InvalidFirmwareException if interface 1 is not supported.
1943
  * @throws UsbException if a communication error occurs.
1944
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
1945
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash page size.
1946
*/
1947
    public void xmegaFlashPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1948
        checkCapability(CAPABILITY_XMEGA);
1949
 
1950
        if ( buf.length < xmegaFlashPageSize() )
1951
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash page size: " + buf.length + " < " + xmegaFlashPageSize);
1952
 
1953
        try {
1954
            vendorCommand2( 0x4b, "XMEGA Flash page write", addr, addr>> 16, buf, xmegaFlashPageSize );
1955
        }
1956
        catch ( UsbException e ) {
1957
            throw new UsbException( dev().dev(), "XMEGA Flash page write: " + xmegaStrError() );
1958
        }
1959
        try {
1960
            Thread.sleep( 3 );
1961
        }
1962
        catch ( InterruptedException e) {
1963
        }
1964
    }
1965
 
1966
// ******* xmegaEpromPageWrite *************************************************
1967
/**
1968
  * Writes data to EEPROM memory of ATxmega.
1969
  * @param addr The source address relative to the EEPROM memory base.
1970
  * @param buf A buffer that stores the data.
1971
  * @throws InvalidFirmwareException if interface 1 is not supported.
1972
  * @throws UsbException if a communication error occurs.
1973
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
1974
  * @throws IndexOutOfBoundsException If the buffer is smaller than the EEPROM page size.
1975
*/
1976
    public void xmegaEepromPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1977
        checkCapability(CAPABILITY_XMEGA);
1978
 
1979
        if ( buf.length < xmegaEepromPageSize() )
1980
            throw new IndexOutOfBoundsException( "Buffer smaller than the EEPROM page size: " + buf.length + " < " + xmegaEepromPageSize);
1981
 
1982
        try {
1983
            vendorCommand2( 0x4c, "XMEGA EEPROM page write", addr, addr>> 16, buf, xmegaEepromPageSize );
1984
        }
1985
        catch ( UsbException e ) {
1986
            throw new UsbException( dev().dev(), "XMEGA EEPROM page write: " + xmegaStrError() );
1987
        }
1988
        try {
1989
            Thread.sleep( 3 );
1990
        }
1991
        catch ( InterruptedException e) {
1992
        }
1993
    }
1994
 
1995
// ******* xmegaFuseWrite ******************************************************
1996
/**
1997
  * Writes one Fuse of the ATxmega.
1998
  * @param addr The index of th Fuse.
1999
  * @param val The value of th Fuse.
2000
  * @throws InvalidFirmwareException if interface 1 is not supported.
2001
  * @throws UsbException if a communication error occurs.
2002
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2003
*/
2004
    public void xmegaFuseWrite ( int addr, int val ) throws UsbException, InvalidFirmwareException, CapabilityException {
2005
        checkCapability(CAPABILITY_XMEGA);
2006
 
2007
        try {
2008
            vendorCommand( 0x4d, "XMEGA Fuse write", val, addr);
2009
        }
2010
        catch ( UsbException e ) {
2011
            throw new UsbException( dev().dev(), "XMEGA Fuse write: " + xmegaStrError() );
2012
        }
2013
        try {
2014
            Thread.sleep( 3 );
2015
        }
2016
        catch ( InterruptedException e) {
2017
        }
2018
    }
2019
 
2020
// ******* xmegaIhxWrite *******************************************************
2021
/**
2022
  * Uploads data to NVM
2023
*/
2024
    private long xmegaIhxWrite ( boolean toFlash, IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2025
        final int maxTries = 3;  // maximum amount of tries
2026
        int pageSize = toFlash ? xmegaFlashPageSize() : xmegaEepromPageSize();
2027
        checkCapability(CAPABILITY_XMEGA);
2028
 
2029
        long t0 = new Date().getTime();
2030
 
2031
        byte buf1[] = new byte[pageSize];
2032
        byte buf2[] = new byte[pageSize];
2033
 
2034
        for (int i = 0; i<65536; i+=pageSize ) {
2035
 
2036
            boolean b = false;
2037
            boolean c = true;
2038
            for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
2039
                boolean d = (ihxFile.ihxData[i+j]>=0) && (ihxFile.ihxData[i+j]<=255);    // data vaild ?
2040
                b |= d;
2041
                c &= d;
2042
            }
2043
            if ( b ) {   // page contains data ==> has to be written
2044
//              System.out.print("Page " + i +": " );
2045
 
2046
                // read page, if firmware image contains undefined bytes
2047
                if ( ! c ) {
2048
//                  System.out.print("R");
2049
                    if ( toFlash )
2050
                        xmegaFlashRead ( i, buf1, pageSize );
2051
                    else
2052
                        xmegaEepromRead ( i, buf1, pageSize );
2053
                }
2054
 
2055
                // prepare the page buffer
2056
                for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
2057
                    if ( (ihxFile.ihxData[i+j]>=0) && (ihxFile.ihxData[i+j]<=255) )
2058
                        buf1[j]= (byte) ihxFile.ihxData[i+j];
2059
                }
2060
 
2061
                for ( int k=1; b ; k++ ) {
2062
                    // write the page
2063
//                  System.out.print("W");
2064
                    if ( toFlash )
2065
                        xmegaFlashPageWrite ( i, buf1 );
2066
                    else
2067
                        xmegaEepromPageWrite ( i, buf1 );
2068
 
2069
                    // verify it
2070
//                  System.out.print("V");
2071
                    if ( toFlash )
2072
                        xmegaFlashRead ( i, buf2, pageSize );
2073
                    else
2074
                        xmegaEepromRead ( i, buf2, pageSize );
2075
                    b=false;
2076
                    for ( int j=0; (j < pageSize) && (! b ); j++ ) {
2077
                        b |= buf1[j] != buf2[j];
2078
                    }
2079
                    if ( b ) {
2080
                        if ( k<maxTries ) {
2081
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page" + i + " failed (try " + k +")" );
2082
                        }
2083
                        else {
2084
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page " + i + " failed");
2085
                        }
2086
                    }
2087
                    b = false;
2088
 
2089
//                  System.out.println();
2090
                }
2091
            }
2092
        }
2093
 
2094
        return new Date().getTime() - t0;
2095
    }
2096
 
2097
 
2098
 
2099
// ******* xmegaWriteFirmware **************************************************
2100
/**
2101
  * Uploads firmware to the flash memory
2102
  * @param ihxFile The firmware / data image.
2103
  * @throws InvalidFirmwareException if interface 1 is not supported.
2104
  * @throws UsbException if a communication error occurs.
2105
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2106
  * @throws FirmwareUploadException if the verification fails.
2107
  * @return the upload time in ms.
2108
*/
2109
    public long xmegaWriteFirmware ( IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2110
        return xmegaIhxWrite( true, ihxFile);
2111
    }
2112
 
2113
 
2114
// ******* xmegaWriteEeprom ****************************************************
2115
/**
2116
  * Uploads data to the EEPROM memory
2117
  * @param ihxFile The firmware / data image.
2118
  * @throws InvalidFirmwareException if interface 1 is not supported.
2119
  * @throws UsbException if a communication error occurs.
2120
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2121
  * @throws FirmwareUploadException if the verification fails.
2122
  * @return the upload time in ms.
2123
*/
2124
    public long xmegaWriteEeprom ( IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2125
        return xmegaIhxWrite( false, ihxFile);
2126
    }
2127
 
2128
 
2129 2 ZTEX
// ******* toString ************************************************************
2130
/**
2131
  * Returns a lot of useful information about the corresponding device.
2132
  * @return a lot of useful information about the corresponding device.
2133
  */
2134
    public String toString () {
2135
        String str = dev().toString();
2136
        try {
2137
            str += "\n   " + getFpgaConfigurationStr();
2138
        }
2139
        catch ( Exception e ) {
2140
        }
2141
        return str;
2142
    }
2143
 
2144
// ******* capabilityInfo ******************************************************
2145
/**
2146
  * Creates a String with capability information.
2147
  * @param pf A separator between the single capabilities, e.g. ", "
2148
  * @return a string of the supported capabilities.
2149
  */
2150
    public String capabilityInfo ( String pf ) {
2151
        String str = "";
2152
        for ( int i=0; i<6; i++ )
2153
            for (int j=0; j<8; j++ )
2154
                if ( dev().interfaceCapabilities(i,j) ) {
2155
                    if ( ! str.equals("") )
2156
                        str+=pf;
2157
                    if (i*8+j < capabilityStrings.length)
2158
                        str+=capabilityStrings[i*8+j];
2159
                    else
2160
                        str+=i+"."+j;
2161
                }
2162
        return str;
2163
    }
2164 5 ZTEX
// ******* configureFpgaHS *****************************************************
2165
//  returns configuration time in ms
2166
/**
2167
  * Upload a Bitstream to the FPGA using high speed mode.
2168
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
2169
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2170
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2171
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2172
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2173
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2174
  * @throws InvalidFirmwareException if interface 1 is not supported.
2175
  * @throws UsbException if a communication error occurs.
2176
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2177
  */
2178
    public long configureFpgaHS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2179
        final int transactionBytes = 65536;
2180
        long t0 = 0;
2181
        byte[] settings = new byte[2];
2182
        boolean releaseIF;
2183
 
2184
        checkCapability(CAPABILITY_HS_FPGA);
2185
        vendorRequest2(0x33, "getHSFpgaSettings", settings, 2);
2186
 
2187
        if ( !force && getFpgaConfiguration() )
2188
            throw new AlreadyConfiguredException();
2189
 
2190
        releaseIF = ! getInterfaceClaimed(settings[1] & 255);
2191
//      System.out.println("EP "+ settings[0] + "    IF "+settings[1]+ "   claim " + releaseIF);
2192
 
2193
// read the Bitstream file      
2194
        byte[][] buffer = new byte[16*1024*1024/transactionBytes][];
2195
        int size = 0;
2196
        try {
2197
            InputStream inputStream = JInputStream.getInputStream( fwFileName );
2198
            int j = transactionBytes;
2199
            for ( int i=0; i<buffer.length && j==transactionBytes; i++ ) {
2200
                buffer[i] = new byte[transactionBytes];
2201
                int k;
2202
                j = 0;
2203
                do {
2204
                    k = inputStream.read( buffer[i], j, transactionBytes-j );
2205
                    if ( k < 0 )
2206
                        k = 0;
2207
                    j += k;
2208
                }
2209
                while ( j<transactionBytes && k>0 );
2210
                size += j;
2211
            }
2212
 
2213
            try {
2214
                inputStream.close();
2215
            }
2216
            catch ( Exception e ) {
2217
                System.err.println( "Warning: Error closing file " + fwFileName + ": " + e.getLocalizedMessage() );
2218
            }
2219
        }
2220
        catch (IOException e) {
2221
            throw new BitstreamReadException(e.getLocalizedMessage());
2222
        }
2223
 
2224
        if ( size < 64 )
2225
            throw new BitstreamReadException("Invalid file size: " + size );
2226
 
2227
// detect bitstream bit order and swap bits if necessary 
2228
        if ( bs<0 || bs>1 )
2229
            bs = detectBitstreamBitOrder ( buffer[0] );
2230
        if ( bs == 1 )
2231
            swapBits(buffer,size);
2232
 
2233
 
2234
// claim interface if required
2235
        if ( releaseIF ) claimInterface( settings[1] & 255 );
2236
 
2237
//      System.out.println(size & 127);
2238
 
2239
// upload the Bitstream file    
2240
        for ( int tries=1; tries>0; tries-- ) {
2241
 
2242
            vendorCommand(0x34, "initHSFPGAConfiguration" );
2243
 
2244
            try {
2245
                t0 = -new Date().getTime();
2246
 
2247
                for ( int i=0; i<buffer.length && i*transactionBytes < size; i++ ) {
2248
                    int j = size-i*transactionBytes;
2249
                    if (j>transactionBytes)
2250
                        j = transactionBytes;
2251
 
2252
                    int l = LibusbJava.usb_bulk_write(handle(), settings[0] & 255, buffer[i], j, 1000);
2253
                    if ( l < 0 )
2254
                        throw new UsbException("Error sending Bitstream: " + LibusbJava.usb_strerror());
2255
                    else if ( l != j )
2256
                        throw new UsbException("Error sending Bitstream: Sent " + l +" of " + j + " bytes");
2257
                }
2258
 
2259
                vendorCommand(0x35, "finishHSFPGAConfiguration" );
2260
                t0 += new Date().getTime();
2261
 
2262
                getFpgaState();
2263
//              System.err.println("fpgaConfigred=" + fpgaConfigured +"  fpgaInitB="+fpgaInitB + "  time=" + t0);
2264
                if ( ! fpgaConfigured ) {
2265
                    throw new BitstreamUploadException( "FPGA configuration failed: DONE pin does not go high" );
2266
                }
2267
 
2268
                tries = 0;
2269
            }
2270
            catch ( BitstreamUploadException e ) {
2271
                if ( tries>1 )
2272
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
2273
                else
2274
                    throw e;
2275
            }
2276
        }
2277
 
2278
        if ( releaseIF ) releaseInterface( settings[1] & 255 );
2279
 
2280
        try {
2281
            Thread.sleep( 200 );
2282
        }
2283
        catch ( InterruptedException e) {
2284
        }
2285
 
2286
        return t0;
2287
    }
2288
 
2289
// ******* configureFpga *****************************************************
2290
//  returns configuration time in ms
2291
/**
2292
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
2293
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
2294
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2295
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2296
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2297
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2298
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2299
  * @throws InvalidFirmwareException if interface 1 is not supported.
2300
  * @throws UsbException if a communication error occurs.
2301
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2302
  */
2303
    public long configureFpga ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2304
        try {
2305
            return configureFpgaHS( fwFileName, force, bs );
2306
        }
2307
        catch ( CapabilityException e ) {
2308
            return configureFpgaLS( fwFileName, force, bs );
2309
        }
2310
        catch ( UsbException e ) {
2311
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2312
            return configureFpgaLS( fwFileName, force, bs );
2313
        }
2314
        catch ( BitstreamUploadException e ) {
2315
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2316
            return configureFpgaLS( fwFileName, force, bs );
2317
        }
2318
    }
2319
 
2320
/**
2321
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
2322
  * @param fwFileName The file name of the Bitstream. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
2323
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2324
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2325
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2326
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2327
  * @throws InvalidFirmwareException if interface 1 is not supported.
2328
  * @throws UsbException if a communication error occurs.
2329
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2330
  */
2331
    public long configureFpga ( String fwFileName, boolean force ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2332
        return configureFpga(fwFileName, force, -1);
2333
    }
2334
 
2335
// ******* macEepromWrite ******************************************************
2336
/**
2337
  * Writes data to the MAC EEPROM.
2338
  * @param addr The destination address of the MAC EEPROM.
2339
  * @param buf The data.
2340
  * @param length The amount of bytes to be sent.
2341
  * @throws InvalidFirmwareException if interface 1 is not supported.
2342
  * @throws UsbException if a communication error occurs.
2343
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2344
  */
2345
    public void macEepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2346
        checkCapability(CAPABILITY_MAC_EEPROM);
2347
        byte[] buf2 = new byte[8];
2348
        int ptr = 0;
2349
        while (length>0 ) {
2350
            int i = Math.min( 8 - (addr & 7), length );
2351
            for ( int j=0; j<i; j++ )
2352
                buf2[j] = buf[ptr+j];
2353
            vendorCommand2( 0x3C, "MAC EEPROM Write", addr, 0, buf2, i );
2354
            try {
2355
                Thread.sleep( 10 );
2356
            }
2357
            catch ( InterruptedException e) {
2358
            }
2359
            addr+=i;
2360
            length-=i;
2361
            ptr += i;
2362
        }
2363
    }
2364
 
2365
// ******* macEepromRead *******************************************************
2366
/**
2367
  * Reads data from the MAC EEPROM.
2368
  * @param addr The source address of the MAC EEPROM.
2369
  * @param buf A buffer for the storage of the data.
2370
  * @param length The amount of bytes to be read.
2371
  * @throws InvalidFirmwareException if interface 1 is not supported.
2372
  * @throws UsbException if a communication error occurs.
2373
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2374
  */
2375
    public void macEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2376
        checkCapability(CAPABILITY_MAC_EEPROM);
2377
        vendorRequest2( 0x3B, "MAC EEPROM Read", addr, 0, buf, length );
2378
        try {
2379
            Thread.sleep( 10 );
2380
        }
2381
        catch ( InterruptedException e) {
2382
        }
2383
    }
2384
 
2385
// ******* macEepromState ******************************************************
2386
// returns true if MAC EEPROM is ready
2387
/**
2388
  * Reads the current MAC EEPROM status.
2389
  * @throws InvalidFirmwareException if interface 1 is not supported.
2390
  * @throws UsbException if a communication error occurs.
2391
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2392
  * @return true if MAC EEPROM is ready.
2393
  */
2394
    public boolean macEepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2395
        byte[] buf = new byte[1];
2396
        checkCapability(CAPABILITY_MAC_EEPROM);
2397
        vendorRequest2(0x3D, "MAC EEPROM State", 0, 0, buf, 1);
2398
        return buf[0] == 0;
2399
    }
2400
 
2401
// ******* macRead *************************************************************
2402
/**
2403
  * Reads MAC address from MAC EEPROM.
2404
  * @param buf A buffer with a minimum size of 6 bytes.
2405
  * @throws InvalidFirmwareException if interface 1 is not supported.
2406
  * @throws UsbException if a communication error occurs.
2407
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2408
  * @throws IndexOutOfBoundsException If the buffer is smaller than 6 bytes.
2409
  */
2410
    public void macRead ( byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2411
        if ( buf.length < 6 )
2412
        throw new IndexOutOfBoundsException( "macRead: Buffer smaller than 6 Bytes" );
2413
        macEepromRead(250, buf, 6);
2414
    }
2415
 
2416 2 ZTEX
}
2417
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.