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

Subversion Repositories usb_fpga_2_13

[/] [usb_fpga_2_13/] [trunk/] [java/] [ztex/] [Ztex1v1.java] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 ZTEX
/*!
2
   Java host software API of ZTEX SDK
3
   Copyright (C) 2009-2014 ZTEX GmbH.
4
   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
// ******* detectBitstreamStart ************************************************
879
    private int detectBitstreamStart ( byte[] buf ) {
880
        int l=0;
881
        for ( int i=0; i<buf.length-3; i++ ) {
882
            if ( (l>=4) && ((buf[i+1] & 255)==0x99) && ((buf[i+3] & 255)==0x66) ) {
883
                if ( ((buf[i] & 255)==0xaa) && ((buf[i+2] & 255)==0x55) )
884
                    return i-l;
885
                if ( ((buf[i] & 255)==0x55) && ((buf[i+2] & 255)==0xaa) )
886
                    return i-l;
887
            }
888
            l = buf[i]==-1 ? l+1 : 0;
889
        }
890
        System.err.println("Warning: Unable to determine start of raw bitstream");
891
        return 0;
892
    }
893
 
894
// ******* swapBits ************************************************************
895
    private void swapBits ( byte[][] buf, int size ) {
896
        int j=0, k=0;
897
        for (int i=0; i<size; i++ ) {
898
            while ( k >= buf[j].length ) {
899
                j++;
900
                k=0;
901
            }
902
            byte b = buf[j][k];
903
            buf[j][k] = (byte) ( ((b & 128) >> 7) |
904
                                 ((b &  64) >> 5) |
905
                                 ((b &  32) >> 3) |
906
                                 ((b &  16) >> 1) |
907
                                 ((b &   8) << 1) |
908
                                 ((b &   4) << 3) |
909
                                 ((b &   2) << 5) |
910
                                 ((b &   1) << 7) );
911
            k++;
912
        }
913
    }
914
 
915
// ******* configureFpgaLS *****************************************************
916
//  returns configuration time in ms
917
/**
918
  * Upload a Bitstream to the FPGA using low speed mode.
919
  * @param inputStream for reading the Bitstream.
920
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
921
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
922
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
923
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
924
  * @throws AlreadyConfiguredException if the FPGA is already configured.
925
  * @throws InvalidFirmwareException if interface 1 is not supported.
926
  * @throws UsbException if a communication error occurs.
927
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
928
  */
929
    public long configureFpgaLS ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
930
        final int transactionBytes = certainWorkarounds ? 256 : 2048;
931
        long t0 = 0;
932
 
933
        checkCapability(CAPABILITY_FPGA);
934
 
935
        if ( !force && getFpgaConfiguration() )
936
            throw new AlreadyConfiguredException();
937
 
938
// read the Bitstream file      
939
        byte[][] buffer = new byte[16*1024*1024/transactionBytes][];
940
        int size = 0;
941
        try {
942
            int j = transactionBytes;
943
            for ( int i=0; i<buffer.length && j==transactionBytes; i++ ) {
944
                buffer[i] = new byte[transactionBytes];
945
                int k;
946
                j = 0;
947
                do {
948
                    k = inputStream.read( buffer[i], j, transactionBytes-j );
949
                    if ( k < 0 )
950
                        k = 0;
951
                    j += k;
952
                }
953
                while ( j<transactionBytes && k>0 );
954
 
955
                if ( j < transactionBytes && j % 64 == 0 )       // ensures size % 64 != 0
956
                    j+=1;
957
                size += j;
958
            }
959
 
960
            try {
961
                inputStream.close();
962
            }
963
            catch ( Exception e ) {
964
            }
965
        }
966
        catch (IOException e) {
967
            throw new BitstreamReadException(e.getLocalizedMessage());
968
        }
969
        if ( size < 64 || size % 64 == 0 )
970
            throw new BitstreamReadException("Invalid file size: " + size );
971
 
972
// detect bitstream bit order and swap bits if necessary 
973
        if ( bs<0 || bs>1 )
974
            bs = detectBitstreamBitOrder ( buffer[0] );
975
        if ( bs == 1 )
976
            swapBits(buffer,size);
977
 
978
// upload the Bitstream file    
979
        for ( int tries=10; tries>0; tries-- ) {
980
 
981
            resetFpga();
982
 
983
            try {
984
                t0 = -new Date().getTime();
985
                int cs = 0;
986
                bs = 0;
987
 
988
                for ( int i=0; i<buffer.length && i*transactionBytes < size; i++ ) {
989
                    int j = size-i*transactionBytes;
990
                    if (j>transactionBytes)
991
                        j = transactionBytes;
992
                    vendorCommand2(0x32, "sendFpgaData", 0,0, buffer[i], j);
993
 
994
                    bs+=j;
995
                    for ( int k=0; k<buffer[i].length; k++ )
996
                        cs = ( cs + (buffer[i][k] & 0xff) ) & 0xff;
997
                }
998
 
999
                getFpgaState();
1000
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+bs+")   fpgaChecksum="+fpgaChecksum + " ("+cs+")   fpgaInitB="+fpgaInitB );
1001
                if ( ! fpgaConfigured ) {
1002
                    throw new BitstreamUploadException( "FPGA configuration failed: DONE pin does not go high (size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes got lost;  checksum="
1003
                        + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB +")" );
1004
                }
1005
                if ( enableExtraFpgaConfigurationChecks ) {
1006
                    if ( fpgaBytes!=0 && fpgaBytes!=bs )
1007
                        System.err.println("Warning: Possible FPGA configuration data loss: " + (bs - fpgaBytes) + " bytes got lost");
1008
                    if ( fpgaInitB!=222 )
1009
                        System.err.println("Warning: Possible Bitstream CRC error: INIT_B_HIST=" + fpgaInitB );
1010
                }
1011
//              System.out.println( "FPGA configuration: size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes got lost;  checksum=" + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB );
1012
 
1013
                tries = 0;
1014
                t0 += new Date().getTime();
1015
 
1016
            }
1017
            catch ( BitstreamUploadException e ) {
1018
                if ( tries>1 )
1019
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1020
                else
1021
                    throw e;
1022
            }
1023
        }
1024
 
1025
        try {
1026
            Thread.sleep( 100 );
1027
        }
1028
        catch ( InterruptedException e) {
1029
        }
1030
 
1031
        return t0;
1032
    }
1033
 
1034
 
1035
/**
1036
  * Upload a Bitstream to the FPGA using low speed mode.
1037
  * @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).
1038
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
1039
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1040
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1041
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
1042
  * @throws AlreadyConfiguredException if the FPGA is already configured.
1043
  * @throws InvalidFirmwareException if interface 1 is not supported.
1044
  * @throws UsbException if a communication error occurs.
1045
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1046
  */
1047
    public long configureFpgaLS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
1048
        try {
1049
            return configureFpgaLS( JInputStream.getInputStream( fwFileName ), force, bs );
1050
        }
1051
        catch (IOException e) {
1052
            throw new BitstreamReadException(e.getLocalizedMessage());
1053
        }
1054
    }
1055
 
1056
// ******* eepromState *********************************************************
1057
// returns true if EEPROM is ready
1058
/**
1059
  * Reads the current EEPROM status.
1060
  * This method also sets the varibles {@link #eepromBytes} and {@link #eepromChecksum}.
1061
  * @throws InvalidFirmwareException if interface 1 is not supported.
1062
  * @throws UsbException if a communication error occurs.
1063
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1064
  * @return true if EEPROM is ready.
1065
  */
1066
    public boolean eepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1067
        byte[] buf = new byte[4];
1068
        checkCapability(CAPABILITY_EEPROM);
1069
        vendorRequest2(0x3A, "EEPROM State", 0, 0, buf, 4);
1070
        eepromBytes = (buf[0] & 255) | (buf[1] & 255)<<8;
1071
        eepromChecksum = buf[2] & 255;
1072
        return buf[3] == 0;
1073
    }
1074
 
1075
// ******* eepromWrite *********************************************************
1076
/**
1077
  * Writes data to the EEPROM.
1078
  * @param addr The destination address of the EEPROM.
1079
  * @param buf The data.
1080
  * @param length The amount of bytes to be sent.
1081
  * @throws InvalidFirmwareException if interface 1 is not supported.
1082
  * @throws UsbException if a communication error occurs.
1083
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1084
  */
1085
    public void eepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1086
        checkCapability(CAPABILITY_EEPROM);
1087
        if ( (addr & 63) != 0 ) {
1088
            int i = Math.min(length, 64-(addr & 63));
1089
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, i );
1090
            try {
1091
                Thread.sleep( 10 );
1092
            }
1093
            catch ( InterruptedException e) {
1094
            }
1095
            addr+=i;
1096
            length-=i;
1097
            if ( length > 0 ) {
1098
                byte[] buf2 = new byte[length];
1099
                for (int j=0; j<length; j++ )
1100
                    buf2[j] = buf[i+j];
1101
                vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf2, length );
1102
            }
1103
        }
1104
        else {
1105
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, length );
1106
        }
1107
 
1108
        try {
1109
                Thread.sleep( 10 );
1110
        }
1111
            catch ( InterruptedException e) {
1112
        }
1113
    }
1114
 
1115
// ******* eepromRead **********************************************************
1116
/**
1117
  * Reads data from the EEPROM.
1118
  * @param addr The source address of the EEPROM.
1119
  * @param buf A buffer for the storage of the data.
1120
  * @param length The amount of bytes to be read.
1121
  * @throws InvalidFirmwareException if interface 1 is not supported.
1122
  * @throws UsbException if a communication error occurs.
1123
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1124
  */
1125
    public void eepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1126
        checkCapability(CAPABILITY_EEPROM);
1127
        vendorRequest2( 0x38, "EEPROM Read", addr, 0, buf, length );             // sometimes a little bit slow
1128
        try {
1129
            Thread.sleep( 10 );
1130
        }
1131
        catch ( InterruptedException e) {
1132
        }
1133
    }
1134
 
1135
// ******* eepromUpload ********************************************************
1136
//  returns upload time in ms
1137
/**
1138
  * Upload the firmware to the EEPROM.
1139
  * In order to start the uploaded firmware the device must be reset.
1140
  * @param ihxFile The firmware image.
1141
  * @param force Skips the compatibility check if true.
1142
  * @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.)
1143
  * @throws InvalidFirmwareException if interface 1 is not supported.
1144
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1145
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1146
  */
1147
    public long eepromUpload ( ZtexIhxFile1 ihxFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1148
        final int pagesMax = 256;
1149
        final int pageSize = 256;
1150
        int pages = 0;
1151
        byte[][] buffer = new byte[pagesMax][];
1152
 
1153
        checkCapability(CAPABILITY_EEPROM);
1154
 
1155
//      ihxFile.dataInfo(System.out);
1156
//      System.out.println(ihxFile);
1157
 
1158
// check for compatibility
1159
        if ( ! force && dev().valid() ) {
1160
            if ( ihxFile.interfaceVersion() != 1 )
1161
                throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ihxFile.interfaceVersion() );
1162
 
1163
            if ( ! dev().compatible ( ihxFile.productId(0), ihxFile.productId(1), ihxFile.productId(2), ihxFile.productId(3) ) )
1164
                throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev().productId())
1165
                    + "  Ihx File: " + ZtexDevice1.byteArrayString(ihxFile.productId()) );
1166
        }
1167
 
1168
        Usb_Device_Descriptor dd = dev().dev().getDescriptor();
1169
        int vid = dd.getIdVendor() & 65535;
1170
        int pid = dd.getIdProduct() & 65535;
1171
 
1172
        buffer[0] = new byte[pageSize];
1173
        buffer[0][0] = (byte) 0xc2;
1174
        buffer[0][1] = (byte) (vid & 255);
1175
        buffer[0][2] = (byte) ((vid >> 8) & 255);
1176
        buffer[0][3] = (byte) (pid & 255);
1177
        buffer[0][4] = (byte) ((pid >> 8) & 255);
1178
        buffer[0][5] = 0;
1179
        buffer[0][6] = 0;
1180
        buffer[0][7] = 0;
1181
 
1182
        int ptr = 8, i = 0;
1183
 
1184
        while ( i < ihxFile.ihxData.length ) {
1185
            if ( ihxFile.ihxData[i]>=0 && ihxFile.ihxData[i]<256 ) {                     // new data block
1186
                int j = 1;
1187
                while ( i+j<ihxFile.ihxData.length && ihxFile.ihxData[i+j]>=0 && ihxFile.ihxData[i+j]<256 )
1188
                    j++;
1189
 
1190
                for (int k=ptr/pageSize + 1; k < (ptr+j+9)/pageSize + 1; k++ )  // also considers 5 bytes for the last data block
1191
                    buffer[k] = new byte[pageSize];
1192
 
1193
                buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) ((j >> 8) & 255);
1194
                buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) (j & 255);                // length
1195
                buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((i >> 8) & 255);
1196
                buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) (i & 255);                // address
1197
                ptr+=4;
1198
                for ( int k=0; k<j; k++ )                                        // data
1199
                    buffer[(ptr+k)/pageSize][(ptr+k) % pageSize] = (byte) ihxFile.ihxData[i+k];
1200
                ptr+=j;
1201
                i+=j;
1202
            }
1203
            else {
1204
                i+=1;
1205
            }
1206
        }
1207
 
1208
        buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) 0x80;               // last data block
1209
        buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) 0x01;
1210
        buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) 0xe6;
1211
        buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) 0x00;
1212
        buffer[(ptr+3)/pageSize][(ptr+4) % pageSize] = (byte) 0x00;
1213
        ptr+=5;
1214
 
1215
 
1216
        long t0 = new Date().getTime();
1217
        byte[] rbuf = new byte[pageSize];
1218
 
1219
        for ( i=(ptr-1)/pageSize; i>=0; i-- ) {
1220
 
1221
            int k = (i+1)*pageSize < ptr ? pageSize : ptr-i*pageSize;
1222
            int cs = 0;
1223
            for (int j=0; j<k; j++ ) {
1224
                cs = ( cs + (buffer[i][j] & 255) ) & 255;
1225
            }
1226
 
1227
            for ( int tries=3; tries>0; tries-- ) {
1228
                try {
1229
                    eepromWrite(i*pageSize, buffer[i], k);
1230
                    eepromState();
1231
                    if ( eepromBytes!=k )
1232
                        throw new FirmwareUploadException("Error writing data to EEPROM: Wrote " + eepromBytes + " bytes instead of "  + k + " bytes" );
1233
                    if ( eepromChecksum!=cs )
1234
                        throw new FirmwareUploadException("Error writing data to EEPROM: Checksum error");
1235
 
1236
                    eepromRead(i*pageSize, rbuf, k);
1237
                    for (int j=0; j<k; j++ ) {
1238
                        if ( rbuf[j] != buffer[i][j] )
1239
                            throw new FirmwareUploadException("Error writing data to EEPROM: Verification failed");
1240
                    }
1241
                    tries = 0;
1242
                }
1243
                catch ( Exception e ) {
1244
                    if ( tries > 1 ) {
1245
                        System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1246
                    }
1247
                    else {
1248
                        throw new FirmwareUploadException(e.getLocalizedMessage());
1249
                    }
1250
                }
1251
            }
1252
        }
1253
 
1254
        return new Date().getTime() - t0;
1255
    }
1256
 
1257
//  returns upload time in ms
1258
/**
1259
  * Upload the firmware to the EEPROM.
1260
  * In order to start the uploaded firmware the device must be reset.
1261
  * @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).
1262
  * @param force Skips the compatibility check if true.
1263
  * @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.)
1264
  * @throws InvalidFirmwareException if interface 1 is not supported.
1265
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1266
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1267
  */
1268
    public long eepromUpload ( String ihxFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1269
        checkCapability(CAPABILITY_EEPROM);
1270
 
1271
// load the ihx file
1272
        ZtexIhxFile1 ihxFile;
1273
        try {
1274
            ihxFile = new ZtexIhxFile1( ihxFileName );
1275
        }
1276
        catch ( IOException e ) {
1277
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1278
        }
1279
        catch ( IhxFileDamagedException e ) {
1280
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1281
        }
1282
 
1283
        return eepromUpload( ihxFile, force );
1284
    }
1285
 
1286
 
1287
// ******* eepromDisable ********************************************************
1288
/**
1289
  * Disables the firmware stored in the EEPROM.
1290
  * This is achived by writing a "0" to the address 0 of the EEPROM.
1291
  * @throws InvalidFirmwareException if interface 1 is not supported.
1292
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1293
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
1294
  */
1295
    public void eepromDisable ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1296
        byte[] buf = { 0 };
1297
 
1298
        for ( int tries=3; tries>0; tries-- ) {
1299
            try {
1300
                eepromWrite(0, buf, 1);
1301
 
1302
                eepromRead(0, buf, 1);
1303
                if ( buf[0] != 0 )
1304
                    throw new FirmwareUploadException("Error disabling EEPROM firmware: Verification failed");
1305
                tries = 0;
1306
 
1307
            }
1308
            catch ( Exception e ) {
1309
                if ( tries > 1 ) {
1310
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1311
                }
1312
                else {
1313
                    throw new FirmwareUploadException(e.getLocalizedMessage());
1314
                }
1315
            }
1316
        }
1317
    }
1318
 
1319
// ******* flashStrError *******************************************************
1320
/**
1321
  * Converts a given error code into a String.
1322
  * @param errNum The error code.
1323
  * @return an error message.
1324
  */
1325
    public static String flashStrError ( int errNum ) {
1326
        switch ( errNum ) {
1327
            case FLASH_EC_NO_ERROR:
1328
                return "USB error: " + LibusbJava.usb_strerror();
1329
            case FLASH_EC_CMD_ERROR:
1330
                return "Command error";
1331
            case FLASH_EC_TIMEOUT:
1332
                return "Timeout error";
1333
            case FLASH_EC_BUSY:
1334
                return "Busy";
1335
            case FLASH_EC_PENDING:
1336
                return "Another operation is pending";
1337
            case FLASH_EC_READ_ERROR:
1338
                return "Read error";
1339
            case FLASH_EC_WRITE_ERROR:
1340
                return "Write error";
1341
            case FLASH_EC_NOTSUPPORTED:
1342
                return "Not supported";
1343
        }
1344
        return "Error " + errNum;
1345
    }
1346
 
1347
/**
1348
  * Gets the last Flash error from the device.
1349
  * @return an error message.
1350
  */
1351
    public String flashStrError ( ) {
1352
        try {
1353
            return flashStrError( getFlashEC() );
1354
        }
1355
        catch ( Exception e ) {
1356
            return "Unknown error (Error receiving errorcode: "+e.getLocalizedMessage() +")";
1357
        }
1358
    }
1359
 
1360
// ******* flashState **********************************************************
1361
/**
1362
  * Reads the the Flash memory status and information.
1363
  * This method also sets the variables {@link #flashEnabled()}, {@link #flashSectorSize()} and {@link #flashSectors()}.
1364
  * @return true if Flash memory is installed.
1365
  * @throws InvalidFirmwareException if interface 1 is not supported.
1366
  * @throws UsbException if a communication error occurs.
1367
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1368
  */
1369
    public boolean flashState () throws UsbException, InvalidFirmwareException, CapabilityException {
1370
        byte[] buf = new byte[8];
1371
        checkCapability(CAPABILITY_FLASH);
1372
 
1373
        // device may be busy due to initialization, we try it up to up to 4s
1374
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1375
        flashEC = buf[7] & 255;
1376
        int tries=20;
1377
        while ( flashEC==FLASH_EC_BUSY && tries>0 )
1378
        {
1379
            try {
1380
                Thread.sleep( 200 );
1381
            }
1382
            catch ( InterruptedException e) {
1383
            }
1384
            tries-=1;
1385
            vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1386
            flashEC = buf[7] & 255;
1387
        }
1388
        flashEnabled = buf[0] & 255;
1389
        flashSectorSize = flashEnabled == 1 ? ((buf[2] & 255) << 8) | (buf[1] & 255) : 0;
1390
        if ( (flashSectorSize & 0x8000) != 0 )
1391
            flashSectorSize = 1 << (flashSectorSize & 0x7fff);
1392
        flashSectors = flashEnabled == 1 ? ((buf[6] & 255) << 24) | ((buf[5] & 255) << 16) | ((buf[4] & 255) << 8) | (buf[3] & 255) : 0;
1393
        return flashEnabled == 1;
1394
    }
1395
 
1396
// ******* getFlashEC **********************************************************
1397
// reads the current error code
1398
/**
1399
  * Gets the last Flash error from the device.
1400
  * @return The last error code.
1401
  * @throws InvalidFirmwareException if interface 1 is not supported.
1402
  * @throws UsbException if a communication error occurs.
1403
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1404
  */
1405
    public int getFlashEC () throws UsbException, InvalidFirmwareException, CapabilityException {
1406
        byte[] buf = new byte[8];
1407
        checkCapability(CAPABILITY_FLASH);
1408
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1409
        flashEC = buf[7] & 255;
1410
        return flashEC;
1411
    }
1412
 
1413
 
1414
// ******* flashReadSector ****************************************************
1415
// read a integer number of sectors
1416
/**
1417
  * Reads a integer number of sectors from the Flash.
1418
  * @param sector The number of the first sector to be read.
1419
  * @param num The number of sectors to be read.
1420
  * @param buf A buffer for the storage of the data.
1421
  * @throws InvalidFirmwareException if interface 1 is not supported.
1422
  * @throws UsbException if a communication error occurs.
1423
  * @throws CapabilityException if Flash memory access is not possible.
1424
  * @throws IndexOutOfBoundsException If the buffer is to small.
1425
  */
1426
    public void flashReadSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1427
        if ( num<1 ) return;
1428
 
1429
        if ( buf.length < flashSectorSize() )
1430
            throw new IndexOutOfBoundsException( "Buffer is to small: " + buf.length + " < " + (num*flashSectorSize()) );
1431
 
1432
        checkCapability(CAPABILITY_FLASH);
1433
        if ( ! flashEnabled() )
1434
            throw new CapabilityException(this, "No Flash memory installed or");
1435
 
1436
        try {
1437
            if ( flashSectorSize()>2048 ) {
1438
                byte[] buf2 = new byte[2048];
1439
                int iz = (flashSectorSize-1) >> 11;
1440
                for (int sn=0; sn<num; sn++ ) {
1441
                    for (int i=0; i<iz; i++) {
1442
//                      System.out.println("r: "+i);
1443
                        vendorRequest2( 0x41, "Flash Read", sector, i==0 ? 0 : 256, buf2, 2048 );
1444
                        System.arraycopy(buf2,0, buf, sn*flashSectorSize + i*2048, 2048);
1445
                    }
1446
                    int len = flashSectorSize-iz*2048;
1447
                    vendorRequest2( 0x41, "Flash Read", sector, 512, buf2,  len);
1448
                    System.arraycopy(buf2,0, buf, sn*flashSectorSize + iz*2048, len);
1449
                }
1450
            }
1451
            else {
1452
                if ( flashSectorSize*num>2048 ) System.err.println("Warning: flashReadSector: Transaction size " + flashSectorSize*num + " may be too large");
1453
                vendorRequest2( 0x41, "Flash Read", sector, sector >> 16, buf, flashSectorSize*num );
1454
            }
1455
        }
1456
        catch ( UsbException e ) {
1457
            throw new UsbException( dev().dev(), "Flash Read: " + flashStrError() );
1458
        }
1459
    }
1460
 
1461
// read one sector
1462
/**
1463
  * Reads one sector from the Flash.
1464
  * @param sector The sector number to be read.
1465
  * @param buf A buffer for the storage of the data.
1466
  * @throws InvalidFirmwareException if interface 1 is not supported.
1467
  * @throws UsbException if a communication error occurs.
1468
  * @throws CapabilityException if Flash memory access is not possible.
1469
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
1470
  */
1471
    public void flashReadSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1472
        flashReadSector ( sector, 1, buf );
1473
    }
1474
 
1475
 
1476
// ******* flashWriteSector ***************************************************
1477
// write integer number of sectors
1478
/**
1479
  * Writes a integer number of sectors to the Flash.
1480
  * @param sector The sector number to be written.
1481
  * @param num The number of sectors to be read.
1482
  * @param buf The data.
1483
  * @throws InvalidFirmwareException if interface 1 is not supported.
1484
  * @throws UsbException if a communication error occurs.
1485
  * @throws CapabilityException if Flash memory access is not possible.
1486
  * @throws IndexOutOfBoundsException If the buffer is to small.
1487
  */
1488
    public void flashWriteSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1489
        if ( num<1 ) return;
1490
 
1491
        if ( buf.length < flashSectorSize()*num )
1492
            throw new IndexOutOfBoundsException( "Buffer to small: " + buf.length + " < " + (num*flashSectorSize()));
1493
 
1494
        checkCapability(CAPABILITY_FLASH);
1495
        if ( ! flashEnabled() )
1496
            throw new CapabilityException(this, "No Flash memory installed or");
1497
 
1498
        try {
1499
            if ( flashSectorSize()>2048 ) {
1500
                byte[] buf2 = new byte[2048];
1501
                int iz = (flashSectorSize-1) >> 11;
1502
                for (int sn=0; sn<num; sn++ ) {
1503
 
1504
                    int oto = controlMsgTimeout;
1505
                    controlMsgTimeout = 12000; // 12s timeout for erase
1506
                    System.arraycopy(buf,sn*flashSectorSize, buf2,0, 2048);
1507
                    vendorCommand2( 0x42, "Flash Write", sector, 0, buf, 2048 );
1508
                    controlMsgTimeout = oto;
1509
 
1510
                    for (int i=1; i<iz; i++) {
1511
//                      System.out.println("w: "+i);
1512
                        System.arraycopy(buf,sn*flashSectorSize+i*2048, buf2,0, 2048);
1513
                        vendorCommand2( 0x42, "Flash Write", sector, 256, buf2, 2048 );
1514
                    }
1515
 
1516
                    int len = flashSectorSize-iz*2048;
1517
                    System.arraycopy(buf,sn*flashSectorSize+iz*2048, buf2,0, len);
1518
                    vendorCommand2( 0x42, "Flash Write", sector, 512, buf2, len );
1519
                }
1520
            }
1521
            else {
1522
                if ( flashSectorSize*num>2048) System.err.println("Warning: flashWriteSector: Transaction size " + flashSectorSize*num + " may be too large");
1523
                vendorCommand2( 0x42, "Flash Write", sector, sector >> 16, buf, flashSectorSize*num );
1524
            }
1525
        }
1526
        catch ( UsbException e ) {
1527
            throw new UsbException( dev().dev(), "Flash Write: " + flashStrError() );
1528
        }
1529
    }
1530
 
1531
// write one sector
1532
/**
1533
  * Writes one sector to the Flash.
1534
  * @param sector The sector number to be written.
1535
  * @param buf The data.
1536
  * @throws InvalidFirmwareException if interface 1 is not supported.
1537
  * @throws UsbException if a communication error occurs.
1538
  * @throws CapabilityException if Flash memory access is not possible.
1539
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
1540
  */
1541
    public void flashWriteSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1542
        flashWriteSector(sector,1,buf);
1543
    }
1544
 
1545
// ******* flashEnabled ********************************************************
1546
// returns enabled / disabled state 
1547
/**
1548
  * Returns true if Flash memory is installed.
1549
  * @return true if Flash memory is installed.
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 boolean flashEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
1555
        if ( flashEnabled < 0 ) // init variable
1556
            flashState();
1557
        return flashEnabled == 1;
1558
    }
1559
 
1560
// ******* flashSectorSize *****************************************************
1561
// returns sector size of Flash memory, if available
1562
/**
1563
  * Returns the sector size of the Flash memory or 0, if no flash memory is installed.
1564
  * If required, the sector size is determined form the device first.
1565
  * @return the sector size 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 flashSectorSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1571
        if ( flashSectorSize < 0 ) // init variable
1572
            flashState();
1573
        return flashSectorSize;
1574
    }
1575
 
1576
// ******* flashSectors ********************************************************
1577
// returns number of sectors of Flash memory, if available
1578
/**
1579
  * Returns the number of sectors of the Flash memory or 0, if no Flash memory is installed.
1580
  * If required, the number of sectors is determined form the device first.
1581
  * @return the number of sectors of the 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 int flashSectors () throws UsbException, InvalidFirmwareException, CapabilityException {
1587
        if ( flashSectors < 0 ) // init variable
1588
            flashState();
1589
        return flashSectors;
1590
    }
1591
 
1592
// ******* flashSize ***********************************************************
1593
// returns size of Flash memory, if available
1594
/**
1595
  * Returns the size of Flash memory or 0, if no Flash memory is installed.
1596
  * If required, the Flash size is determined form the device first.
1597
  * @return the size of Flash memory.
1598
  * @throws InvalidFirmwareException if interface 1 is not supported.
1599
  * @throws UsbException if a communication error occurs.
1600
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1601
  */
1602
    public long flashSize () throws UsbException, InvalidFirmwareException, CapabilityException {
1603
        return flashSectorSize() * (long)flashSectors();
1604
    }
1605
 
1606
// ******* printMmcState *******************************************************
1607
// returns true if Flash is available
1608
/**
1609
  * Prints out some debug information about *SD/MMC Flash cards in SPI mode.<br>
1610
  * <b>Only use this method if such kind of Flash is installed.</b>
1611
  * @throws InvalidFirmwareException if interface 1 is not supported.
1612
  * @throws UsbException if a communication error occurs.
1613
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1614
  */
1615
    public boolean printMmcState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1616
        byte[] buf = new byte[23];
1617
        checkCapability(CAPABILITY_FLASH);
1618
        vendorRequest2(0x43, "MMC State", 0, 0, buf, 23);
1619
        System.out.println("status=" + Integer.toBinaryString(256+(buf[0] & 255)).substring(1) + "." + Integer.toBinaryString(256+(buf[1] & 255)).substring(1) +
1620
                "   lastCmd=" + buf[3] +
1621
                "   lastCmdResponse=" + Integer.toBinaryString(256+(buf[4] & 255)).substring(1) +
1622
                "   ec=" + buf[2] +
1623
                "   BUSY=" + buf[22] +
1624
                "   SDHC=" + buf[5] +
1625
                "   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));
1626
 
1627
        return flashEnabled == 1;
1628
    }
1629
 
1630
 
1631
// ******* flashUploadBitstream ************************************************
1632
/*
1633
    Returns configuration time in ms.
1634
    The format of the boot sector (sector 0 of the Flash memory) is
1635
        0..7    ID
1636
        8..9    Number of BS sectors, or 0 is disabled
1637
        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))
1638
*/
1639
/**
1640
  * Uploads a Bitstream to the Flash.
1641
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
1642
  * it is possible to construct fully autonomous devices.
1643
  * <p>
1644
  * If configuration data is present information about bitstream are stored there and Bitstream starts
1645
  * at sector 0.
1646
  * <p>
1647
  * On all other devices the information about the bitstream is stored in sector 0.
1648
  * This so called boot sector has the following format:
1649
  * <table bgcolor="#404040" cellspacing=1 cellpadding=4>
1650
  *   <tr>
1651
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
1652
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
1653
  *   </tr>
1654
  *   <tr>
1655
  *     <td bgcolor="#ffffff" valign="top">0..7</td>
1656
  *     <td bgcolor="#ffffff" valign="top">ID, must be "ZTEXBS",1,1</td>
1657
  *   </tr>
1658
  *   <tr>
1659
  *     <td bgcolor="#ffffff" valign="top">8..9</td>
1660
  *     <td bgcolor="#ffffff" valign="top">The number of sectors used to store the Bitstream. 0 means no Bitstream.</td>
1661
  *   </tr>
1662
  *   <tr>
1663
  *     <td bgcolor="#ffffff" valign="top">10..11</td>
1664
  *     <td bgcolor="#ffffff" valign="top">The number of bytes in the last sector.</td>
1665
  *   </tr>
1666
  *   <tr>
1667
  *     <td bgcolor="#ffffff" valign="top">12..sectorSize-1</td>
1668
  *     <td bgcolor="#ffffff" valign="top">This data is reserved for future use and preserved by this method.</td>
1669
  *   </tr>
1670
  * </table>
1671
  * <p>
1672
  * The total size of the Bitstream is computed as ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
1673
  * where bs[i] denotes byte i of the boot sector.
1674
  * <p>
1675
  * The first sector of the Bitstream is sector 1.
1676
  * @param inputStream for reading the Bitstream.
1677
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1678
  * @throws InvalidFirmwareException if interface 1 is not supported.
1679
  * @throws UsbException if a communication error occurs.
1680
  * @throws CapabilityException if Flash memory access is not possible.
1681
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1682
  */
1683
    public long flashUploadBitstream ( InputStream inputStream, int bs ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1684
        int secNum = Math.max(1, 2048 / flashSectorSize());
1685
        final int bufferSize = secNum * flashSectorSize;
1686
        checkCapability(CAPABILITY_FPGA);
1687
        checkCapability(CAPABILITY_FLASH);
1688
        if ( ! flashEnabled() )
1689
            throw new CapabilityException(this, "No Flash memory installed or");
1690
        getFpgaState();
1691
 
1692
// read the Bitstream file      
1693
        byte[][] buffer = new byte[32768][];
1694
        byte[] buf1 = new byte[flashSectorSize()];
1695
 
1696
        int i,j,k,l;
1697
        try {
1698
            j = bufferSize;
1699
            for ( i=0; i<buffer.length && j==bufferSize; i++ ) {
1700
                buffer[i] = new byte[bufferSize];
1701
                j = 0;
1702
                do {
1703
                    k = inputStream.read( buffer[i], j, bufferSize-j );
1704
                    if ( k < 0 )
1705
                        k = 0;
1706
                    j += k;
1707
 
1708
                    // remove header because S6 FPGA's does not support bitstream start word detection
1709
                    if ( i==0 && j==bufferSize && (l=detectBitstreamStart(buffer[0]))>0 ) {
1710
                        for (int m=0; m<bufferSize-l; m++ )
1711
                            buffer[0][m]=buffer[0][m+l];
1712
                        j-=l;
1713
                    }
1714
                }
1715
                while ( j<bufferSize && k>0 );
1716
            }
1717
 
1718
            try {
1719
                inputStream.close();
1720
            }
1721
            catch ( Exception e ) {
1722
            }
1723
        }
1724
        catch (IOException e) {
1725
            throw new BitstreamReadException(e.getLocalizedMessage());
1726
        }
1727
 
1728
// detect bitstream bit order and swap bits if necessary 
1729
        if ( bs<0 || bs>1 )
1730
            bs = detectBitstreamBitOrder(buffer[0]);
1731
        if ( fpgaFlashBitSwap != (bs==1) )
1732
            swapBits( buffer, bufferSize*i );
1733
 
1734
// upload the Bitstream file    
1735
        int startSector = 0;
1736
        long t0 = new Date().getTime();
1737
 
1738
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
1739
            config.setBitstreamSize( ((i-1)*secNum + (j-1)/flashSectorSize + 1)*flashSectorSize );
1740
        }
1741
        else {
1742
            byte[] sector = new byte[flashSectorSize];
1743
            byte[] ID = new String("ZTEXBS").getBytes();
1744
 
1745
            flashReadSector(0,sector);                           // read the boot sector (only the first 16 bytes are overwritten if boot sector is valid)
1746
            boolean b = true;
1747
            for (k=0; k<6; k++) {
1748
                b = b && (sector[k] == ID[k]);
1749
                sector[k]=ID[k];
1750
            }
1751
            if ( ! b )
1752
            sector[6] = 1;
1753
            sector[7] = 1;
1754
            k = (i-1)*secNum + (j-1)/flashSectorSize + 1;
1755
            sector[8] = (byte) (k & 255);
1756
            sector[9] = (byte) ((k>>8) & 255);
1757
            k = ((j-1) % flashSectorSize) + 1;
1758
            sector[10] = (byte) (k & 255);
1759
            sector[11] = (byte) ((k>>8) & 255);
1760
            if ( ! b ) {
1761
                for ( k=12; k<flashSectorSize; k++ )
1762
                    sector[k]=0;
1763
            }
1764
            System.out.print("\rWriting boot sector");
1765
            flashWriteSector(0,sector);                          // write the boot sector
1766
 
1767
            startSector = 1;
1768
        }
1769
 
1770
        for (k=0; k<i-1; k++) {
1771
            System.out.print("\rWriting sector " + (k+1)*secNum + " of " + i*secNum);
1772
            flashWriteSector( startSector+k*secNum, secNum, buffer[k] );        // write the Bitstream sectors
1773
        }
1774
        System.out.println("\rWriting sector " + i*secNum + " of " + i*secNum);
1775
        flashWriteSector( startSector+k*secNum, (j-1)/flashSectorSize + 1, buffer[k] );
1776
 
1777
        return new Date().getTime() - t0;
1778
    }
1779
 
1780
/**
1781
  * Uploads a Bitstream to the Flash.
1782
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
1783
  * it is possible to construct fully autonomous devices.
1784
  * See {@link #flashUploadBitstream(InputStream,int)} for further details.
1785
  * @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).
1786
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1787
  * @throws InvalidFirmwareException if interface 1 is not supported.
1788
  * @throws UsbException if a communication error occurs.
1789
  * @throws CapabilityException if Flash memory access is not possible.
1790
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1791
  */
1792
    public long flashUploadBitstream ( String fwFileName, int bs ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1793
        try {
1794
            return flashUploadBitstream ( JInputStream.getInputStream( fwFileName ), bs );
1795
        }
1796
        catch (IOException e) {
1797
            throw new BitstreamReadException(e.getLocalizedMessage());
1798
        }
1799
    }
1800
 
1801
/**
1802
  * Uploads a Bitstream to the Flash.
1803
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
1804
  * it is possible to construct fully autonomous devices.
1805
  * See {@link #flashUploadBitstream(InputStream,int)} for further details.
1806
  * @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).
1807
  * @throws InvalidFirmwareException if interface 1 is not supported.
1808
  * @throws UsbException if a communication error occurs.
1809
  * @throws CapabilityException if Flash memory access is not possible.
1810
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1811
  */
1812
    public long flashUploadBitstream ( String fwFileName ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1813
        return flashUploadBitstream(fwFileName, -1);
1814
    }
1815
 
1816
// ******* flashResetBitstream *************************************************
1817
// Clears a Bitstream from the Flash.
1818
/**
1819
  * Clears a Bitstream from the Flash.
1820
  * This is achieved by writing 0 to bytes 8..9 of the boot sector, see {@link #flashUploadBitstream(String)}.
1821
  * If no boot sector is installed the method returns without any write action.
1822
  * @throws InvalidFirmwareException if interface 1 is not supported.
1823
  * @throws UsbException if a communication error occurs.
1824
  * @throws CapabilityException if Flash memory access is not possible.
1825
  */
1826
    public void flashResetBitstream ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1827
        checkCapability(CAPABILITY_FLASH);
1828
        if ( ! flashEnabled() )
1829
            throw new CapabilityException(this, "Flash memory not installed or");
1830
 
1831
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
1832
            config.setBitstreamSize(0);
1833
            return;
1834
        }
1835
 
1836
        byte[] sector = new byte[flashSectorSize()];
1837
        byte[] ID = new String("ZTEXBS").getBytes();
1838
 
1839
        flashReadSector(0,sector);                       // read the boot sector
1840
        for (int k=0; k<6; k++)
1841
            if ( sector[k] != ID[k] )
1842
                return;
1843
        if (sector[6]!=1 || sector[7]!=1 )
1844
            return;
1845
        sector[8] = 0;
1846
        sector[9] = 0;
1847
        flashWriteSector(0,sector);                      // write the boot sector
1848
    }
1849
 
1850
// ******* flashFirstFreeSector ************************************************
1851
 
1852
// Returns the first free sector of the Flash memory, i.e. the first sector behind the Bitstream
1853
/**
1854
  * Returns the first free sector of the Flash memory.
1855
  * 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).
1856
  * @return the first free sector of the Flash memory.
1857
  * @throws InvalidFirmwareException if interface 1 is not supported.
1858
  * @throws UsbException if a communication error occurs.
1859
  * @throws CapabilityException if Flash memory access is not possible.
1860
  */
1861
    public int flashFirstFreeSector ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1862
        checkCapability(CAPABILITY_FLASH);
1863
        if ( ! flashEnabled() )
1864
            throw new CapabilityException(this, "No Flash memory installed or");
1865
 
1866
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
1867
            return (Math.max(config.getMaxBitstreamSize(), config.getBitstreamSize())+flashSectorSize()-1) / flashSectorSize();
1868
        }
1869
 
1870
        byte[] sector = new byte[flashSectorSize()];
1871
        byte[] ID = new String("ZTEXBS").getBytes();
1872
 
1873
        flashReadSector(0,sector);                       // read the boot sector
1874
        for (int k=0; k<6; k++)
1875
            if ( sector[k] != ID[k] )
1876
                return 0;
1877
        if (sector[6]!=1 || sector[7]!=1 )
1878
            return 0;
1879
        return (sector[8] & 255) + ((sector[9] & 255) << 8) + 1;
1880
    }
1881
 
1882
// ******* toHumanStr **********************************************************
1883
    private String toHumanStr ( long i ) {
1884
        if ( i==0 ) return "0";
1885
        StringBuilder sb = new StringBuilder();
1886
        int k = 0;
1887
        if ( i<0 ) {
1888
            sb.append("-");
1889
            i=-i;
1890
            k=1;
1891
        }
1892
        if ( (i & 1023) != 0 ) sb.insert(k, i & 1023); i=i>>10;
1893
        if ( (i & 1023) != 0 ) sb.insert(k, (i & 1023) + "K"); i=i>>10;
1894
        if ( (i & 1023) != 0 ) sb.insert(k, (i & 1023) + "M"); i=i>>10;
1895
        if ( i != 0 ) sb.append(i + "G");;
1896
        return sb.toString();
1897
    }
1898
 
1899
// ******* flashInfo **********************************************************
1900
/**
1901
  * Returns information about Flash memory.
1902
  * The result contains the size and how much of the Flash is us used / reserved for / by the Bitstream.
1903
  * If no Flash memeory is suppported an empty string is returned.
1904
  * Returns Information about Flash memory.
1905
  */
1906
    public String flashInfo ( ) {
1907
        StringBuilder sb = new StringBuilder();
1908
        try {
1909
            if ( flashSize() > 0 ) {
1910
                sb.append( "Size: " + toHumanStr(flashSize()) + " Bytes" );
1911
                if ( config!=null && config.getMaxBitstreamSize()>0 ) {
1912
                    sb.append( ";  Bitstream (used / reserved): " + toHumanStr(config.getBitstreamSize()) + " / "  + toHumanStr(config.getMaxBitstreamSize()) + " Bytes" );
1913
                }
1914
                else {
1915
                    sb.append( ";  Bitstream (used): " + toHumanStr(flashFirstFreeSector()*flashSectorSize()) + " Bytes" );
1916
                }
1917
            }
1918
        }
1919
        catch ( Exception e ) {
1920
        }
1921
        return sb.toString();
1922
    }
1923
 
1924
// ******* debugStackSize ******************************************************
1925
/**
1926
  * Returns the size of message stack in messages.
1927
  * @return the size of message stack in messages.
1928
  * @throws InvalidFirmwareException if interface 1 is not supported.
1929
  * @throws UsbException if a communication error occurs.
1930
  * @throws CapabilityException if Flash memory access is not possible.
1931
  */
1932
    public int debugStackSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1933
        checkCapability(CAPABILITY_DEBUG);
1934
        if ( debugStackSize<=0 || debugMsgSize<=0 ) {
1935
            byte[] buf = new byte[7];
1936
            vendorRequest2(0x28, "Read debug data", 0, 0, buf, 4);
1937
            debugStackSize = buf[2] & 255;
1938
            debugMsgSize = buf[3] & 255;
1939
        }
1940
        return debugStackSize;
1941
    }
1942
 
1943
// ******* debugMsgSize ********************************************************
1944
/**
1945
  * Returns the size of messages in bytes.
1946
  * @return the size of messages in bytes.
1947
  * @throws InvalidFirmwareException if interface 1 is not supported.
1948
  * @throws UsbException if a communication error occurs.
1949
  * @throws CapabilityException if Flash memory access is not possible.
1950
  */
1951
    public int debugMsgSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1952
        checkCapability(CAPABILITY_DEBUG);
1953
        if ( debugMsgSize<=0 )
1954
            debugStackSize();
1955
 
1956
        return debugMsgSize;
1957
    }
1958
 
1959
// ******* debugLastMsg ********************************************************
1960
/**
1961
  * Returns the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
1962
  * @return the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
1963
  */
1964
    public final int debugLastMsg ( )  {
1965
        return debugLastMsg;
1966
    }
1967
 
1968
// ******* debugReadMessages ***************************************************
1969
/**
1970
  * Reads debug messages from message stack.
1971
  * The number of messages stored in buf is returned. The total number of new messages is stored in {@link #debugNewMessages}.
1972
  * The number of the latest message is returned by {@link #debugLastMsg()}.
1973
  * @param all If true, all messages from stack are written to buf. If it is false, only the new messages are written to buf.
1974
  * @param buf The buffer to store the messages.
1975
  * @return the size of messages stored in buffer.
1976
  * @throws InvalidFirmwareException if interface 1 is not supported.
1977
  * @throws UsbException if a communication error occurs.
1978
  * @throws CapabilityException if Flash memory access is not possible.
1979
  */
1980
    public int debugReadMessages ( boolean all, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException {
1981
        checkCapability(CAPABILITY_DEBUG);
1982
        byte buf2[] = new byte[ debugStackSize()*debugMsgSize() + 4 ];
1983
        vendorRequest2(0x28, "Read debug data", 0, 0, buf2, buf2.length);
1984
        int lm = (buf2[0] & 255) | ((buf2[1] & 255) << 8);
1985
        debugNewMessages = lm - debugLastMsg;
1986
 
1987
        int r = Math.min( Math.min( buf.length/debugMsgSize() , debugStackSize ), lm);
1988
        if ( !all ) r = Math.min(r,debugNewMessages);
1989
        for (int i = 0; i<r; i++) {
1990
            int k=(lm-r+i) % debugStackSize;
1991
            for (int j=0; j<debugMsgSize; j++ )
1992
                buf[i*debugMsgSize+j] = buf2[k*debugMsgSize+j+4];
1993
        }
1994
 
1995
        debugLastMsg = lm;
1996
        return r;
1997
    }
1998
 
1999
// ******* xmegaStrError *******************************************************
2000
/**
2001
  * Converts a given error code into a String.
2002
  * @param errNum The error code.
2003
  * @return an error message.
2004
  */
2005
    public String xmegaStrError ( int errNum ) {
2006
        switch ( errNum ) {
2007
            case XMEGA_EC_NO_ERROR:
2008
                return "USB error: " + LibusbJava.usb_strerror();
2009
            case XMEGA_EC_PDI_READ_ERROR:
2010
                return "PDI read error";
2011
            case XMEGA_EC_NVM_TIMEOUT:
2012
                return "NVM timeout error";
2013
            case XMEGA_EC_INVALID_DEVICE:
2014
                return "Invalid or unsupported ATxmega";
2015
            case XMEGA_EC_ADDRESS_ERROR:
2016
                return "Address error (invalid address or wrong page size)";
2017
            case XMEGA_EC_NVM_BUSY:
2018
                return "NVM busy";
2019
        }
2020
        return "Error " + errNum;
2021
    }
2022
 
2023
/**
2024
  * Gets the last ATxmega error from the device.
2025
  * @return an error message.
2026
  */
2027
    public String xmegaStrError ( ) {
2028
        try {
2029
            return xmegaStrError( xmegaState() );
2030
        }
2031
        catch ( Exception e ) {
2032
            return "Unknown error (Error receiving error code: "+e.getLocalizedMessage() +")";
2033
        }
2034
    }
2035
 
2036
// ******* xmegaState **********************************************************
2037
/**
2038
  * Read ATxmega error and status information from the device.
2039
  * @return The last error code.
2040
  * @throws InvalidFirmwareException if interface 1 is not supported.
2041
  * @throws UsbException if a communication error occurs.
2042
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2043
  */
2044
    public int xmegaState () throws UsbException, InvalidFirmwareException, CapabilityException {
2045
        byte[] buf = new byte[7];
2046
        checkCapability(CAPABILITY_XMEGA);
2047
        vendorRequest2(0x48, "Xmega state", 0, 0, buf, 7);
2048
        xmegaEC = buf[0] & 255;
2049
 
2050
        xmegaFlashPages = ((buf[2] & 255) << 8) | (buf[1] & 255);
2051
        xmegaEepromPages = ((buf[4] & 255) << 8) | (buf[3] & 255);
2052
        xmegaFlashPageSize = 1 << (buf[5] & 15);
2053
        xmegaEepromPageSize = 1 << (buf[6] & 15);
2054
        return xmegaEC;
2055
    }
2056
 
2057
// ******* xmegaEnabled ********************************************************
2058
/**
2059
  * Returns true if ATxmega controller is available.
2060
  * @return true if ATxmega controller is available.
2061
  * @throws InvalidFirmwareException if interface 1 is not supported.
2062
  * @throws UsbException if a communication error occurs.
2063
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2064
  */
2065
    public boolean xmegaEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
2066
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2067
            xmegaState();
2068
        return xmegaFlashPages > 0 && xmegaEepromPages > 0;
2069
    }
2070
 
2071
// ******* xmegaFlashPages *****************************************************
2072
/**
2073
  * Returns the number of the ATxmega Flash pages.
2074
  * @return The number of the ATxmega Flash pages.
2075
  * @throws InvalidFirmwareException if interface 1 is not supported.
2076
  * @throws UsbException if a communication error occurs.
2077
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2078
  */
2079
    public int xmegaFlashPages () throws UsbException, InvalidFirmwareException, CapabilityException {
2080
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2081
            xmegaState();
2082
        return xmegaFlashPages;
2083
    }
2084
 
2085
// ******* xmegaEepromPages ****************************************************
2086
/**
2087
  * Returns the number of the ATxmega EEPROM pages.
2088
  * @return The number of the ATxmega EEPROM pages.
2089
  * @throws InvalidFirmwareException if interface 1 is not supported.
2090
  * @throws UsbException if a communication error occurs.
2091
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2092
  */
2093
    public int xmegaEepromPages () throws UsbException, InvalidFirmwareException, CapabilityException {
2094
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2095
            xmegaState();
2096
        return xmegaEepromPages;
2097
    }
2098
 
2099
// ******* xmegaFlashPageSize **************************************************
2100
/**
2101
  * Returns the size of the ATxmega Flash pages.
2102
  * @return The size of the ATxmega Flash pages.
2103
  * @throws InvalidFirmwareException if interface 1 is not supported.
2104
  * @throws UsbException if a communication error occurs.
2105
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2106
  */
2107
    public int xmegaFlashPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2108
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2109
            xmegaState();
2110
        return xmegaFlashPageSize;
2111
    }
2112
 
2113
// ******* xmegaEEpromPageSize *************************************************
2114
/**
2115
  * Returns the size of the ATXmega EEPROM pages.
2116
  * @return The size of the ATXmega EEPROM pages.
2117
  * @throws InvalidFirmwareException if interface 1 is not supported.
2118
  * @throws UsbException if a communication error occurs.
2119
  * @throws CapabilityException if ATXmega controllers are not supported by the firmware.
2120
  */
2121
    public int xmegaEepromPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2122
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2123
            xmegaState();
2124
        return xmegaEepromPageSize;
2125
    }
2126
 
2127
// ******* xmegaReset **********************************************************
2128
/**
2129
  * Resets the ATxmega.
2130
  * @throws InvalidFirmwareException if interface 1 is not supported.
2131
  * @throws UsbException if a communication error occurs.
2132
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2133
  */
2134
    public void xmegaReset () throws UsbException, InvalidFirmwareException, CapabilityException {
2135
        checkCapability(CAPABILITY_XMEGA);
2136
        try {
2137
            vendorCommand( 0x49, "XMEGA Reset" );
2138
        }
2139
        catch ( UsbException e ) {
2140
            throw new UsbException( dev().dev(), "NVM Reset: " + xmegaStrError() );
2141
        }
2142
    }
2143
 
2144
 
2145
// ******* xmegaNvmRead ********************************************************
2146
/**
2147
  * Reads data from the NVM of ATxmega.
2148
  * @param addr The source address of the NVM (PDI address space).
2149
  * @param buf A buffer for the storage of the data.
2150
  * @param length The amount of bytes to be read.
2151
  * @throws InvalidFirmwareException if interface 1 is not supported.
2152
  * @throws UsbException if a communication error occurs.
2153
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2154
  */
2155
    public void xmegaNvmRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2156
        checkCapability(CAPABILITY_XMEGA);
2157
 
2158
        try {
2159
            vendorRequest2( 0x4a, "XMEGA NVM Read", addr, addr>> 16, buf, length );
2160
        }
2161
        catch ( UsbException e ) {
2162
            throw new UsbException( dev().dev(), "NVM Read: " + xmegaStrError() );
2163
        }
2164
        try {
2165
            Thread.sleep( 3 );
2166
        }
2167
        catch ( InterruptedException e) {
2168
        }
2169
    }
2170
 
2171
 
2172
// ******* xmegaFlashRead ******************************************************
2173
/**
2174
  * Reads data from Flash memory of ATxmega.
2175
  * @param addr The source address relative to the Flash memory base.
2176
  * @param buf A buffer for the storage of the data.
2177
  * @param length The amount of bytes to be read.
2178
  * @throws InvalidFirmwareException if interface 1 is not supported.
2179
  * @throws UsbException If a communication error occurs.
2180
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2181
  */
2182
    public void xmegaFlashRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2183
        checkCapability(CAPABILITY_XMEGA);
2184
 
2185
        try {
2186
            vendorRequest2( 0x4b, "XMEGA Flash Read", addr, addr>> 16, buf, length );
2187
        }
2188
        catch ( UsbException e ) {
2189
            throw new UsbException( dev().dev(), "XMEGA Flash Read: " + xmegaStrError() );
2190
        }
2191
        try {
2192
            Thread.sleep( 3 );
2193
        }
2194
        catch ( InterruptedException e) {
2195
        }
2196
    }
2197
 
2198
 
2199
 
2200
// ******* xmegaEepromRead *****************************************************
2201
/**
2202
  * Reads data from EEPROM memory of ATxmega.
2203
  * @param addr The source address relative to the EEPROM memory base.
2204
  * @param buf A buffer for the storage of the data.
2205
  * @param length The amount of bytes to be read.
2206
  * @throws InvalidFirmwareException if interface 1 is not supported.
2207
  * @throws UsbException If a communication error occurs.
2208
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2209
  */
2210
    public void xmegaEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2211
        checkCapability(CAPABILITY_XMEGA);
2212
 
2213
        try {
2214
            vendorRequest2( 0x4c, "XMEGA EEPROM Read", addr, addr>> 16, buf, length );
2215
        }
2216
        catch ( UsbException e ) {
2217
            throw new UsbException( dev().dev(), "XMEGA EEPROM Read: " + xmegaStrError() );
2218
        }
2219
        try {
2220
            Thread.sleep( 3 );
2221
        }
2222
        catch ( InterruptedException e) {
2223
        }
2224
    }
2225
 
2226
 
2227
// ******* xmegaFuseRead *******************************************************
2228
/**
2229
  * Reads data from Fuse memory of ATxmega.
2230
  * @param addr The source address relative to the Fuse memory base.
2231
  * @param buf A buffer for the storage of the data.
2232
  * @param length The amount of bytes to be 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 void xmegaFuseRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2238
        checkCapability(CAPABILITY_XMEGA);
2239
 
2240
        try {
2241
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, addr>> 16, buf, length );
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
    }
2252
 
2253
/**
2254
  * Reads data one Fuse of ATxmega.
2255
  * @param addr The index of th Fuse.
2256
  * @return The Fuse read.
2257
  * @throws InvalidFirmwareException if interface 1 is not supported.
2258
  * @throws UsbException If a communication error occurs.
2259
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2260
  */
2261
    public int xmegaFuseRead ( int addr ) throws UsbException, InvalidFirmwareException, CapabilityException {
2262
        byte[] buf = new byte[1];
2263
        checkCapability(CAPABILITY_XMEGA);
2264
        try {
2265
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, 0, buf, 1 );
2266
        }
2267
        catch ( UsbException e ) {
2268
            throw new UsbException( dev().dev(), "XMEGA Fuse Read: " + xmegaStrError() );
2269
        }
2270
        try {
2271
            Thread.sleep( 3 );
2272
        }
2273
        catch ( InterruptedException e) {
2274
        }
2275
        return buf[0] & 255;
2276
    }
2277
 
2278
 
2279
// ******* xmegaFlashPageWrite *************************************************
2280
/**
2281
  * Writes data to Flash memory of ATxmega.
2282
  * @param addr The source address relative to the Flash memory base.
2283
  * @param buf A buffer that stores the data.
2284
  * @throws InvalidFirmwareException if interface 1 is not supported.
2285
  * @throws UsbException if a communication error occurs.
2286
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2287
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash page size.
2288
*/
2289
    public void xmegaFlashPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2290
        checkCapability(CAPABILITY_XMEGA);
2291
 
2292
        if ( buf.length < xmegaFlashPageSize() )
2293
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash page size: " + buf.length + " < " + xmegaFlashPageSize);
2294
 
2295
        try {
2296
            vendorCommand2( 0x4b, "XMEGA Flash page write", addr, addr>> 16, buf, xmegaFlashPageSize );
2297
        }
2298
        catch ( UsbException e ) {
2299
            throw new UsbException( dev().dev(), "XMEGA Flash page write: " + xmegaStrError() );
2300
        }
2301
        try {
2302
            Thread.sleep( 3 );
2303
        }
2304
        catch ( InterruptedException e) {
2305
        }
2306
    }
2307
 
2308
// ******* xmegaEpromPageWrite *************************************************
2309
/**
2310
  * Writes data to EEPROM memory of ATxmega.
2311
  * @param addr The source address relative to the EEPROM memory base.
2312
  * @param buf A buffer that stores the data.
2313
  * @throws InvalidFirmwareException if interface 1 is not supported.
2314
  * @throws UsbException if a communication error occurs.
2315
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2316
  * @throws IndexOutOfBoundsException If the buffer is smaller than the EEPROM page size.
2317
*/
2318
    public void xmegaEepromPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2319
        checkCapability(CAPABILITY_XMEGA);
2320
 
2321
        if ( buf.length < xmegaEepromPageSize() )
2322
            throw new IndexOutOfBoundsException( "Buffer smaller than the EEPROM page size: " + buf.length + " < " + xmegaEepromPageSize);
2323
 
2324
        try {
2325
            vendorCommand2( 0x4c, "XMEGA EEPROM page write", addr, addr>> 16, buf, xmegaEepromPageSize );
2326
        }
2327
        catch ( UsbException e ) {
2328
            throw new UsbException( dev().dev(), "XMEGA EEPROM page write: " + xmegaStrError() );
2329
        }
2330
        try {
2331
            Thread.sleep( 3 );
2332
        }
2333
        catch ( InterruptedException e) {
2334
        }
2335
    }
2336
 
2337
// ******* xmegaFuseWrite ******************************************************
2338
/**
2339
  * Writes one Fuse of the ATxmega.
2340
  * @param addr The index of th Fuse.
2341
  * @param val The value of th Fuse.
2342
  * @throws InvalidFirmwareException if interface 1 is not supported.
2343
  * @throws UsbException if a communication error occurs.
2344
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2345
*/
2346
    public void xmegaFuseWrite ( int addr, int val ) throws UsbException, InvalidFirmwareException, CapabilityException {
2347
        checkCapability(CAPABILITY_XMEGA);
2348
 
2349
        try {
2350
            vendorCommand( 0x4d, "XMEGA Fuse write", val, addr);
2351
        }
2352
        catch ( UsbException e ) {
2353
            throw new UsbException( dev().dev(), "XMEGA Fuse write: " + xmegaStrError() );
2354
        }
2355
        try {
2356
            Thread.sleep( 3 );
2357
        }
2358
        catch ( InterruptedException e) {
2359
        }
2360
    }
2361
 
2362
// ******* xmegaIhxWrite *******************************************************
2363
/**
2364
  * Uploads data to NVM
2365
*/
2366
    private long xmegaIhxWrite ( boolean toFlash, IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2367
        final int maxTries = 3;  // maximum amount of tries
2368
        int pageSize = toFlash ? xmegaFlashPageSize() : xmegaEepromPageSize();
2369
        checkCapability(CAPABILITY_XMEGA);
2370
 
2371
        long t0 = new Date().getTime();
2372
 
2373
        byte buf1[] = new byte[pageSize];
2374
        byte buf2[] = new byte[pageSize];
2375
 
2376
        for (int i = 0; i<65536; i+=pageSize ) {
2377
 
2378
            boolean b = false;
2379
            boolean c = true;
2380
            for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
2381
                boolean d = (ihxFile.ihxData[i+j]>=0) && (ihxFile.ihxData[i+j]<=255);    // data vaild ?
2382
                b |= d;
2383
                c &= d;
2384
            }
2385
            if ( b ) {   // page contains data ==> has to be written
2386
//              System.out.print("Page " + i +": " );
2387
 
2388
                // read page, if firmware image contains undefined bytes
2389
                if ( ! c ) {
2390
//                  System.out.print("R");
2391
                    if ( toFlash )
2392
                        xmegaFlashRead ( i, buf1, pageSize );
2393
                    else
2394
                        xmegaEepromRead ( i, buf1, pageSize );
2395
                }
2396
 
2397
                // prepare the page buffer
2398
                for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
2399
                    if ( (ihxFile.ihxData[i+j]>=0) && (ihxFile.ihxData[i+j]<=255) )
2400
                        buf1[j]= (byte) ihxFile.ihxData[i+j];
2401
                }
2402
 
2403
                for ( int k=1; b ; k++ ) {
2404
                    // write the page
2405
//                  System.out.print("W");
2406
                    if ( toFlash )
2407
                        xmegaFlashPageWrite ( i, buf1 );
2408
                    else
2409
                        xmegaEepromPageWrite ( i, buf1 );
2410
 
2411
                    // verify it
2412
//                  System.out.print("V");
2413
                    if ( toFlash )
2414
                        xmegaFlashRead ( i, buf2, pageSize );
2415
                    else
2416
                        xmegaEepromRead ( i, buf2, pageSize );
2417
                    b=false;
2418
                    for ( int j=0; (j < pageSize) && (! b ); j++ ) {
2419
                        b |= buf1[j] != buf2[j];
2420
                    }
2421
                    if ( b ) {
2422
                        if ( k<maxTries ) {
2423
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page" + i + " failed (try " + k +")" );
2424
                        }
2425
                        else {
2426
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page " + i + " failed");
2427
                        }
2428
                    }
2429
                    b = false;
2430
 
2431
//                  System.out.println();
2432
                }
2433
            }
2434
        }
2435
 
2436
        return new Date().getTime() - t0;
2437
    }
2438
 
2439
 
2440
 
2441
// ******* xmegaWriteFirmware **************************************************
2442
/**
2443
  * Uploads firmware to the flash memory
2444
  * @param ihxFile The firmware / data image.
2445
  * @throws InvalidFirmwareException if interface 1 is not supported.
2446
  * @throws UsbException if a communication error occurs.
2447
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2448
  * @throws FirmwareUploadException if the verification fails.
2449
  * @return the upload time in ms.
2450
*/
2451
    public long xmegaWriteFirmware ( IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2452
        return xmegaIhxWrite( true, ihxFile);
2453
    }
2454
 
2455
 
2456
// ******* xmegaWriteEeprom ****************************************************
2457
/**
2458
  * Uploads data to the EEPROM memory
2459
  * @param ihxFile The firmware / data image.
2460
  * @throws InvalidFirmwareException if interface 1 is not supported.
2461
  * @throws UsbException if a communication error occurs.
2462
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2463
  * @throws FirmwareUploadException if the verification fails.
2464
  * @return the upload time in ms.
2465
*/
2466
    public long xmegaWriteEeprom ( IhxFile ihxFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
2467
        return xmegaIhxWrite( false, ihxFile);
2468
    }
2469
 
2470
 
2471
// ******* toString ************************************************************
2472
/**
2473
  * Returns a lot of useful information about the corresponding device.
2474
  * @return a lot of useful information about the corresponding device.
2475
  */
2476
    public String toString () {
2477
        String str = dev().toString();
2478
        try {
2479
            str += "\n   " + getFpgaConfigurationStr();
2480
        }
2481
        catch ( Exception e ) {
2482
        }
2483
        return str;
2484
    }
2485
 
2486
// ******* capabilityInfo ******************************************************
2487
/**
2488
  * Creates a String with capability information.
2489
  * @param pf A separator between the single capabilities, e.g. ", "
2490
  * @return a string of the supported capabilities.
2491
  */
2492
    public String capabilityInfo ( String pf ) {
2493
        String str = "";
2494
        for ( int i=0; i<6; i++ )
2495
            for (int j=0; j<8; j++ )
2496
                if ( dev().interfaceCapabilities(i,j) ) {
2497
                    if ( ! str.equals("") )
2498
                        str+=pf;
2499
                    if (i*8+j < capabilityStrings.length)
2500
                        str+=capabilityStrings[i*8+j];
2501
                    else
2502
                        str+=i+"."+j;
2503
                }
2504
        return str;
2505
    }
2506
// ******* configureFpgaHS *****************************************************
2507
//  returns configuration time in ms
2508
/**
2509
  * Upload a Bitstream to the FPGA using high speed mode.
2510
  * @param inputStream for reading the Bitstream.
2511
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2512
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2513
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2514
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2515
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2516
  * @throws InvalidFirmwareException if interface 1 is not supported.
2517
  * @throws UsbException if a communication error occurs.
2518
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2519
  */
2520
    public long configureFpgaHS ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2521
        final int transactionBytes = 16384;
2522
        long t0 = 0;
2523
        byte[] settings = new byte[2];
2524
        boolean releaseIF;
2525
 
2526
        checkCapability(CAPABILITY_HS_FPGA);
2527
        vendorRequest2(0x33, "getHSFpgaSettings", settings, 2);
2528
 
2529
        if ( !force && getFpgaConfiguration() )
2530
            throw new AlreadyConfiguredException();
2531
 
2532
        releaseIF = ! getInterfaceClaimed(settings[1] & 255);
2533
//      System.out.println("EP "+ settings[0] + "    IF "+settings[1]+ "   claim " + releaseIF);
2534
 
2535
// read the Bitstream file      
2536
        byte[][] buffer = new byte[16*1024*1024/transactionBytes][];
2537
        int size = 0;
2538
        try {
2539
            int j = transactionBytes;
2540
            for ( int i=0; i<buffer.length && j==transactionBytes; i++ ) {
2541
                buffer[i] = new byte[transactionBytes];
2542
                int k;
2543
                j = 0;
2544
                do {
2545
                    k = inputStream.read( buffer[i], j, transactionBytes-j );
2546
                    if ( k < 0 )
2547
                        k = 0;
2548
                    j += k;
2549
                }
2550
                while ( j<transactionBytes && k>0 );
2551
                size += j;
2552
            }
2553
 
2554
            try {
2555
                inputStream.close();
2556
            }
2557
            catch ( Exception e ) {
2558
            }
2559
        }
2560
        catch (IOException e) {
2561
            throw new BitstreamReadException(e.getLocalizedMessage());
2562
        }
2563
 
2564
        if ( size < 64 )
2565
            throw new BitstreamReadException("Invalid file size: " + size );
2566
 
2567
// detect bitstream bit order and swap bits if necessary 
2568
        if ( bs<0 || bs>1 )
2569
            bs = detectBitstreamBitOrder ( buffer[0] );
2570
        if ( bs == 1 )
2571
            swapBits(buffer,size);
2572
 
2573
// remove NOP's from the end
2574
/*      System.out.println(size);
2575
        while ( size-2>=0 && buffer[(size-2) / transactionBytes][(size-2) % transactionBytes] == 4 && buffer[(size-1) / transactionBytes][(size-1) % transactionBytes]==0 )
2576
            size-=2;
2577
        System.out.println(size);
2578
*/
2579
 
2580
// claim interface if required
2581
        if ( releaseIF ) claimInterface( settings[1] & 255 );
2582
 
2583
//      System.out.println(size & 127);
2584
 
2585
// upload the Bitstream file    
2586
        for ( int tries=3; tries>0; tries-- ) {
2587
 
2588
            vendorCommand(0x34, "initHSFPGAConfiguration" );
2589
 
2590
            try {
2591
                t0 = -new Date().getTime();
2592
 
2593
                for ( int i=0; i<buffer.length && i*transactionBytes < size; i++ ) {
2594
                    int j = size-i*transactionBytes;
2595
                    if (j>transactionBytes)
2596
                        j = transactionBytes;
2597
 
2598
                    if ( j>0 ) {
2599
                        int l = LibusbJava.usb_bulk_write(handle(), settings[0] & 255, buffer[i], j, 1000);
2600
                        if ( l < 0 )
2601
                            throw new UsbException("Error sending Bitstream: " + l + ": " + LibusbJava.usb_strerror());
2602
                        else if ( l != j )
2603
                            throw new UsbException("Error sending Bitstream: Sent " + l +" of " + j + " bytes");
2604
                    }
2605
                }
2606
 
2607
                try {
2608
                    Thread.sleep( (size % transactionBytes) / 1000 + 10 );
2609
                }
2610
                catch ( InterruptedException e) {
2611
                }
2612
 
2613
                vendorCommand(0x35, "finishHSFPGAConfiguration" );
2614
                t0 += new Date().getTime();
2615
 
2616
                getFpgaState();
2617
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+size+")   fpgaInitB="+fpgaInitB + "  time=" + t0);
2618
                if ( ! fpgaConfigured ) {
2619
                    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") + ")" );
2620
                }
2621
 
2622
                if ( enableExtraFpgaConfigurationChecks ) {
2623
                    if ( fpgaBytes!=0 && fpgaBytes!=size )
2624
                        System.err.println("Warning: Possible FPGA configuration data loss: " + (size - fpgaBytes) + " bytes got lost");
2625
                    if ( fpgaInitB!=222 )
2626
                        System.err.println("Warning: Possible Bitstream CRC error: INIT_B_HIST=" + fpgaInitB );
2627
                }
2628
 
2629
                tries = 0;
2630
            }
2631
            catch ( BitstreamUploadException e ) {
2632
                if (tries == 1)
2633
                    throw e;
2634
                else if ( tries<3 || enableExtraFpgaConfigurationChecks )
2635
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
2636
            }
2637
        }
2638
 
2639
        if ( releaseIF ) releaseInterface( settings[1] & 255 );
2640
 
2641
        try {
2642
            Thread.sleep( 25 );
2643
        }
2644
        catch ( InterruptedException e) {
2645
        }
2646
 
2647
        return t0;
2648
    }
2649
 
2650
//  returns configuration time in ms
2651
/**
2652
  * Upload a Bitstream to the FPGA using high speed mode.
2653
  * @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).
2654
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2655
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2656
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2657
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2658
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2659
  * @throws InvalidFirmwareException if interface 1 is not supported.
2660
  * @throws UsbException if a communication error occurs.
2661
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2662
  */
2663
    public long configureFpgaHS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2664
        try {
2665
            return configureFpgaHS( JInputStream.getInputStream( fwFileName ), force, bs );
2666
        }
2667
        catch (IOException e) {
2668
            throw new BitstreamReadException(e.getLocalizedMessage());
2669
        }
2670
    }
2671
 
2672
// ******* configureFpga *****************************************************
2673
//  returns configuration time in ms
2674
/**
2675
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
2676
  * @param inputStream for reading the Bitstream.
2677
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2678
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2679
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2680
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2681
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2682
  * @throws InvalidFirmwareException if interface 1 is not supported.
2683
  * @throws UsbException if a communication error occurs.
2684
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2685
  * @throws IOException if mark/reset is not supported
2686
  */
2687
    public long configureFpga ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException, IOException {
2688
        try {
2689
            inputStream.mark(64*1024*1024);
2690
            return configureFpgaHS( inputStream, force, bs );
2691
        }
2692
        catch ( CapabilityException e ) {
2693
            return configureFpgaLS( inputStream, force, bs );
2694
        }
2695
        catch ( UsbException e ) {
2696
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2697
            inputStream.reset();
2698
            return configureFpgaLS( inputStream, force, bs );
2699
        }
2700
        catch ( BitstreamUploadException e ) {
2701
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2702
            inputStream.reset();
2703
            return configureFpgaLS( inputStream, force, bs );
2704
        }
2705
    }
2706
 
2707
//  returns configuration time in ms
2708
/**
2709
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
2710
  * @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).
2711
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2712
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2713
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2714
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2715
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2716
  * @throws InvalidFirmwareException if interface 1 is not supported.
2717
  * @throws UsbException if a communication error occurs.
2718
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2719
  */
2720
    public long configureFpga ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2721
        try {
2722
            return configureFpgaHS( fwFileName, force, bs );
2723
        }
2724
        catch ( CapabilityException e ) {
2725
            return configureFpgaLS( fwFileName, force, bs );
2726
        }
2727
        catch ( UsbException e ) {
2728
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2729
            return configureFpgaLS( fwFileName, force, bs );
2730
        }
2731
        catch ( BitstreamUploadException e ) {
2732
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
2733
            return configureFpgaLS( fwFileName, force, bs );
2734
        }
2735
    }
2736
 
2737
/**
2738
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
2739
  * @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).
2740
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
2741
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2742
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
2743
  * @throws AlreadyConfiguredException if the FPGA is already configured.
2744
  * @throws InvalidFirmwareException if interface 1 is not supported.
2745
  * @throws UsbException if a communication error occurs.
2746
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
2747
  */
2748
    public long configureFpga ( String fwFileName, boolean force ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
2749
        return configureFpga(fwFileName, force, -1);
2750
    }
2751
 
2752
// ******* macEepromWrite ******************************************************
2753
/**
2754
  * Writes data to the MAC EEPROM.
2755
  * @param addr The destination address of the MAC EEPROM.
2756
  * @param buf The data.
2757
  * @param length The amount of bytes to be sent.
2758
  * @throws InvalidFirmwareException if interface 1 is not supported.
2759
  * @throws UsbException if a communication error occurs.
2760
  * @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.
2761
  */
2762
    public void macEepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2763
        checkCapability(CAPABILITY_MAC_EEPROM);
2764
        if ( ( config != null ) && ( addr<80 ))
2765
            throw new CapabilityException(this, "Overwriting configuration data in MAC EEPROM");
2766
        vendorCommand2( 0x3C, "MAC EEPROM Write", addr, 0, buf, length );
2767
        try {
2768
            Thread.sleep( 10 );
2769
        }
2770
        catch ( InterruptedException e) {
2771
        }
2772
    }
2773
 
2774
// ******* macEepromRead *******************************************************
2775
/**
2776
  * Reads data from the MAC EEPROM.
2777
  * @param addr The source address of the MAC EEPROM.
2778
  * @param buf A buffer for the storage of the data.
2779
  * @param length The amount of bytes to be read.
2780
  * @throws InvalidFirmwareException if interface 1 is not supported.
2781
  * @throws UsbException if a communication error occurs.
2782
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2783
  */
2784
    public void macEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2785
        checkCapability(CAPABILITY_MAC_EEPROM);
2786
        vendorRequest2( 0x3B, "MAC EEPROM Read", addr, 0, buf, length );
2787
        try {
2788
            Thread.sleep( 10 );
2789
        }
2790
        catch ( InterruptedException e) {
2791
        }
2792
    }
2793
 
2794
// ******* macEepromState ******************************************************
2795
// returns true if MAC EEPROM is ready
2796
/**
2797
  * Reads the current MAC EEPROM status.
2798
  * @throws InvalidFirmwareException if interface 1 is not supported.
2799
  * @throws UsbException if a communication error occurs.
2800
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2801
  * @return true if MAC EEPROM is ready.
2802
  */
2803
    public boolean macEepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2804
        byte[] buf = new byte[1];
2805
        checkCapability(CAPABILITY_MAC_EEPROM);
2806
        vendorRequest2(0x3D, "MAC EEPROM State", 0, 0, buf, 1);
2807
        return buf[0] == 0;
2808
    }
2809
 
2810
// ******* macRead *************************************************************
2811
/**
2812
  * Reads MAC address from MAC EEPROM.
2813
  * @param buf A buffer with a minimum size of 6 bytes.
2814
  * @throws InvalidFirmwareException if interface 1 is not supported.
2815
  * @throws UsbException if a communication error occurs.
2816
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
2817
  * @throws IndexOutOfBoundsException If the buffer is smaller than 6 bytes.
2818
  */
2819
    public void macRead ( byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2820
        if ( buf.length < 6 )
2821
            throw new IndexOutOfBoundsException( "macRead: Buffer smaller than 6 Bytes" );
2822
        macEepromRead(250, buf, 6);
2823
    }
2824
 
2825
// ******* numberOfFpgas *******************************************************
2826
/**
2827
  * Returns the number of FPGA's
2828
  * @throws InvalidFirmwareException if interface 1 is not supported.
2829
  * @throws UsbException if a communication error occurs.
2830
  * @return number of FPGA's
2831
  */
2832
    public int numberOfFpgas ( ) throws UsbException, InvalidFirmwareException {
2833
        if ( numberOfFpgas < 0 ) {
2834
            try {
2835
                byte[] buffer = new byte[3];
2836
                checkCapability(CAPABILITY_MULTI_FPGA);
2837
                vendorRequest2(0x50, "getMultiFpgaInfo", buffer, 3);
2838
                numberOfFpgas = (buffer[0] & 255)+1;
2839
                selectedFpga = buffer[1] & 255;
2840
                parallelConfigSupport = buffer[2]==1;
2841
            }
2842
            catch ( CapabilityException e ) {
2843
                numberOfFpgas = 1;
2844
                selectedFpga = 0;
2845
                parallelConfigSupport = false;
2846
            }
2847
        }
2848
        return numberOfFpgas;
2849
    }
2850
 
2851
// ******* selectFpga **********************************************************
2852
/**
2853
  * Select a FPGA
2854
  * @param num FPGA to select. Valid values are 0 to {@link #numberOfFpgas()}-1
2855
  * @throws InvalidFirmwareException if interface 1 is not supported.
2856
  * @throws UsbException if a communication error occurs.
2857
  * @throws IndexOutOfBoundsException If FPGA number is not in range.
2858
  */
2859
    public void selectFpga ( int num ) throws UsbException, InvalidFirmwareException, IndexOutOfBoundsException {
2860
        numberOfFpgas();
2861
        if ( num<0 || num>=numberOfFpgas )
2862
            throw new IndexOutOfBoundsException( "selectFPGA: Invalid FPGA number" );
2863
 
2864
        if ( numberOfFpgas != 1 ) {
2865
            try {
2866
                checkCapability(CAPABILITY_MULTI_FPGA);
2867
                vendorCommand( 0x51, "selectFPGA", num, 0);
2868
            }
2869
            catch ( CapabilityException e ) {
2870
                // should'nt occur
2871
            }
2872
        }
2873
        selectedFpga = num;
2874
    }
2875
 
2876
// ******* TempSensorRead ******************************************************
2877
/**
2878
  * Read temperature sensor data.
2879
  * @param idx Temperature sensor index
2880
  * @return Temperature in deg. C
2881
  * @throws InvalidFirmwareException If interface 1 or temperature sensor protocol is not supported.
2882
  * @throws UsbException If a communication error occurs.
2883
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2884
  * @throws IndexOutOfBoundsException If idx is not in range.
2885
  */
2886
    public double tempSensorRead ( int idx ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2887
        int[] xIdx = { 3, 4, 1, 2 };
2888
 
2889
        checkCapability(CAPABILITY_TEMP_SENSOR);
2890
 
2891
        int len = 0;
2892
 
2893
        if ( tempSensorUpdateInterval < 40 )
2894
            tempSensorUpdateInterval = 40;
2895
 
2896
        if ( new Date().getTime() > lastTempSensorReadTime+tempSensorUpdateInterval ) {
2897
            len = vendorRequest( 0x58, "Temperature Sensor Read", 0, 0, tempSensorBuf, tempSensorBuf.length );
2898
            lastTempSensorReadTime = new Date().getTime();
2899
 
2900
            if ( len != 5 || tempSensorBuf[0] != 1 )
2901
                throw new InvalidFirmwareException("tempSensorRead: Invalid temperature sensor protocol");
2902
        }
2903
 
2904
        if ( idx<0 || idx>3 )
2905
            throw new IndexOutOfBoundsException( "tempSensorRead: Invalid temperature sensor index" );
2906
 
2907
        return ((tempSensorBuf[xIdx[idx]] & 255)-77.2727)/1.5454;
2908
    }
2909
 
2910
// ******* printSpiState *******************************************************
2911
// returns true if Flash is available
2912
/**
2913
  * Prints out some debug information about SPI Flash.<br>
2914
  * <b>Only use this method if such kind of Flash is installed.</b>
2915
  * @throws InvalidFirmwareException if interface 1 is not supported.
2916
  * @throws UsbException if a communication error occurs.
2917
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2918
  */
2919
    public boolean printSpiState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2920
        byte[] buf = new byte[10];
2921
        checkCapability(CAPABILITY_FLASH);
2922
        vendorRequest2(0x43, "SPI State", 0, 0, buf, 10);
2923
        System.out.println("ec=" + buf[0] +
2924
                "   vendor=" + Integer.toHexString(buf[1] & 255).toUpperCase() + "h" +
2925
                "   device=" + Integer.toHexString(buf[2] & 255).toUpperCase() + "h" +
2926
                "   memType=" + Integer.toHexString(buf[3] & 255).toUpperCase() + "h" +
2927
                "   eraseCmd=" + Integer.toHexString(buf[4] & 255).toUpperCase() + "h" +
2928
                "   lastCmd=" + Integer.toHexString(buf[5] & 255).toUpperCase() + "h" +
2929
                "   buf=" + (buf[6] & 255)+" "+(buf[7] & 255)+" "+(buf[8] & 255)+" "+(buf[9] & 255)
2930
            );
2931
        return flashEnabled == 1;
2932
    }
2933
 
2934
}
2935
 

powered by: WebSVN 2.1.0

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