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

Subversion Repositories usb_fpga_1_2

[/] [usb_fpga_1_2/] [trunk/] [java/] [ztex/] [Ztex1v1.java] - Blame information for rev 9

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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