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

Subversion Repositories usb_fpga_2_16

[/] [usb_fpga_2_16/] [trunk/] [java/] [ztex/] [Ztex1v1.java] - Blame information for rev 3

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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