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

Subversion Repositories usb_fpga_2_14

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

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 ZTEX
/*%
2
   Java host software API of ZTEX SDK
3
   Copyright (C) 2009-2017 ZTEX GmbH.
4
   http://www.ztex.de
5
 
6
   This Source Code Form is subject to the terms of the Mozilla Public
7
   License, v. 2.0. If a copy of the MPL was not distributed with this file,
8
   You can obtain one at http://mozilla.org/MPL/2.0/.
9
 
10
   Alternatively, the contents of this file may be used under the terms
11
   of the GNU General Public License Version 3, as described below:
12
 
13
   This program is free software; you can redistribute it and/or modify
14
   it under the terms of the GNU General Public License version 3 as
15
   published by the Free Software Foundation.
16
 
17
   This program is distributed in the hope that it will be useful, but
18
   WITHOUT ANY WARRANTY; without even the implied warranty of
19
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20
   General Public License for more details.
21
 
22
   You should have received a copy of the GNU General Public License
23
   along with this program; if not, see http://www.gnu.org/licenses/.
24
%*/
25
 
26
/*
27
    Functions for USB devices with ZTEX descriptor 1, Interface 1
28
    Interface capabilities and vendor requests (VR) / commands (VC):
29
    0.0  : EEPROM support
30
        VR 0x38 : read from EEPROM
31
            Returns:
32
                EEPROM data
33
        VC 0x39 : write to EEPROM
34
        VR 0x3a : EEPROM state
35
            Returns:
36
                Offs    Description
37
                0-1     bytes written
38
                2       checksum
39
                3       0:idle, 1:busy or error
40
 
41
    0.1  : FPGA Configuration
42
        VR 0x30 : get FPGA state
43
            Returns:
44
                Offs    Description
45
 
46
                1       checksum
47
                2-5     transferred bytes
48
                6       INIT_B state
49
                7       Flash configuration result
50
                8       Flash bitstream bit order (1=swapped)
51
 
52
        VC 0x31 : reset FPGA
53
        VC 0x32 : send FPGA configuration data (Bitstream)
54
 
55
    0.2  : Flash memory support
56
        VR 0x40 : read Flash state
57
            Returns:
58
                Offs    Description
59
 
60
                1-2     Sector size <sector size> = MSB==0 : flash_sector_size and 0x7fff ? 1<<(flash_sector_size and 0x7fff)
61
                3-6     Number of sectors
62
                7       Error code
63
        VR 0x41 : read from Flash
64
        VC 0x42 : write to Flash
65
    0.3  : Debug helper support
66
        VR 0x28 : read debug data
67
            Returns:
68
                Offs    Description
69
                0-1     number of messages
70
                2       stack size in messages
71
                3       message size in bytes
72
                >=4     message stack
73
    0.4  : XMEGA support
74
        VR 0x48 : read XMEGA status information
75
            Returns:
76
                Offs    Description
77
 
78
                1-2     Flash size in pages
79
                3-4     EEPROM size in pages
80
                5       Flash page size as power of two (e.g. 9 means 512 bytes)
81
                6       EEPROM page size as power of two
82
        VC 0x49 : reset XMEGA
83
        VR 0x4A,0x4B,0x4C,0x4D : read XMEGA NVM using PDI address space / relative to Flash address base / EEPROM address base / Fuse address base
84
        VC 0x4B,0x4C : write exactly one Flash / EEPROM page
85
        VC 0x4D : write Fuse
86
 
87
    0.5  : High speed FPGA configuration support
88
        VR 0x33 : Return Endpoint settings
89
            Returns:
90
                Offs    Description
91
 
92
                1       Interface number
93
        VC 0x34 : Start high speed FPGA configuration
94
        VC 0x35 : Finish high speed FPGA configuration
95
 
96
    0.6  : MAC EEPROM support
97
        VR 0x3B : read from MAC EEPROM
98
            Returns:
99
                MAC EEPROM data
100
        VC 0x3C : write to MAC EEPROM
101
        VR 0x3D : MAC EEPROM state
102
            Returns:
103
                Offs    Description
104
 
105
 
106
    0.7  : Multi-FPGA support
107
        VR 0x50 : Return multi-FPGA information
108
            Returns:
109
                Offs    Description
110
 
111
                1       Selected FPGA - 1
112
                2       Parallel configuration support (0:no, 1:yes)
113
        VC 0x51 : set CS
114
            Parameters:
115
                index: Select command
116
 
117
                    1 : select all FPGA's for configuration
118
                value: FPGA to select - 1
119
 
120
    1.0  : Temperature sensor
121
        VR 0x58 : Return temperature data
122
            Returns:
123
                Offs    Description
124
 
125
                1..n    Data
126
 
127
    1.1  : Flash 2 support
128
        VR 0x44 : read Flash state
129
            Returns:
130
                Offs    Description
131
 
132
                1-2     Sector size <sector size> = MSB==0 : flash_sector_size and 0x7fff ? 1<<(flash_sector_size and 0x7fff)
133
                3-6     Number of sectors
134
                7       Error code
135
        VR 0x45 : read from Flash
136
        VC 0x46 : write to Flash
137
 
138
    1.2  : FX3 extensions
139
        indicates an FX3 firmware
140
 
141
    1.3  : Debug helper 2 support
142
        VR 0x28 : read a debug message given by index (value<<16 | index)
143
            Returns:
144
                Offs    Description
145
 
146
                1..4    Index of last message in buffer
147
                5..6    Number of messages in buffer
148
                7..8    Size if the message
149
                9       Type of the message
150
                >=10    Message data
151
        VR 0x29 : returns USB 3.0 errors
152
            Returns:
153
                Offs    Description
154
                0..1    Send errors
155
                2..3    Receive errors
156
 
157
    1.4  : Default firmware interface
158
        VC 0x60: Reset
159
        VR 0x61: Write/read GPIO's
160
            Returns:
161
                Offs    Description
162
                1       GPIO state (bits 0..3)
163
        VC 0x62: Write to low speed interface
164
        VR 0x63: Read from low speed interface
165
        VR 0x64: Default interface information
166
            Returns:
167
                Offs    Description
168
                1       Version
169
                2       Output Endpoint of the high speed interface
170
                3       Input Endpoint of the high speed interface
171
*/
172
 
173
package ztex;
174
 
175
import java.io.*;
176
import java.util.*;
177
import java.nio.*;
178
 
179
import org.usb4java.*;
180
 
181
/**
182
  * This class implements the communication protocol of the interface version 1 for the interaction with the ZTEX firmware.
183
  * <p>
184
  * The features supported by this interface can be accessed via vendor commands and vendor requests via Endpoint 0.
185
  * Each feature can be enabled or disabled by the firmware and also depends from the hardware.
186
  * The presence of a feature is indicated by a 1 in the corresponding feature bit of the ZTEX descriptor 1, see {@link ZtexDevice1}.
187
  * The following table gives an overview about the features
188
  * <table bgcolor="#404040" cellspacing=1 cellpadding=10>
189
  *   <tr>
190
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Capability bit</b></td>
191
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
192
  *   </tr>
193
  *   <tr>
194
  *     <td bgcolor="#ffffff" valign="top">0.0</td>
195
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
196
  *       EEPROM support<p>
197
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
198
  *         <tr>
199
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
200
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
201
  *         </tr>
202
  *         <tr>
203
  *           <td bgcolor="#ffffff" valign="top">VR 0x38</td>
204
  *           <td bgcolor="#ffffff" valign="top">Read from EEPROM</td>
205
  *         </tr>
206
  *         <tr>
207
  *           <td bgcolor="#ffffff" valign="top">VC 0x39</td>
208
  *           <td bgcolor="#ffffff" valign="top">Write to EEPROM</td>
209
  *         </tr>
210
  *         <tr>
211
  *           <td bgcolor="#ffffff" valign="top">VR 0x3a</td>
212
  *           <td bgcolor="#ffffff" valign="top">Get EEPROM state. Returns:
213
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
214
  *               <tr>
215
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
216
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
217
  *               </tr>
218
  *               <tr>
219
  *                 <td bgcolor="#ffffff" valign="top">0-1</td>
220
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes written.</td>
221
  *               </tr>
222
  *               <tr>
223
  *                 <td bgcolor="#ffffff" valign="top">2</td>
224
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
225
  *               </tr>
226
  *               <tr>
227
  *                 <td bgcolor="#ffffff" valign="top">3</td>
228
  *                 <td bgcolor="#ffffff" valign="top">0:idle, 1:busy or error</td>
229
  *               </tr>
230
  *             </table>
231
  *           </td>
232
  *         </tr>
233
  *       </table>
234
  *     </td>
235
  *   </tr>
236
  *   <tr>
237
  *     <td bgcolor="#ffffff" valign="top">0.1</td>
238
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
239
  *       FPGA Configuration<p>
240
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
241
  *         <tr>
242
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
243
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
244
  *         </tr>
245
  *         <tr>
246
  *           <td bgcolor="#ffffff" valign="top">VR 0x30</td>
247
  *           <td bgcolor="#ffffff" valign="top">Get FPGA state. Returns:
248
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
249
  *               <tr>
250
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
251
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
252
  *               </tr>
253
  *               <tr>
254
  *                 <td bgcolor="#ffffff" valign="top">0</td>
255
  *                 <td bgcolor="#ffffff" valign="top">1: unconfigured, 0:configured</td>
256
  *               </tr>
257
  *               <tr>
258
  *                 <td bgcolor="#ffffff" valign="top">1</td>
259
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
260
  *               </tr>
261
  *               <tr>
262
  *                 <td bgcolor="#ffffff" valign="top">2-5</td>
263
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes transferred.</td>
264
  *               </tr>
265
  *               <tr>
266
  *                 <td bgcolor="#ffffff" valign="top">6</td>
267
  *                 <td bgcolor="#ffffff" valign="top">INIT_B states.</td>
268
  *               </tr>
269
  *               <tr>
270
  *                 <td bgcolor="#ffffff" valign="top">7</td>
271
  *                 <td bgcolor="#ffffff" valign="top">Flash configuration result.</td>
272
  *               </tr>
273
  *               <tr>
274
  *                 <td bgcolor="#ffffff" valign="top">8</td>
275
  *                 <td bgcolor="#ffffff" valign="top">Flash Bitstreambit order (1=swapped).</td>
276
  *               </tr>
277
  *             </table>
278
  *           </td>
279
  *         </tr>
280
  *         <tr>
281
  *           <td bgcolor="#ffffff" valign="top">VC 0x31</td>
282
  *           <td bgcolor="#ffffff" valign="top">Reset FPGA</td>
283
  *         </tr>
284
  *         <tr>
285
  *           <td bgcolor="#ffffff" valign="top">VR 0x32</td>
286
  *           <td bgcolor="#ffffff" valign="top">Send Bitstream</td>
287
  *         </tr>
288
  *       </table>
289
  *     </td>
290
  *   </tr>
291
  *   <tr>
292
  *     <td bgcolor="#ffffff" valign="top">0.2</td>
293
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
294
  *       Flash memory support<p>
295
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
296
  *         <tr>
297
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
298
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
299
  *         </tr>
300
  *         <tr>
301
  *           <td bgcolor="#ffffff" valign="top">VR 0x40</td>
302
  *           <td bgcolor="#ffffff" valign="top">Get Flash state. Returns:
303
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
304
  *               <tr>
305
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
306
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
307
  *               </tr>
308
  *               <tr>
309
  *                 <td bgcolor="#ffffff" valign="top">0</td>
310
  *                 <td bgcolor="#ffffff" valign="top">1:enabled, 0:disabled</td>
311
  *               </tr>
312
  *               <tr>
313
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
314
  *                 <td bgcolor="#ffffff" valign="top">Sector size</td>
315
  *               </tr>
316
  *               <tr>
317
  *                 <td bgcolor="#ffffff" valign="top">3-6</td>
318
  *                 <td bgcolor="#ffffff" valign="top">Number of sectors</td>
319
  *               </tr>
320
  *               <tr>
321
  *                 <td bgcolor="#ffffff" valign="top">7</td>
322
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
323
  *               </tr>
324
  *             </table>
325
  *           </td>
326
  *         </tr>
327
  *         <tr>
328
  *           <td bgcolor="#ffffff" valign="top">VR 0x41</td>
329
  *           <td bgcolor="#ffffff" valign="top">Read one sector from Flash</td>
330
  *         </tr>
331
  *         <tr>
332
  *           <td bgcolor="#ffffff" valign="top">VC 0x42</td>
333
  *           <td bgcolor="#ffffff" valign="top">Write one sector to Flash</td>
334
  *         </tr>
335
  *       </table>
336
  *     </td>
337
  *   </tr>
338
  *   <tr>
339
  *     <td bgcolor="#ffffff" valign="top">0.3</td>
340
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
341
  *       Debug helper support<p>
342
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
343
  *         <tr>
344
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
345
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
346
  *         </tr>
347
  *         <tr>
348
  *           <td bgcolor="#ffffff" valign="top">VR 0x28</td>
349
  *           <td bgcolor="#ffffff" valign="top">Get debug data. Returns:
350
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
351
  *               <tr>
352
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
353
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
354
  *               </tr>
355
  *               <tr>
356
  *                 <td bgcolor="#ffffff" valign="top">0-1</td>
357
  *                 <td bgcolor="#ffffff" valign="top">Number of the last message</td>
358
  *               </tr>
359
  *               <tr>
360
  *                 <td bgcolor="#ffffff" valign="top">2</td>
361
  *                 <td bgcolor="#ffffff" valign="top">Stack size in messages</td>
362
  *               </tr>
363
  *               <tr>
364
  *                 <td bgcolor="#ffffff" valign="top">3</td>
365
  *                 <td bgcolor="#ffffff" valign="top">Message size in bytes</td>
366
  *               </tr>
367
  *               <tr>
368
  *                 <td bgcolor="#ffffff" valign="top">&ge;4</td>
369
  *                 <td bgcolor="#ffffff" valign="top">Message stack</td>
370
  *               </tr>
371
  *             </table>
372
  *           </td>
373
  *         </tr>
374
  *       </table>
375
  *     </td>
376
  *   </tr>
377
  *   <tr>
378
  *     <td bgcolor="#ffffff" valign="top">0.4</td>
379
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
380
  *       XMEGA support<p>
381
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
382
  *         <tr>
383
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
384
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
385
  *         </tr>
386
  *         <tr>
387
  *           <td bgcolor="#ffffff" valign="top">VR 0x48</td>
388
  *           <td bgcolor="#ffffff" valign="top">Read XMEGA status information. Returns:
389
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
390
  *               <tr>
391
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
392
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
393
  *               </tr>
394
  *               <tr>
395
  *                 <td bgcolor="#ffffff" valign="top">0</td>
396
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
397
  *               </tr>
398
  *               <tr>
399
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
400
  *                 <td bgcolor="#ffffff" valign="top">Flash size in pages</td>
401
  *               </tr>
402
  *               <tr>
403
  *                 <td bgcolor="#ffffff" valign="top">3-4</td>
404
  *                 <td bgcolor="#ffffff" valign="top">EEPROM sie in pages</td>
405
  *               </tr>
406
  *               <tr>
407
  *                 <td bgcolor="#ffffff" valign="top">5</td>
408
  *                 <td bgcolor="#ffffff" valign="top">Flash page size as power of two  (e.g. 9 means 512 bytes)</td>
409
  *               </tr>
410
  *               <tr>
411
  *                 <td bgcolor="#ffffff" valign="top">6</td>
412
  *                 <td bgcolor="#ffffff" valign="top">EEPROM page size as power of two</td>
413
  *               </tr>
414
  *             </table>
415
  *           </td>
416
  *         </tr>
417
  *         <tr>
418
  *           <td bgcolor="#ffffff" valign="top">VC 0x49</td>
419
  *           <td bgcolor="#ffffff" valign="top">Reset XMEGA</td>
420
  *         </tr>
421
  *         <tr>
422
  *           <td bgcolor="#ffffff" valign="top">VRs 0x4A, 0x4B, 0x4C, 0x4D</td>
423
  *           <td bgcolor="#ffffff" valign="top">Read XMEGA NVM using PDI address space / relative to Flash address base / EEPROM address base / Fuse address base</td>
424
  *         </tr>
425
  *         <tr>
426
  *           <td bgcolor="#ffffff" valign="top">VCs 0x4B, 0x4C</td>
427
  *           <td bgcolor="#ffffff" valign="top">Write exactly one Flash / EEPROM page</td>
428
  *         </tr>
429
  *         <tr>
430
  *           <td bgcolor="#ffffff" valign="top">VCs 0x4D</td>
431
  *           <td bgcolor="#ffffff" valign="top">Write Fuse</td>
432
  *         </tr>
433
  *       </table>
434
  *     </td>
435
  *   </tr>
436
  *   <tr>
437
  *     <td bgcolor="#ffffff" valign="top">0.5</td>
438
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
439
  *       High speed FPGA configuration support<p>
440
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
441
  *         <tr>
442
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
443
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
444
  *         </tr>
445
  *         <tr>
446
  *           <td bgcolor="#ffffff" valign="top">VR 0x33</td>
447
  *           <td bgcolor="#ffffff" valign="top">Read Endpoint settings. Returns:
448
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
449
  *               <tr>
450
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
451
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
452
  *               </tr>
453
  *               <tr>
454
  *                 <td bgcolor="#ffffff" valign="top">0</td>
455
  *                 <td bgcolor="#ffffff" valign="top">Endpoint number</td>
456
  *               </tr>
457
  *               <tr>
458
  *                 <td bgcolor="#ffffff" valign="top">1</td>
459
  *                 <td bgcolor="#ffffff" valign="top">Interface number</td>
460
  *               </tr>
461
  *             </table>
462
  *           </td>
463
  *         </tr>
464
  *         <tr>
465
  *           <td bgcolor="#ffffff" valign="top">VR 0x34</td>
466
  *           <td bgcolor="#ffffff" valign="top">Start FPGA configuration</td>
467
  *         </tr>
468
  *         <tr>
469
  *           <td bgcolor="#ffffff" valign="top">VC 0x35</td>
470
  *           <td bgcolor="#ffffff" valign="top">Finish FPGA configuration</td>
471
  *         </tr>
472
  *       </table>
473
  *     </td>
474
  *   </tr>
475
  *   <tr>
476
  *     <td bgcolor="#ffffff" valign="top">0.6</td>
477
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
478
  *       MAC EEPROM support<p>
479
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
480
  *         <tr>
481
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
482
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
483
  *         </tr>
484
  *         <tr>
485
  *           <td bgcolor="#ffffff" valign="top">VR 0x3B</td>
486
  *           <td bgcolor="#ffffff" valign="top">Read from MAC EEPROM</td>
487
  *         </tr>
488
  *         <tr>
489
  *           <td bgcolor="#ffffff" valign="top">VC 0x3C</td>
490
  *           <td bgcolor="#ffffff" valign="top">Write to MAC EEPROM</td>
491
  *         </tr>
492
  *         <tr>
493
  *           <td bgcolor="#ffffff" valign="top">VR 0x3D</td>
494
  *           <td bgcolor="#ffffff" valign="top">Get MAC EEPROM state. Returns:
495
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
496
  *               <tr>
497
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
498
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
499
  *               </tr>
500
  *               <tr>
501
  *                 <td bgcolor="#ffffff" valign="top">0</td>
502
  *                 <td bgcolor="#ffffff" valign="top">0:idle, 1:busy or error</td>
503
  *               </tr>
504
  *             </table>
505
  *           </td>
506
  *         </tr>
507
  *       </table>
508
  *     </td>
509
  *   </tr>
510
  *   <tr>
511
  *     <td bgcolor="#ffffff" valign="top">0.7</td>
512
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
513
  *       Multi-FPGA support<p>
514
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
515
  *         <tr>
516
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
517
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
518
  *         </tr>
519
  *         <tr>
520
  *           <td bgcolor="#ffffff" valign="top">VR 0x50</td>
521
  *           <td bgcolor="#ffffff" valign="top">Return multi-FPGA information:
522
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
523
  *               <tr>
524
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
525
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
526
  *               </tr>
527
  *               <tr>
528
  *                 <td bgcolor="#ffffff" valign="top">0</td>
529
  *                 <td bgcolor="#ffffff" valign="top">Number of FPGA's - 1</td>
530
  *               </tr>
531
  *               <tr>
532
  *                 <td bgcolor="#ffffff" valign="top">1</td>
533
  *                 <td bgcolor="#ffffff" valign="top">Selected FPGA - 1</td>
534
  *               </tr>
535
  *               <tr>
536
  *                 <td bgcolor="#ffffff" valign="top">2</td>
537
  *                 <td bgcolor="#ffffff" valign="top">Parallel configuration support (0:no, 1:yes)</td>
538
  *               </tr>
539
  *             </table>
540
  *           </td>
541
  *         </tr>
542
  *         <tr>
543
  *           <td bgcolor="#ffffff" valign="top">VC 0x51</td>
544
  *           <td bgcolor="#ffffff" valign="top">Parameters:
545
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
546
  *               <tr>
547
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Parameter</b></td>
548
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
549
  *               </tr>
550
  *               <tr>
551
  *                 <td bgcolor="#ffffff" valign="top">index</td>
552
  *                 <td bgcolor="#ffffff" valign="top">Select command<br> 0: Select single FPGA <br> 1: Select all FPGA's for configuration</td>
553
  *               </tr>
554
  *               <tr>
555
  *                 <td bgcolor="#ffffff" valign="top">value</td>
556
  *                 <td bgcolor="#ffffff" valign="top">FPGA to select - 1</td>
557
  *               </tr>
558
  *             </table>
559
  *           </td>
560
  *         </tr>
561
  *       </table>
562
  *     </td>
563
  *   </tr>
564
  *   <tr>
565
  *     <td bgcolor="#ffffff" valign="top">1.0</td>
566
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
567
  *       Temperature sensor support<p>
568
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
569
  *         <tr>
570
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
571
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
572
  *         </tr>
573
  *         <tr>
574
  *           <td bgcolor="#ffffff" valign="top">VR 0x58</td>
575
  *           <td bgcolor="#ffffff" valign="top">Return temperature data:
576
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
577
  *               <tr>
578
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
579
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
580
  *               </tr>
581
  *               <tr>
582
  *                 <td bgcolor="#ffffff" valign="top">0</td>
583
  *                 <td bgcolor="#ffffff" valign="top">Protocol</td>
584
  *               </tr>
585
  *               <tr>
586
  *                 <td bgcolor="#ffffff" valign="top">1..n</td>
587
  *                 <td bgcolor="#ffffff" valign="top">Data</td>
588
  *               </tr>
589
  *             </table>
590
  *           </td>
591
  *         </tr>
592
  *       </table>
593
  *     </td>
594
  *   </tr>
595
  *   <tr>
596
  *     <td bgcolor="#ffffff" valign="top">1.1</td>
597
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
598
  *       Flash 2 support<p>
599
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
600
  *         <tr>
601
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
602
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
603
  *         </tr>
604
  *         <tr>
605
  *           <td bgcolor="#ffffff" valign="top">VR 0x40</td>
606
  *           <td bgcolor="#ffffff" valign="top">Get Flash state. Returns:
607
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
608
  *               <tr>
609
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
610
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
611
  *               </tr>
612
  *               <tr>
613
  *                 <td bgcolor="#ffffff" valign="top">0</td>
614
  *                 <td bgcolor="#ffffff" valign="top">1:enabled, 0:disabled</td>
615
  *               </tr>
616
  *               <tr>
617
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
618
  *                 <td bgcolor="#ffffff" valign="top">Sector size</td>
619
  *               </tr>
620
  *               <tr>
621
  *                 <td bgcolor="#ffffff" valign="top">3-6</td>
622
  *                 <td bgcolor="#ffffff" valign="top">Number of sectors</td>
623
  *               </tr>
624
  *               <tr>
625
  *                 <td bgcolor="#ffffff" valign="top">7</td>
626
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
627
  *               </tr>
628
  *             </table>
629
  *           </td>
630
  *         </tr>
631
  *         <tr>
632
  *           <td bgcolor="#ffffff" valign="top">VR 0x41</td>
633
  *           <td bgcolor="#ffffff" valign="top">Read one sector from Flash</td>
634
  *         </tr>
635
  *         <tr>
636
  *           <td bgcolor="#ffffff" valign="top">VC 0x42</td>
637
  *           <td bgcolor="#ffffff" valign="top">Write one sector to Flash</td>
638
  *         </tr>
639
  *       </table>
640
  *     </td>
641
  *   </tr>
642
  *   <tr>
643
  *     <td bgcolor="#ffffff" valign="top">1.2</td>
644
  *     <td bgcolor="#ffffff" valign="top" colspan=2>Indicates an FX3 firmware</td>
645
  *   </tr>
646
  *   <tr>
647
  *     <td bgcolor="#ffffff" valign="top">1.3</td>
648
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
649
  *       Debug helper support<p>
650
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
651
  *         <tr>
652
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
653
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
654
  *         </tr>
655
  *         <tr>
656
  *           <td bgcolor="#ffffff" valign="top">VR 0x28</td>
657
  *           <td bgcolor="#ffffff" valign="top">Read debug message given by index (value<<16 | index) Returns:
658
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
659
  *               <tr>
660
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
661
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
662
  *               </tr>
663
  *               <tr>
664
  *                 <td bgcolor="#ffffff" valign="top">0</td>
665
  *                 <td bgcolor="#ffffff" valign="top">Error code (!= 0 if fatal error occurred)</td>
666
  *               </tr>
667
  *               <tr>
668
  *                 <td bgcolor="#ffffff" valign="top">1..4</td>
669
  *                 <td bgcolor="#ffffff" valign="top">Index of last message in buffer</td>
670
  *               </tr>
671
  *               <tr>
672
  *                 <td bgcolor="#ffffff" valign="top">5..6</td>
673
  *                 <td bgcolor="#ffffff" valign="top">Number of messages in buffer</td>
674
  *               </tr>
675
  *               <tr>
676
  *                 <td bgcolor="#ffffff" valign="top">7..8</td>
677
  *                 <td bgcolor="#ffffff" valign="top">Size if the message</td>
678
  *               </tr>
679
  *               <tr>
680
  *                 <td bgcolor="#ffffff" valign="top">9</td>
681
  *                 <td bgcolor="#ffffff" valign="top">Type of the message</td>
682
  *               </tr>
683
  *               <tr>
684
  *                 <td bgcolor="#ffffff" valign="top">10..</td>
685
  *                 <td bgcolor="#ffffff" valign="top">Message data</td>
686
  *               </tr>
687
  *             </table>
688
  *           </td>
689
  *         </tr>
690
  *         <tr>
691
  *           <td bgcolor="#ffffff" valign="top">VR 0x29</td>
692
  *           <td bgcolor="#ffffff" valign="top">Return USB 3.0 errors
693
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
694
  *               <tr>
695
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
696
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
697
  *               </tr>
698
  *               <tr>
699
  *                 <td bgcolor="#ffffff" valign="top">0..1</td>
700
  *                 <td bgcolor="#ffffff" valign="top">Send errors</td>
701
  *               </tr>
702
  *               <tr>
703
  *                 <td bgcolor="#ffffff" valign="top">2..3</td>
704
  *                 <td bgcolor="#ffffff" valign="top">Receive errors</td>
705
  *               </tr>
706
  *             </table>
707
  *           </td>
708
  *         </tr>
709
  *       </table>
710
  *     </td>
711
  *   </tr>
712
  *   <tr>
713
  *     <td bgcolor="#ffffff" valign="top">1.4</td>
714
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
715
  *       Default firmware interface<p>
716
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
717
  *         <tr>
718
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
719
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
720
  *         </tr>
721
  *         <tr>
722
  *           <td bgcolor="#ffffff" valign="top">VC 0x60</td>
723
  *           <td bgcolor="#ffffff" valign="top">Reset</td>
724
  *         </tr>
725
  *         <tr>
726
  *           <td bgcolor="#ffffff" valign="top">VR 0x61</td>
727
  *           <td bgcolor="#ffffff" valign="top">Read/write GPIO's:
728
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
729
  *               <tr>
730
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
731
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
732
  *               </tr>
733
  *               <tr>
734
  *                 <td bgcolor="#ffffff" valign="top">0</td>
735
  *                 <td bgcolor="#ffffff" valign="top">GPIO state (bits 0..3)</td>
736
  *               </tr>
737
  *             </table>
738
  *           </td>
739
  *         </tr>
740
  *         <tr>
741
  *           <td bgcolor="#ffffff" valign="top">VC 0x62</td>
742
  *           <td bgcolor="#ffffff" valign="top">Write to low speed interface</td>
743
  *         </tr>
744
  *         <tr>
745
  *           <td bgcolor="#ffffff" valign="top">VC 0x63</td>
746
  *           <td bgcolor="#ffffff" valign="top">Read from low speed interface</td>
747
  *         </tr>
748
  *         <tr>
749
  *           <td bgcolor="#ffffff" valign="top">VR 0x64</td>
750
  *           <td bgcolor="#ffffff" valign="top">Return Default Interface information:
751
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
752
  *               <tr>
753
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
754
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
755
  *               </tr>
756
  *               <tr>
757
  *                 <td bgcolor="#ffffff" valign="top">0</td>
758
  *                 <td bgcolor="#ffffff" valign="top">Version</td>
759
  *               </tr>
760
  *               <tr>
761
  *                 <td bgcolor="#ffffff" valign="top">1</td>
762
  *                 <td bgcolor="#ffffff" valign="top">Output Endpoint of the high speed interface</td>
763
  *               </tr>
764
  *               <tr>
765
  *                 <td bgcolor="#ffffff" valign="top">2</td>
766
  *                 <td bgcolor="#ffffff" valign="top">Input Endpoint of the high speed interface</td>
767
  *               </tr>
768
  *             </table>
769
  *           </td>
770
  *         </tr>
771
  *       </table>
772
  *     </td>
773
  *   </tr>
774
  * </table>
775
  * @see ZtexDevice1
776
  * @see Ztex1
777
  */
778
 
779
public class Ztex1v1 extends Ztex1 {
780
    /** * Capability index for EEPROM support. */
781
    public static final int CAPABILITY_EEPROM = 0;
782
    /** * Capability index for FPGA configuration support. */
783
    public static final int CAPABILITY_FPGA = 1;
784
    /** * Capability index for FLASH memory support. */
785
    public static final int CAPABILITY_FLASH = 2;
786
    /** * Capability index for DEBUG helper support. */
787
    public static final int CAPABILITY_DEBUG = 3;
788
    /** * Capability index for AVR XMEGA support. */
789
    public static final int CAPABILITY_XMEGA = 4;
790
    /** * Capability index for AVR XMEGA support. */
791
    public static final int CAPABILITY_HS_FPGA = 5;
792
    /** * Capability index for AVR XMEGA support. */
793
    public static final int CAPABILITY_MAC_EEPROM = 6;
794
    /** * Capability index for multi FPGA support */
795
    public static final int CAPABILITY_MULTI_FPGA = 7;
796
    /** * Capability index for Temperature sensor support */
797
    public static final int CAPABILITY_TEMP_SENSOR = 8+0;
798
    /** * Capability index for 2nd FLASH memory support. */
799
    public static final int CAPABILITY_FLASH2 = 8+1;
800
    /** * Capability index for FX3 firmware */
801
    public static final int CAPABILITY_FX3 = 8+2;
802
    /** * Capability index for debug helper 2 */
803
    public static final int CAPABILITY_DEBUG2 = 8+3;
804
    /** * Capability index for default firmware interface */
805
    public static final int CAPABILITY_DEFAULT = 8+4;
806
 
807
    /** * The names of the capabilities */
808
    public static final String capabilityStrings[] = {
809
        "EEPROM read/write" ,
810
        "FPGA configuration" ,
811
        "Flash memory support",
812
        "Debug helper",
813
        "XMEGA support",
814
        "High speed FPGA configuration",
815
        "MAC EEPROM read/write",
816
        "Multi FPGA support",
817
 
818
        "Temperature Sensor support" ,
819
        "2nd Flash memory support",
820
        "FX3 firmware",
821
        "Debug helper 2",
822
        "Default firmware interface"
823
    };
824
 
825
    /** * Enables extra FPGA configuration checks. Certain Bistream settings may cause false warnings.  */
826
    public boolean enableExtraFpgaConfigurationChecks = false;
827
 
828
    private boolean fpgaConfigured = false;
829
    private int fpgaChecksum = 0;
830
    private int fpgaBytes = 0;
831
    private int fpgaInitB = 0;
832
    private int fpgaFlashResult = 255;
833
    private int fpgaFlash2Result = 255;
834
    private boolean fpgaFlashBitSwap = false;
835
 
836
    /** * Number of bytes written to EEPROM. (Obtained by {@link #eepromState()}.) */
837
    public int eepromBytes = 0;
838
    /** * Checksum of the last EEPROM transfer. (Obtained by {@link #eepromState()}.) */
839
    public int eepromChecksum = 0;
840
 
841
    private int flashEnabled = -1;
842
    private int flashSectorSize = -1;
843
    private int flashSectors = -1;
844
 
845
    private int flash2Enabled = -1;
846
    private int flash2SectorSize = -1;
847
    private int flash2Sectors = -1;
848
 
849
    /** * Last Flash error code obtained by {@link #flashState()}. See FLASH_EC_* for possible error codes. */
850
    public int flashEC = 0;
851
    /** * Last 2nd Flash error code obtained by {@link #flashState()}. See FLASH_EC_* for possible error codes. */
852
    public int flash2EC = 0;
853
    /** * Means no error. */
854
    public static final int FLASH_EC_NO_ERROR = 0;
855
    /** * Signals an error while attempting to execute a command. */
856
    public static final int FLASH_EC_CMD_ERROR = 1;
857
    /** * Signals that a timeout occurred. */
858
    public static final int FLASH_EC_TIMEOUT = 2;
859
    /** * Signals that Flash memory it busy. */
860
    public static final int FLASH_EC_BUSY = 3;
861
    /** * Signals that another Flash operation is pending. */
862
    public static final int FLASH_EC_PENDING = 4;
863
    /** * Signals an error while attempting to read from Flash. */
864
    public static final int FLASH_EC_READ_ERROR = 5;
865
    /** * Signals an error while attempting to write to Flash. */
866
    public static final int FLASH_EC_WRITE_ERROR = 6;
867
    /** * Signals the installed Flash memory is not supported. */
868
    public static final int FLASH_EC_NOTSUPPORTED = 7;
869
    /** * Signals a runtime error of the firmware. */
870
    public static final int FLASH_EC_RUNTIME = 8;
871
 
872
    private int debugStackSize = -1;
873
    private int debugMsgSize = -1;
874
    private int debugLastMsg = 0;
875
    /** * Is set by {@link #debugReadMessages(boolean,byte[])} and contains the number of new messages. */
876
    public int debugNewMessages = 0;
877
 
878
    private int xmegaFlashPages = -1;
879
    private int xmegaEepromPages = -1;
880
    private int xmegaFlashPageSize;
881
    private int xmegaEepromPageSize;
882
 
883
    /** * Last ATxmega error code obtained by {@link #xmegaState()}. See XMEGA_EC_* for possible error codes. */
884
    public int xmegaEC = 0;
885
    /** * Means no error. */
886
    public static final int XMEGA_EC_NO_ERROR = 0;
887
    /** * Signals a PDI read error. */
888
    public static final int XMEGA_EC_PDI_READ_ERROR = 1;
889
    /** * Signals that an NVM timeout occurred. */
890
    public static final int XMEGA_EC_NVM_TIMEOUT = 2;
891
    /** * Signals that the ATxmega controller is not supported. */
892
    public static final int XMEGA_EC_INVALID_DEVICE = 3;
893
    /** * Signals an address error (invalid address or wrong page size). */
894
    public static final int XMEGA_EC_ADDRESS_ERROR = 4;
895
    /** * Signals that the NVM is busy. */
896
    public static final int XMEGA_EC_NVM_BUSY = 5;
897
 
898
    private int numberOfFpgas = -1;
899
    private int selectedFpga = -1;
900
    private boolean parallelConfigSupport = false;
901
 
902
    private long lastTempSensorReadTime = 0;
903
    private byte[] tempSensorBuf = new byte[9];
904
    /** * smallest temperature sensor update interval in ms */
905
    public int tempSensorUpdateInterval = 100;
906
 
907
    private int debug2LastIdx = -1;
908
    private int debug2EC = -1;
909
    private int debug2Cnt = -1;
910
    /** * Index of next log entry (messages of type 1 and 2) to be read. */
911
    public int debug2LogIdx = 0;
912
    /** * USB 3.0 send error count. This variable is set by {@link #getUsb3Errors()}. */
913
    public int usb3SndErrors = 0;
914
    /** * USB 3.0 receive error count. This variable is set by {@link #getUsb3Errors()}. */
915
    public int usb3RcvErrors = 0;
916
 
917
    // default interface stuff
918
    private int defaultVersion = -1;   // 0 means not present, <0 mean unchecked
919
    private int defaultSubVersion = -1;
920
    private int defaultInEP = -1;
921
    private int defaultOutEP = -1;
922
    /** * disable update warnings. */
923
    public boolean defaultDisableWarnings = false;
924
    /** * version number of the latest default interface. */
925
    public final int defaultLatestVersion = 1;
926
    /** * sub-version number of the latest default interface. */
927
    public final int defaultLatestSubVersion = 4;
928
 
929
/**
930
  * The configuration data structure
931
  * is initialized if this kind of data is present in MAC EEPROM.
932
  * In this case MAC EEPROM writes to addresses 0 to 79 are disabled, see {@link #macEepromWrite(int,byte[],int)}.
933
  * In order to override this behavior set this variable to null.
934
  * If no configuration data is present {@link #config} is null.
935
  */
936
    public ConfigData config;
937
 
938
// ******* Ztex1v1 *************************************************************
939
/**
940
  * Constructs an instance from a given device.
941
  * @param pDev The given device.
942
  * @throws UsbException if an communication error occurred.
943
  */
944
    public Ztex1v1 ( ZtexDevice1 pDev ) throws UsbException {
945
        super ( pDev );
946
    }
947
 
948
// ******* init ****************************************************************
949
/**
950
  * Initializates the class.
951
  * @throws UsbException if an communication error occurred.
952
  */
953
    protected void init () throws UsbException {
954
        super.init();
955
        config = new ConfigData ();
956
        try {
957
            if ( ! config.connect( this ) )
958
                config = null;
959
        }
960
        catch ( Exception e ) {
961
            config = null;
962
        }
963
    }
964
 
965
// ******* valid ***************************************************************
966
/**
967
  * Returns true if ZTEX interface 1 is available.
968
  * @return true if ZTEX interface 1 is available.
969
  */
970
    public boolean valid ( ) {
971
        return dev().valid() && dev().interfaceVersion()==1;
972
    }
973
 
974
/**
975
  * Returns true if ZTEX interface 1 and capability i.j are available.
976
  * @param i byte index of the capability
977
  * @param j bit index of the capability
978
  * @return true if ZTEX interface 1 and capability i.j are available.
979
  */
980
    public boolean valid ( int i, int j) {
981
        return dev().valid() && dev().interfaceVersion()==1 && dev().interfaceCapabilities(i,j);
982
    }
983
 
984
// ******* compatible **********************************************************
985
/**
986
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.<br>
987
  * The given product ID is compatible
988
  * <pre>if ( this.productId(0)==0 || productId0<=0 || this.productId(0)==productId0 ) &&
989
   ( this.productId(0)==0 || productId1<=0 || this.productId(1)==productId1 ) &&
990
   ( this.productId(2)==0 || productId2<=0 || this.productId(2)==productId2 ) &&
991
   ( this.productId(3)==0 || productId3<=0 || this.productId(3)==productId3 ) </pre>
992
  * @param productId0 Byte 0 of the given product ID
993
  * @param productId1 Byte 1 of the given product ID
994
  * @param productId2 Byte 2 of the given product ID
995
  * @param productId3 Byte 3 of the given product ID
996
  * @return true if the given product ID is compatible and interface 1 is supported.
997
  */
998
    public boolean compatible ( int productId0, int productId1, int productId2, int productId3 ) {
999
        return dev().valid() && dev().compatible ( productId0, productId1, productId2, productId3 ) && dev().interfaceVersion()==1;
1000
    }
1001
 
1002
// ******* checkValid **********************************************************
1003
/**
1004
  * Checks whether ZTEX descriptor 1 is available and interface 1 is supported.
1005
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
1006
  */
1007
    public void checkValid () throws InvalidFirmwareException {
1008
        super.checkValid();
1009
        if ( dev().interfaceVersion() != 1 )
1010
            throw new InvalidFirmwareException(this, "Wrong interface: " + dev().interfaceVersion() + ", expected: 1" );
1011
    }
1012
 
1013
// ******* checkCapability *****************************************************
1014
/**
1015
  * Checks whether ZTEX descriptor 1 is available and interface 1 and a given capability are supported.
1016
  * @param i byte index of the capability
1017
  * @param j bit index of the capability
1018
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
1019
  * @throws CapabilityException if the given capability is not supported.
1020
  */
1021
    public void checkCapability ( int i, int j ) throws InvalidFirmwareException, CapabilityException {
1022
        checkValid();
1023
        if ( ! dev().interfaceCapabilities(i,j) ) {
1024
            int k = i*8 + j;
1025
            if ( k>=0 && k<capabilityStrings.length )
1026
            throw new CapabilityException( this, ( k>=0 && k<=capabilityStrings.length ) ? capabilityStrings[k] : ("Capabilty " + i + "," + j) );
1027
        }
1028
    }
1029
 
1030
/**
1031
  * Checks whether ZTEX descriptor 1 is available and interface 1 and a given capability are supported.
1032
  * @param i capability index (0..47)
1033
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
1034
  * @throws CapabilityException if the given capability is not supported.
1035
  */
1036
    public void checkCapability ( int i ) throws InvalidFirmwareException, CapabilityException {
1037
        checkCapability(i/8, i%8);
1038
    }
1039
 
1040
// ******* InterfaceCapabilities ***********************************************
1041
/**
1042
  * Returns interface capability bit.
1043
  * @return interface capability bit.
1044
  * @param i capability index (0..47)
1045
  */
1046
    public boolean InterfaceCapabilities ( int i ) {
1047
        return dev().interfaceCapabilities(i/8, i%8);
1048
    }
1049
 
1050
// ******* checkCompatible *****************************************************
1051
/**
1052
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.
1053
  * See {@link #compatible(int,int,int,int)}.
1054
  * @param productId0 Byte 0 of the given product ID
1055
  * @param productId1 Byte 1 of the given product ID
1056
  * @param productId2 Byte 2 of the given product ID
1057
  * @param productId3 Byte 3 of the given product ID
1058
  * @throws InvalidFirmwareException if the given product ID is not compatible or interface 1 is not supported.
1059
  */
1060
    public void checkCompatible ( int productId0, int productId1, int productId2, int productId3 ) throws InvalidFirmwareException {
1061
        checkValid();
1062
        if ( ! dev().compatible ( productId0, productId1, productId2, productId3 ) )
1063
            throw new InvalidFirmwareException(this, "Incompatible Product ID");
1064
    }
1065
 
1066
// ******* getFpgaState ********************************************************
1067
    private void getFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
1068
        byte[] buffer = new byte[9];
1069
        checkCapability(CAPABILITY_FPGA);
1070
        vendorRequest2(0x30, "getFpgaState", buffer, 9);
1071
        fpgaConfigured = buffer[0] == 0;
1072
        fpgaChecksum = buffer[1] & 0xff;
1073
        fpgaBytes = ((buffer[5] & 0xff)<<24) | ((buffer[4] & 0xff)<<16) | ((buffer[3] & 0xff)<<8) | (buffer[2] & 0xff);
1074
        fpgaInitB = buffer[6] & 0xff;
1075
        fpgaFlashResult = buffer[7];
1076
        fpgaFlashBitSwap = buffer[8] != 0;
1077
    }
1078
 
1079
// ******* printFpgaState ******************************************************
1080
/**
1081
  * Prints out the FPGA state.
1082
  * @throws InvalidFirmwareException if interface 1 is not supported.
1083
  * @throws UsbException if a communication error occurs.
1084
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1085
  */
1086
    public void printFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
1087
 
1088
        final String flashResultStr[] = {
1089
         "Configuration successful",
1090
         "FPGA already configured",
1091
         "Flash error",
1092
         "No bitstream found",
1093
         "Configuration error"
1094
        };
1095
 
1096
        getFpgaState();
1097
        System.out.println( "size=" + fpgaBytes + ";  checksum=" + fpgaChecksum + "; INIT_B_HIST=" + fpgaInitB +"; flash_configuration_result=" + fpgaFlashResult +
1098
          (fpgaFlashResult>=0 && fpgaFlashResult<flashResultStr.length ? " ("+flashResultStr[fpgaFlashResult]+")" : "" )
1099
        );
1100
    }
1101
 
1102
// ******* getFpgaConfiguration ************************************************
1103
/**
1104
  * Returns true if the FPGA is configured.
1105
  * @return true if the FPGA is configured.
1106
  * @throws InvalidFirmwareException if interface 1 is not supported.
1107
  * @throws UsbException if a communication error occurs.
1108
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1109
  */
1110
    public boolean getFpgaConfiguration () throws UsbException, InvalidFirmwareException, CapabilityException {
1111
        getFpgaState ();
1112
        return fpgaConfigured;
1113
    }
1114
 
1115
// ******* getFpgaConfigurationStr *********************************************
1116
/**
1117
  * Returns a string that indicates the FPGA configuration status.
1118
  * @return a string that indicates the FPGA configuration status.
1119
  * @throws InvalidFirmwareException if interface 1 is not supported.
1120
  * @throws UsbException if a communication error occurs.
1121
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1122
  */
1123
    public String getFpgaConfigurationStr () throws UsbException, InvalidFirmwareException, CapabilityException {
1124
        getFpgaState ();
1125
        return fpgaConfigured ? "FPGA configured" : "FPGA unconfigured";
1126
    }
1127
 
1128
// ******* resetFGPA ***********************************************************
1129
/**
1130
  * Resets the FPGA.
1131
  * @throws InvalidFirmwareException if interface 1 is not supported.
1132
  * @throws UsbException if a communication error occurs.
1133
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1134
  */
1135
    public void resetFpga () throws UsbException, InvalidFirmwareException, CapabilityException {
1136
        checkCapability(CAPABILITY_FPGA);
1137
        vendorCommand(0x31, "resetFpga" );
1138
    }
1139
 
1140
 
1141
// ******* detectBitstreamBitOrder *********************************************
1142
    private int detectBitstreamBitOrder ( byte[] buf ) {
1143
        for ( int i=0; i<buf.length-3; i++ ) {
1144
            if ( ((buf[i] & 255)==0xaa) && ((buf[i+1] & 255)==0x99) && ((buf[i+2] & 255)==0x55) && ((buf[i+3] & 255)==0x66) )
1145
                return 1;
1146
            if ( ((buf[i] & 255)==0x55) && ((buf[i+1] & 255)==0x99) && ((buf[i+2] & 255)==0xaa) && ((buf[i+3] & 255)==0x66) )
1147
                return 0;
1148
        }
1149
        System.err.println("Warning: Unable to determine bitstream bit order: no signature found");
1150
        return 0;
1151
    }
1152
 
1153
// ******* detectBitstreamStart ************************************************
1154
    private int detectBitstreamStart ( byte[] buf ) {
1155
        int l=0;
1156
        for ( int i=0; i<buf.length-3; i++ ) {
1157
            if ( (l>=4) && ((buf[i+1] & 255)==0x99) && ((buf[i+3] & 255)==0x66) ) {
1158
                if ( ((buf[i] & 255)==0xaa) && ((buf[i+2] & 255)==0x55) )
1159
                    return i-l;
1160
                if ( ((buf[i] & 255)==0x55) && ((buf[i+2] & 255)==0xaa) )
1161
                    return i-l;
1162
            }
1163
            l = buf[i]==-1 ? l+1 : 0;
1164
        }
1165
        System.err.println("Warning: Unable to determine start of raw bitstream");
1166
        return 0;
1167
    }
1168
 
1169
// ******* swapBits ************************************************************
1170
    private void swapBits ( byte[] buf, int length ) {
1171
        for (int i=0; i<length; i++ ) {
1172
            byte b = buf[i];
1173
            buf[i] = (byte) ( ((b & 128) >> 7) |
1174
                              ((b &  64) >> 5) |
1175
                              ((b &  32) >> 3) |
1176
                              ((b &  16) >> 1) |
1177
                              ((b &   8) << 1) |
1178
                              ((b &   4) << 3) |
1179
                              ((b &   2) << 5) |
1180
                              ((b &   1) << 7) );
1181
        }
1182
    }
1183
 
1184
// ******* configureFpgaLS *****************************************************
1185
/**
1186
  * Upload a Bitstream to the FPGA using low speed mode.
1187
  * @param inputStream for reading the Bitstream.
1188
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
1189
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1190
  * @return Configuration time in ms.
1191
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1192
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
1193
  * @throws AlreadyConfiguredException if the FPGA is already configured.
1194
  * @throws InvalidFirmwareException if interface 1 is not supported.
1195
  * @throws UsbException if a communication error occurs.
1196
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1197
  */
1198
    public long configureFpgaLS ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
1199
        final int transactionBytes = 2048;
1200
        long t0 = 0;
1201
 
1202
        checkCapability(CAPABILITY_FPGA);
1203
 
1204
        if ( !force && getFpgaConfiguration() )
1205
            throw new AlreadyConfiguredException();
1206
 
1207
// read the Bitstream file      
1208
        ByteBuffer[] buffers = new ByteBuffer[64*1024*1024/transactionBytes];
1209
        byte[] buf = new byte[transactionBytes];
1210
        int size = 0;
1211
        int cs = 0;
1212
        try {
1213
            int j = transactionBytes;
1214
            for ( int i=0; i<buffers.length && j==transactionBytes; i++ ) {
1215
                int k;
1216
                j = 0;
1217
                do {
1218
                    k = inputStream.read( buf, j, transactionBytes-j );
1219
                    if ( k < 0 ) k = 0;
1220
                    j += k;
1221
                }
1222
                while ( j<transactionBytes && k>0 );
1223
 
1224
                if ( j < transactionBytes && j % 64 == 0 )       // ensures size % 64 != 0
1225
                    j+=1;
1226
 
1227
                if ( (i==0) && ( bs<0 || bs>1 ) ) {
1228
                    bs = detectBitstreamBitOrder ( buf );
1229
//                  System.out.println(bs);
1230
                }
1231
 
1232
                if ( bs == 1 ) swapBits(buf, j);
1233
 
1234
                buffers[i] = allocateByteBuffer(buf, 0, j);
1235
 
1236
                for ( k=0; k<j; k++ )
1237
                    cs = ( cs + (buf[k] & 0xff) ) & 0xff;
1238
 
1239
                size += j;
1240
            }
1241
 
1242
            try {
1243
                inputStream.close();
1244
            }
1245
            catch ( Exception e ) {
1246
            }
1247
        }
1248
        catch (IOException e) {
1249
            throw new BitstreamReadException(e.getLocalizedMessage());
1250
        }
1251
        if ( size < 64 || size % 64 == 0 )
1252
            throw new BitstreamReadException("Invalid file size: " + size );
1253
 
1254
 
1255
// upload the Bitstream file    
1256
        for ( int tries=10; tries>0; tries-- ) {
1257
 
1258
            resetFpga();
1259
 
1260
            try {
1261
                t0 = -new Date().getTime();
1262
                bs = 0;
1263
 
1264
                for ( int i=0; i<buffers.length && i*transactionBytes < size; i++ ) {
1265
                    int j = size-i*transactionBytes;
1266
                    if (j>transactionBytes)
1267
                        j = transactionBytes;
1268
                    vendorCommand2(0x32, "sendFpgaData", 0,0, buffers[i]);
1269
                    bs+=j;
1270
                }
1271
 
1272
                getFpgaState();
1273
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+bs+")   fpgaChecksum="+fpgaChecksum + " ("+cs+")   fpgaInitB="+fpgaInitB );
1274
                if ( ! fpgaConfigured ) {
1275
                    throw new BitstreamUploadException( "FPGA configuration failed: DONE pin does not go high (size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes got lost;  checksum="
1276
                        + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB +")" );
1277
                }
1278
                if ( enableExtraFpgaConfigurationChecks ) {
1279
                    if ( fpgaBytes!=0 && fpgaBytes!=bs )
1280
                        System.err.println("Warning: Possible FPGA configuration data loss: " + (bs - fpgaBytes) + " bytes got lost");
1281
                    if ( fpgaInitB!=222 )
1282
                        System.err.println("Warning: Possible Bitstream CRC error: INIT_B_HIST=" + fpgaInitB );
1283
                }
1284
//              System.out.println( "FPGA configuration: size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes got lost;  checksum=" + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB );
1285
 
1286
                tries = 0;
1287
                t0 += new Date().getTime();
1288
 
1289
            }
1290
            catch ( BitstreamUploadException e ) {
1291
                if ( tries>1 )
1292
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1293
                else
1294
                    throw e;
1295
            }
1296
        }
1297
 
1298
        try {
1299
            Thread.sleep( 100 );
1300
        }
1301
        catch ( InterruptedException e) {
1302
        }
1303
 
1304
        return t0;
1305
    }
1306
 
1307
 
1308
/**
1309
  * Upload a Bitstream to the FPGA using low speed mode.
1310
  * @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).
1311
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
1312
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
1313
  * @return Configuration time in ms.
1314
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1315
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
1316
  * @throws AlreadyConfiguredException if the FPGA is already configured.
1317
  * @throws InvalidFirmwareException if interface 1 is not supported.
1318
  * @throws UsbException if a communication error occurs.
1319
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
1320
  */
1321
    public long configureFpgaLS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
1322
        try {
1323
            return configureFpgaLS( JInputStream.getInputStream( fwFileName ), force, bs );
1324
        }
1325
        catch (IOException e) {
1326
            throw new BitstreamReadException(e.getLocalizedMessage());
1327
        }
1328
    }
1329
 
1330
// ******* eepromState *********************************************************
1331
// returns true if EEPROM is ready
1332
/**
1333
  * Reads the current EEPROM status.
1334
  * This method also sets the varibles {@link #eepromBytes} and {@link #eepromChecksum}.
1335
  * @throws InvalidFirmwareException if interface 1 is not supported.
1336
  * @throws UsbException if a communication error occurs.
1337
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1338
  * @return true if EEPROM is ready.
1339
  */
1340
    public boolean eepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1341
        byte[] buf = new byte[4];
1342
        checkCapability(CAPABILITY_EEPROM);
1343
        vendorRequest2(0x3A, "EEPROM State", 0, 0, buf, 4);
1344
        eepromBytes = (buf[0] & 255) | (buf[1] & 255)<<8;
1345
        eepromChecksum = buf[2] & 255;
1346
        return buf[3] == 0;
1347
    }
1348
 
1349
// ******* eepromWrite *********************************************************
1350
/**
1351
  * Writes data to the EEPROM.
1352
  * @param addr The destination address of the EEPROM.
1353
  * @param buf The data.
1354
  * @param length The amount of bytes to be sent.
1355
  * @throws InvalidFirmwareException if interface 1 is not supported.
1356
  * @throws UsbException if a communication error occurs.
1357
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1358
  */
1359
    public void eepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1360
        checkCapability(CAPABILITY_EEPROM);
1361
        if ( (addr & 63) != 0 ) {
1362
            int i = Math.min(length, 64-(addr & 63));
1363
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, i );
1364
            try {
1365
                Thread.sleep( 10 );
1366
            }
1367
            catch ( InterruptedException e) {
1368
            }
1369
            addr+=i;
1370
            length-=i;
1371
            if ( length > 0 ) {
1372
                byte[] buf2 = new byte[length];
1373
                for (int j=0; j<length; j++ )
1374
                    buf2[j] = buf[i+j];
1375
                vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf2, length );
1376
            }
1377
        }
1378
        else {
1379
            vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, length );
1380
        }
1381
 
1382
        try {
1383
                Thread.sleep( 10 );
1384
        }
1385
            catch ( InterruptedException e) {
1386
        }
1387
    }
1388
 
1389
// ******* eepromRead **********************************************************
1390
/**
1391
  * Reads data from the EEPROM.
1392
  * @param addr The source address of the EEPROM.
1393
  * @param buf A buffer for the storage of the data.
1394
  * @param length The amount of bytes to be read.
1395
  * @throws InvalidFirmwareException if interface 1 is not supported.
1396
  * @throws UsbException if a communication error occurs.
1397
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1398
  */
1399
    public void eepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
1400
        checkCapability(CAPABILITY_EEPROM);
1401
        vendorRequest2( 0x38, "EEPROM Read", addr, 0, buf, length );             // sometimes a little bit slow
1402
        try {
1403
            Thread.sleep( 10 );
1404
        }
1405
        catch ( InterruptedException e) {
1406
        }
1407
    }
1408
 
1409
 
1410
// ******* eepromUploadFirmware ********************************************************
1411
//  returns upload time in ms
1412
/**
1413
  * Upload the firmware to the EEPROM.
1414
  * In order to start the uploaded firmware the device must be reset.
1415
  * @param imgFile The firmware image.
1416
  * @param force Skips the compatibility check if true.
1417
  * @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.)
1418
  * @throws InvalidFirmwareException if interface 1 is not supported.
1419
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1420
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1421
  */
1422
    private long eepromUploadFirmware ( ImgFile imgFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1423
        final int pagesMax = 256;
1424
        final int pageSize = 256;
1425
        int pages = 0;
1426
        byte[][] buffer = new byte[pagesMax][];
1427
 
1428
        checkCapability(CAPABILITY_EEPROM);
1429
 
1430
//      imgFile.dataInfo(System.out);
1431
//      System.out.println(imgFile);
1432
 
1433
// check for compatibility
1434
        if ( (imgFile instanceof ZtexImgFile1) && (!force) && dev().valid() ) {
1435
            if ( ((ZtexImgFile1)imgFile).interfaceVersion() != 1 )
1436
                throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ((ZtexImgFile1)imgFile).interfaceVersion() );
1437
 
1438
            if ( ! dev().compatible ( ((ZtexImgFile1)imgFile).productId(0), ((ZtexImgFile1)imgFile).productId(1), ((ZtexImgFile1)imgFile).productId(2), ((ZtexImgFile1)imgFile).productId(3) ) )
1439
                throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev().productId())
1440
                    + "  Img File: " + ZtexDevice1.byteArrayString(((ZtexImgFile1)imgFile).productId()) );
1441
        }
1442
 
1443
        int vid = dev().usbVendorId();
1444
        int pid = dev().usbProductId();
1445
 
1446
        buffer[0] = new byte[pageSize];
1447
        buffer[0][0] = (byte) 0xc2;
1448
        buffer[0][1] = (byte) (vid & 255);
1449
        buffer[0][2] = (byte) ((vid >> 8) & 255);
1450
        buffer[0][3] = (byte) (pid & 255);
1451
        buffer[0][4] = (byte) ((pid >> 8) & 255);
1452
        buffer[0][5] = 0;
1453
        buffer[0][6] = 0;
1454
        buffer[0][7] = 65;
1455
 
1456
        int ptr = 8, i = 0;
1457
 
1458
        while ( i < imgFile.data.length ) {
1459
            if ( imgFile.data[i]>=0 && imgFile.data[i]<256 ) {                   // new data block
1460
                int j = 1;
1461
                while ( i+j<imgFile.data.length && imgFile.data[i+j]>=0 && imgFile.data[i+j]<256 )
1462
                    j++;
1463
 
1464
                for (int k=ptr/pageSize + 1; k < (ptr+j+9)/pageSize + 1; k++ )  // also considers 5 bytes for the last data block
1465
                    buffer[k] = new byte[pageSize];
1466
 
1467
                buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) ((j >> 8) & 255);
1468
                buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) (j & 255);                // length
1469
                buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((i >> 8) & 255);
1470
                buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) (i & 255);                // address
1471
                ptr+=4;
1472
                for ( int k=0; k<j; k++ )                                        // data
1473
                    buffer[(ptr+k)/pageSize][(ptr+k) % pageSize] = (byte) imgFile.data[i+k];
1474
                ptr+=j;
1475
                i+=j;
1476
            }
1477
            else {
1478
                i+=1;
1479
            }
1480
        }
1481
 
1482
        buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) 0x80;               // last data block
1483
        buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) 0x01;
1484
        buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) 0xe6;
1485
        buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) 0x00;
1486
        buffer[(ptr+3)/pageSize][(ptr+4) % pageSize] = (byte) 0x00;
1487
        ptr+=5;
1488
 
1489
 
1490
        long t0 = new Date().getTime();
1491
        byte[] rbuf = new byte[pageSize];
1492
 
1493
        for ( i=(ptr-1)/pageSize; i>=0; i-- ) {
1494
 
1495
            int k = (i+1)*pageSize < ptr ? pageSize : ptr-i*pageSize;
1496
            int cs = 0;
1497
            for (int j=0; j<k; j++ ) {
1498
                cs = ( cs + (buffer[i][j] & 255) ) & 255;
1499
            }
1500
 
1501
            for ( int tries=3; tries>0; tries-- ) {
1502
                try {
1503
                    eepromWrite(i*pageSize, buffer[i], k);
1504
                    eepromState();
1505
                    if ( eepromBytes!=k )
1506
                        throw new FirmwareUploadException("Error writing data to EEPROM: Wrote " + eepromBytes + " bytes instead of "  + k + " bytes" );
1507
                    if ( eepromChecksum!=cs )
1508
                        throw new FirmwareUploadException("Error writing data to EEPROM: Checksum error");
1509
 
1510
                    eepromRead(i*pageSize, rbuf, k);
1511
                    for (int j=0; j<k; j++ ) {
1512
                        if ( rbuf[j] != buffer[i][j] )
1513
                            throw new FirmwareUploadException("Error writing data to EEPROM: Verification failed");
1514
                    }
1515
                    tries = 0;
1516
                }
1517
                catch ( Exception e ) {
1518
                    if ( tries > 1 ) {
1519
                        System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1520
                    }
1521
                    else {
1522
                        throw new FirmwareUploadException(e.getLocalizedMessage());
1523
                    }
1524
                }
1525
            }
1526
        }
1527
 
1528
        return new Date().getTime() - t0;
1529
    }
1530
 
1531
 
1532
// ******* nvUploadFirmware ********************************************************
1533
/**
1534
  * Upload the firmware to the non-volatile memory.
1535
  * In order to start the uploaded firmware the device must be reset.
1536
  * @param imgFile The firmware image.
1537
  * @param force Skips the compatibility check if true.
1538
  * @return Upload time in ms.
1539
  * @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.)
1540
  * @throws InvalidFirmwareException if interface 1 is not supported.
1541
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1542
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1543
  * @see #nvDisableFirmware()
1544
  */
1545
    public long nvUploadFirmware ( ImgFile imgFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1546
        return dev().fx3() ? flashUploadFirmware(imgFile, force) : eepromUploadFirmware(imgFile, force);
1547
    }
1548
 
1549
/**
1550
  * @deprecated Replaced by {@link #nvUploadFirmware(ZtexImgFile1,boolean)}
1551
  */
1552
    @Deprecated public long eepromUpload ( ImgFile imgFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1553
        return nvUploadFirmware(imgFile,force);
1554
    }
1555
 
1556
//  returns upload time in ms
1557
/**
1558
  * Upload the firmware to the non-volatile memory.
1559
  * In order to start the uploaded firmware the device must be reset.
1560
  * @param imgFileName The file name of the firmware image in ihx or img format. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
1561
  * @param force Skips the compatibility check if true.
1562
  * @return Upload time in ms.
1563
  * @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.)
1564
  * @throws InvalidFirmwareException if interface 1 is not supported.
1565
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1566
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
1567
  * @see #nvDisableFirmware()
1568
  */
1569
    public long nvUploadFirmware ( String imgFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1570
// load the firmware file
1571
        ImgFile imgFile;
1572
        try {
1573
            try {
1574
                imgFile = new ZtexImgFile1( imgFileName );
1575
            }
1576
            catch ( IncompatibleFirmwareException e ) {
1577
                if ( !force ) throw e;
1578
                imgFile = new ImgFile( imgFileName );
1579
            }
1580
        }
1581
        catch ( IOException e ) {
1582
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1583
        }
1584
        catch ( ImgFileDamagedException e ) {
1585
            throw new FirmwareUploadException( e.getLocalizedMessage() );
1586
        }
1587
 
1588
        return nvUploadFirmware( imgFile, force );
1589
    }
1590
 
1591
/**
1592
  * @deprecated Replaced by {@link #nvUploadFirmware(String,boolean)}
1593
  */
1594
    @Deprecated public long eepromUpload ( String imgFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1595
        return nvUploadFirmware(imgFileName,force);
1596
    }
1597
 
1598
 
1599
// ******* eepromDisable ********************************************************
1600
/**
1601
  * Disables the firmware stored in the EEPROM.
1602
  * This is achived by writing a "0" to the address 0 of the EEPROM.
1603
  * @throws InvalidFirmwareException if interface 1 is not supported.
1604
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1605
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
1606
  */
1607
    private void eepromDisableFirmware ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1608
        byte[] buf = { 0 };
1609
 
1610
        for ( int tries=3; tries>0; tries-- ) {
1611
            try {
1612
                eepromWrite(0, buf, 1);
1613
 
1614
                eepromRead(0, buf, 1);
1615
                if ( buf[0] != 0 )
1616
                    throw new FirmwareUploadException("Error disabling EEPROM firmware: Verification failed");
1617
                tries = 0;
1618
 
1619
            }
1620
            catch ( Exception e ) {
1621
                if ( tries > 1 ) {
1622
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
1623
                }
1624
                else {
1625
                    throw new FirmwareUploadException(e.getLocalizedMessage());
1626
                }
1627
            }
1628
        }
1629
    }
1630
 
1631
/**
1632
  * @deprecated Replaced by {@link #nvDisableFirmware()}
1633
  */
1634
    @Deprecated public void eepromDisable ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1635
        nvDisableFirmware();
1636
    }
1637
 
1638
// ******* nvDisableFirmware ***************************************************
1639
/**
1640
  * Disables the firmware stored in the non-volatile memory.
1641
  * This is achived by writing a "0" to the address 0 of the memory.
1642
  * @throws InvalidFirmwareException if interface 1 is not supported.
1643
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
1644
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
1645
  */
1646
    public void nvDisableFirmware ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
1647
        if ( dev().fx3() ) {
1648
            flashDisableFirmware();
1649
        }
1650
        else {
1651
             eepromDisableFirmware();
1652
        }
1653
    }
1654
 
1655
 
1656
// ******* flashStrError *******************************************************
1657
/**
1658
  * Converts a given error code into a String.
1659
  * @param errNum The error code.
1660
  * @return an error message.
1661
  */
1662
    public static String flashStrError ( int errNum ) {
1663
        switch ( errNum ) {
1664
            case FLASH_EC_NO_ERROR:
1665
                return "USB error";
1666
            case FLASH_EC_CMD_ERROR:
1667
                return "Command error";
1668
            case FLASH_EC_TIMEOUT:
1669
                return "Timeout error";
1670
            case FLASH_EC_BUSY:
1671
                return "Busy";
1672
            case FLASH_EC_PENDING:
1673
                return "Another operation is pending";
1674
            case FLASH_EC_READ_ERROR:
1675
                return "Read error";
1676
            case FLASH_EC_WRITE_ERROR:
1677
                return "Write error";
1678
            case FLASH_EC_NOTSUPPORTED:
1679
                return "Not supported";
1680
            case FLASH_EC_RUNTIME:
1681
                return "Firmware runtime error";
1682
        }
1683
        return "Error " + errNum;
1684
    }
1685
 
1686
/**
1687
  * Gets the last Flash error from the device.
1688
  * @return an error message.
1689
  */
1690
    public String flashStrError ( ) {
1691
        try {
1692
            return flashStrError( getFlashEC() );
1693
        }
1694
        catch ( Exception e ) {
1695
            return "Unknown error (Error receiving errorcode: "+e.getLocalizedMessage() +")";
1696
        }
1697
    }
1698
 
1699
/**
1700
  * Gets the last 2nd Flash error from the device.
1701
  * @return an error message.
1702
  */
1703
    public String flash2StrError ( ) {
1704
        try {
1705
            return flashStrError( getFlash2EC() );
1706
        }
1707
        catch ( Exception e ) {
1708
            return "Unknown error (Error receiving errorcode: "+e.getLocalizedMessage() +")";
1709
        }
1710
    }
1711
 
1712
// ******* flashState **********************************************************
1713
/**
1714
  * Reads the the Flash memory status and information.
1715
  * This method also sets the variables {@link #flashEnabled()}, {@link #flashSectorSize()} and {@link #flashSectors()}.
1716
  * @return true if Flash memory is installed.
1717
  * @throws InvalidFirmwareException if interface 1 is not supported.
1718
  * @throws UsbException if a communication error occurs.
1719
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1720
  */
1721
    public boolean flashState () throws UsbException, InvalidFirmwareException, CapabilityException {
1722
        byte[] buf = new byte[8];
1723
        checkCapability(CAPABILITY_FLASH);
1724
 
1725
        // device may be busy due to initialization, we try it up to up to 4s
1726
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1727
        flashEC = buf[7] & 255;
1728
        int tries=20;
1729
        while ( flashEC==FLASH_EC_BUSY && tries>0 )
1730
        {
1731
            try {
1732
                Thread.sleep( 200 );
1733
            }
1734
            catch ( InterruptedException e) {
1735
            }
1736
            tries-=1;
1737
            vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1738
            flashEC = buf[7] & 255;
1739
        }
1740
        flashEnabled = buf[0] & 255;
1741
        flashSectorSize = flashEnabled == 1 ? ((buf[2] & 255) << 8) | (buf[1] & 255) : 0;
1742
        if ( (flashSectorSize & 0x8000) != 0 )
1743
            flashSectorSize = 1 << (flashSectorSize & 0x7fff);
1744
        flashSectors = flashEnabled == 1 ? ((buf[6] & 255) << 24) | ((buf[5] & 255) << 16) | ((buf[4] & 255) << 8) | (buf[3] & 255) : 0;
1745
        return flashEnabled == 1;
1746
    }
1747
 
1748
// ******* flash2State *********************************************************
1749
/**
1750
  * Reads the the 2nd Flash memory status and information.
1751
  * This method also sets the variables {@link #flash2Enabled()}, {@link #flash2SectorSize()} and {@link #flash2Sectors()}.
1752
  * @return true if 2nd Flash memory is installed.
1753
  * @throws InvalidFirmwareException if interface 1 is not supported.
1754
  * @throws UsbException if a communication error occurs.
1755
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
1756
  */
1757
    public boolean flash2State () throws UsbException, InvalidFirmwareException, CapabilityException {
1758
        byte[] buf = new byte[8];
1759
        checkCapability(CAPABILITY_FLASH2);
1760
 
1761
        // device may be busy due to initialization, we try it up to up to 4s
1762
        vendorRequest2(0x44, "Flash 2 State", 0, 0, buf, 8);
1763
        flash2EC = buf[7] & 255;
1764
        int tries=20;
1765
        while ( flash2EC==FLASH_EC_BUSY && tries>0 )
1766
        {
1767
            try {
1768
                Thread.sleep( 200 );
1769
            }
1770
            catch ( InterruptedException e) {
1771
            }
1772
            tries-=1;
1773
            vendorRequest2(0x44, "Flash 2 State", 0, 0, buf, 8);
1774
            flash2EC = buf[7] & 255;
1775
        }
1776
        flash2Enabled = buf[0] & 255;
1777
        flash2SectorSize = flash2Enabled == 1 ? ((buf[2] & 255) << 8) | (buf[1] & 255) : 0;
1778
        if ( (flash2SectorSize & 0x8000) != 0 )
1779
            flash2SectorSize = 1 << (flash2SectorSize & 0x7fff);
1780
        flash2Sectors = flash2Enabled == 1 ? ((buf[6] & 255) << 24) | ((buf[5] & 255) << 16) | ((buf[4] & 255) << 8) | (buf[3] & 255) : 0;
1781
        return flash2Enabled == 1;
1782
    }
1783
 
1784
// ******* getFlashEC **********************************************************
1785
// reads the current error code
1786
/**
1787
  * Gets the last Flash error from the device.
1788
  * @return The last error code.
1789
  * @throws InvalidFirmwareException if interface 1 is not supported.
1790
  * @throws UsbException if a communication error occurs.
1791
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
1792
  */
1793
    public int getFlashEC () throws UsbException, InvalidFirmwareException, CapabilityException {
1794
        byte[] buf = new byte[8];
1795
        checkCapability(CAPABILITY_FLASH);
1796
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
1797
        flashEC = buf[7] & 255;
1798
        return flashEC;
1799
    }
1800
 
1801
// ******* getFlash2EC *********************************************************
1802
// reads the current error code
1803
/**
1804
  * Gets the last 2nd Flash memory error from the device.
1805
  * @return The last error code.
1806
  * @throws InvalidFirmwareException if interface 1 is not supported.
1807
  * @throws UsbException if a communication error occurs.
1808
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
1809
  */
1810
    public int getFlash2EC () throws UsbException, InvalidFirmwareException, CapabilityException {
1811
        byte[] buf = new byte[8];
1812
        checkCapability(CAPABILITY_FLASH2);
1813
        vendorRequest2(0x44, "Flash 2 State", 0, 0, buf, 8);
1814
        flash2EC = buf[7] & 255;
1815
        return flash2EC;
1816
    }
1817
 
1818
 
1819
// ******* flashReadSector ****************************************************
1820
// read a integer number of sectors
1821
/**
1822
  * Reads a integer number of sectors from the Flash.
1823
  * @param sector The number of the first sector to be read.
1824
  * @param num The number of sectors to be read.
1825
  * @param buf A buffer for the storage of the data.
1826
  * @throws InvalidFirmwareException if interface 1 is not supported.
1827
  * @throws UsbException if a communication error occurs.
1828
  * @throws CapabilityException if Flash memory access is not possible.
1829
  * @throws IndexOutOfBoundsException If the buffer is to small.
1830
  */
1831
    public void flashReadSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1832
        if ( num<1 ) return;
1833
 
1834
        if ( buf.length < flashSectorSize() )
1835
            throw new IndexOutOfBoundsException( "Buffer is to small: " + buf.length + " < " + (num*flashSectorSize()) );
1836
 
1837
        checkCapability(CAPABILITY_FLASH);
1838
        if ( ! flashEnabled() )
1839
            throw new CapabilityException(this, "No Flash memory installed or");
1840
 
1841
        try {
1842
            if ( flashSectorSize()>2048 ) {
1843
                byte[] buf2 = new byte[2048];
1844
                int iz = (flashSectorSize-1) >> 11;
1845
                for (int sn=0; sn<num; sn++ ) {
1846
                    for (int i=0; i<iz; i++) {
1847
//                      System.out.println("r: "+i);
1848
                        vendorRequest2( 0x41, "Flash Read", sector, i==0 ? 0 : 256, buf2, 2048 );
1849
                        System.arraycopy(buf2,0, buf, sn*flashSectorSize + i*2048, 2048);
1850
                    }
1851
                    int len = flashSectorSize-iz*2048;
1852
                    vendorRequest2( 0x41, "Flash Read", sector, 512, buf2,  len);
1853
                    System.arraycopy(buf2,0, buf, sn*flashSectorSize + iz*2048, len);
1854
                }
1855
            }
1856
            else {
1857
                int nz = Math.max(1, 2048 / flashSectorSize);
1858
                byte[] buf2 = new byte[nz * flashSectorSize];
1859
                int bp = 0;
1860
                while ( num>0 ) {
1861
                    int n2 = Math.min(num,nz);
1862
                    vendorRequest2( 0x41, "Flash Read", sector, sector >> 16, buf2, flashSectorSize*n2 );
1863
                    System.arraycopy(buf2,0, buf, bp, flashSectorSize*n2);
1864
                    bp += flashSectorSize*n2;
1865
                    sector += n2;
1866
                }
1867
            }
1868
        }
1869
        catch ( UsbException e ) {
1870
            throw new UsbException( dev().dev(), "Flash Read: " + flashStrError() );
1871
        }
1872
    }
1873
 
1874
// read one sector
1875
/**
1876
  * Reads one sector from the Flash.
1877
  * @param sector The sector number to be read.
1878
  * @param buf A buffer for the storage of the data.
1879
  * @throws InvalidFirmwareException if interface 1 is not supported.
1880
  * @throws UsbException if a communication error occurs.
1881
  * @throws CapabilityException if Flash memory access is not possible.
1882
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
1883
  */
1884
    public void flashReadSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1885
        flashReadSector ( sector, 1, buf );
1886
    }
1887
 
1888
// ******* flash2ReadSector ***************************************************
1889
// read a integer number of sectors
1890
/**
1891
  * Reads a integer number of sectors from the 2nd Flash memory.
1892
  * @param sector The number of the first sector to be read.
1893
  * @param num The number of sectors to be read.
1894
  * @param buf A buffer for the storage of the data.
1895
  * @throws InvalidFirmwareException if interface 1 is not supported.
1896
  * @throws UsbException if a communication error occurs.
1897
  * @throws CapabilityException if 2nd Flash access is not possible.
1898
  * @throws IndexOutOfBoundsException If the buffer is to small.
1899
  */
1900
    public void flash2ReadSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1901
        if ( num<1 ) return;
1902
 
1903
        if ( buf.length < flash2SectorSize() )
1904
            throw new IndexOutOfBoundsException( "Buffer is to small: " + buf.length + " < " + (num*flash2SectorSize()) );
1905
 
1906
        checkCapability(CAPABILITY_FLASH2);
1907
        if ( ! flash2Enabled() )
1908
            throw new CapabilityException(this, "No 2nd Flash installed or");
1909
 
1910
        try {
1911
            if ( flash2SectorSize()>2048 ) {
1912
                byte[] buf2 = new byte[2048];
1913
                int iz = (flash2SectorSize-1) >> 11;
1914
                for (int sn=0; sn<num; sn++ ) {
1915
                    for (int i=0; i<iz; i++) {
1916
//                      System.out.println("r: "+i);
1917
                        vendorRequest2( 0x45, "Flash 2 Read", sector, i==0 ? 0 : 256, buf2, 2048 );
1918
                        System.arraycopy(buf2,0, buf, sn*flash2SectorSize + i*2048, 2048);
1919
                    }
1920
                    int len = flash2SectorSize-iz*2048;
1921
                    vendorRequest2( 0x45, "Flash 2 Read", sector, 512, buf2,  len);
1922
                    System.arraycopy(buf2,0, buf, sn*flash2SectorSize + iz*2048, len);
1923
                }
1924
            }
1925
            else {
1926
                int nz = Math.max(1, 2048 / flash2SectorSize);
1927
                byte[] buf2 = new byte[nz * flash2SectorSize];
1928
                int bp = 0;
1929
                while ( num>0 ) {
1930
                    int n2 = Math.min(num,nz);
1931
                    vendorRequest2( 0x45, "Flash 2 Read", sector, sector >> 16, buf2, flash2SectorSize*n2 );
1932
                    System.arraycopy(buf2,0, buf, bp, flash2SectorSize*n2);
1933
                    bp += flash2SectorSize*n2;
1934
                    sector += n2;
1935
                    num -= n2;
1936
                }
1937
            }
1938
        }
1939
        catch ( UsbException e ) {
1940
            throw new UsbException( dev().dev(), "Flash 2 Read: " + flash2StrError() );
1941
        }
1942
    }
1943
 
1944
// read one sector
1945
/**
1946
  * Reads one sector from the 2nd Flash memory.
1947
  * @param sector The sector number to be read.
1948
  * @param buf A buffer for the storage of the data.
1949
  * @throws InvalidFirmwareException if interface 1 is not supported.
1950
  * @throws UsbException if a communication error occurs.
1951
  * @throws CapabilityException if 2nd Flash memory access is not possible.
1952
  * @throws IndexOutOfBoundsException If the buffer is smaller than the 2nd Flash sector size.
1953
  */
1954
    public void flash2ReadSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException  {
1955
        flash2ReadSector ( sector, 1, buf );
1956
    }
1957
 
1958
 
1959
// ******* flashWriteSector ***************************************************
1960
// write integer number of sectors
1961
/**
1962
  * Writes a integer number of sectors to the Flash.
1963
  * @param sector The sector number to be written.
1964
  * @param num The number of sectors to be read.
1965
  * @param buf The data.
1966
  * @throws InvalidFirmwareException if interface 1 is not supported.
1967
  * @throws UsbException if a communication error occurs.
1968
  * @throws CapabilityException if Flash memory access is not possible.
1969
  * @throws IndexOutOfBoundsException If the buffer is to small.
1970
  */
1971
    public void flashWriteSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
1972
        if ( num<1 ) return;
1973
 
1974
        if ( buf.length < flashSectorSize()*num )
1975
            throw new IndexOutOfBoundsException( "Buffer to small: " + buf.length + " < " + (num*flashSectorSize()));
1976
 
1977
        checkCapability(CAPABILITY_FLASH);
1978
        if ( ! flashEnabled() )
1979
            throw new CapabilityException(this, "No Flash memory installed or");
1980
 
1981
        int oto = controlMsgTimeout;
1982
        controlMsgTimeout = 5000; // 5s timeout
1983
 
1984
        try {
1985
            if ( flashSectorSize()>2048 ) {
1986
                byte[] buf2 = new byte[2048];
1987
                int iz = (flashSectorSize-1) >> 11;
1988
                for (int sn=0; sn<num; sn++ ) {
1989
 
1990
                    controlMsgTimeout = 12000; // 12s timeout for erase
1991
 
1992
                    System.arraycopy(buf,sn*flashSectorSize, buf2,0, 2048);
1993
                    vendorCommand2( 0x42, "Flash Write", sector, 0, buf, 2048 );
1994
 
1995
                    controlMsgTimeout = 5000;
1996
 
1997
                    for (int i=1; i<iz; i++) {
1998
//                      System.out.println("w: "+i);
1999
                        System.arraycopy(buf,sn*flashSectorSize+i*2048, buf2,0, 2048);
2000
                        vendorCommand2( 0x42, "Flash Write", sector, 256, buf2, 2048 );
2001
                    }
2002
 
2003
                    int len = flashSectorSize-iz*2048;
2004
                    System.arraycopy(buf,sn*flashSectorSize+iz*2048, buf2,0, len);
2005
                    vendorCommand2( 0x42, "Flash Write", sector, 512, buf2, len );
2006
                }
2007
            }
2008
            else {
2009
                int nz = Math.max(1, 2048 / flashSectorSize);
2010
                byte[] buf2 = new byte[nz * flashSectorSize];
2011
                int bp = 0;
2012
                while ( num>0 ) {
2013
                    int n2 = Math.min(num,nz);
2014
                    System.arraycopy(buf,bp, buf2,0, flashSectorSize*n2);
2015
                    vendorCommand2( 0x41, "Flash Write", sector, sector >> 16, buf2, flashSectorSize*n2 );
2016
                    bp += flash2SectorSize*n2;
2017
                    sector += n2;
2018
                    num -= n2;
2019
                }
2020
            }
2021
        }
2022
        catch ( UsbException e ) {
2023
            throw new UsbException( dev().dev(), "Flash Write: " + flashStrError() );
2024
        }
2025
 
2026
        controlMsgTimeout = oto;
2027
    }
2028
 
2029
/**
2030
  * Writes one sector to the Flash.
2031
  * @param sector The sector number to be written.
2032
  * @param buf The data.
2033
  * @throws InvalidFirmwareException if interface 1 is not supported.
2034
  * @throws UsbException if a communication error occurs.
2035
  * @throws CapabilityException if Flash memory access is not possible.
2036
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash sector size.
2037
  */
2038
    public void flashWriteSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2039
        flashWriteSector(sector,1,buf);
2040
    }
2041
 
2042
// ******* flash2WriteSector **************************************************
2043
// write integer number of sectors
2044
/**
2045
  * Writes a integer number of sectors to the 2nd Flash.
2046
  * @param sector The sector number to be written.
2047
  * @param num The number of sectors to be read.
2048
  * @param buf The data.
2049
  * @throws InvalidFirmwareException if interface 1 is not supported.
2050
  * @throws UsbException if a communication error occurs.
2051
  * @throws CapabilityException if 2nd Flash memory access is not possible.
2052
  * @throws IndexOutOfBoundsException If the buffer is to small.
2053
  */
2054
    public void flash2WriteSector ( int sector, int num, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2055
        if ( num<1 ) return;
2056
 
2057
        if ( buf.length < flash2SectorSize()*num )
2058
            throw new IndexOutOfBoundsException( "Buffer to small: " + buf.length + " < " + (num*flash2SectorSize()));
2059
 
2060
        checkCapability(CAPABILITY_FLASH2);
2061
        if ( ! flash2Enabled() )
2062
            throw new CapabilityException(this, "No 2nd Flash memory installed or");
2063
 
2064
        int oto = controlMsgTimeout;
2065
        controlMsgTimeout = 5000; // 5s timeout
2066
 
2067
        try {
2068
            if ( flash2SectorSize()>2048 ) {
2069
                byte[] buf2 = new byte[2048];
2070
                int iz = (flash2SectorSize-1) >> 11;
2071
                for (int sn=0; sn<num; sn++ ) {
2072
 
2073
                    controlMsgTimeout = 12000; // 12s timeout for erase
2074
 
2075
                    System.arraycopy(buf,sn*flash2SectorSize, buf2,0, 2048);
2076
                    vendorCommand2( 0x46, "Flash 2 Write", sector, 0, buf, 2048 );
2077
 
2078
                    controlMsgTimeout = 5000;
2079
 
2080
                    for (int i=1; i<iz; i++) {
2081
//                      System.out.println("w: "+i);
2082
                        System.arraycopy(buf,sn*flash2SectorSize+i*2048, buf2,0, 2048);
2083
                        vendorCommand2( 0x46, "Flash 2 Write", sector, 256, buf2, 2048 );
2084
                    }
2085
 
2086
                    int len = flash2SectorSize-iz*2048;
2087
                    System.arraycopy(buf,sn*flash2SectorSize+iz*2048, buf2,0, len);
2088
                    vendorCommand2( 0x46, "Flash 2 Write", sector, 512, buf2, len );
2089
                }
2090
            }
2091
            else {
2092
                int nz = Math.max(1, 2048 / flash2SectorSize);
2093
                byte[] buf2 = new byte[nz * flash2SectorSize];
2094
                int bp = 0;
2095
                while ( num>0 ) {
2096
                    int n2 = Math.min(num,nz);
2097
                    System.arraycopy(buf,bp, buf2,0, flash2SectorSize*n2);
2098
                    vendorCommand2( 0x46, "Flash 2 Write", sector, sector >> 16, buf2, flash2SectorSize*n2 );
2099
                    bp += flash2SectorSize*n2;
2100
                    sector += n2;
2101
                    num -= n2;
2102
                }
2103
            }
2104
        }
2105
        catch ( UsbException e ) {
2106
            throw new UsbException( dev().dev(), "Flash 2 Write: " + flash2StrError() );
2107
        }
2108
 
2109
        controlMsgTimeout = oto;
2110
    }
2111
 
2112
// write one sector
2113
/**
2114
  * Writes one sector to the 2nd Flash memory.
2115
  * @param sector The sector number to be written.
2116
  * @param buf The data.
2117
  * @throws InvalidFirmwareException if interface 1 is not supported.
2118
  * @throws UsbException if a communication error occurs.
2119
  * @throws CapabilityException if 2nd Flash access is not possible.
2120
  * @throws IndexOutOfBoundsException If the buffer is smaller than the 2nd Flash sector size.
2121
  */
2122
    public void flash2WriteSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2123
        flash2WriteSector(sector,1,buf);
2124
    }
2125
 
2126
// ******* flashEnabled ********************************************************
2127
// returns enabled / disabled state 
2128
/**
2129
  * Returns true if Flash memory is installed.
2130
  * @return true if Flash memory is installed.
2131
  * @throws InvalidFirmwareException if interface 1 is not supported.
2132
  * @throws UsbException if a communication error occurs.
2133
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2134
  */
2135
    public boolean flashEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
2136
        if ( flashEnabled < 0 ) // init variable
2137
            flashState();
2138
        return flashEnabled == 1;
2139
    }
2140
 
2141
// ******* flash2Enabled *******************************************************
2142
// returns enabled / disabled state 
2143
/**
2144
  * Returns true if 2nd Flash memory is installed.
2145
  * @return true if 2nd Flash memory is installed.
2146
  * @throws InvalidFirmwareException if interface 1 is not supported.
2147
  * @throws UsbException if a communication error occurs.
2148
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
2149
  */
2150
    public boolean flash2Enabled () throws UsbException, InvalidFirmwareException, CapabilityException {
2151
        if ( flash2Enabled < 0 ) // init variable
2152
            flash2State();
2153
        return flash2Enabled == 1;
2154
    }
2155
 
2156
// ******* flashSectorSize *****************************************************
2157
// returns sector size of Flash memory, if available
2158
/**
2159
  * Returns the sector size of the Flash memory or 0, if no Flash is installed.
2160
  * If required, the sector size is determined form the device first.
2161
  * @return the sector size of the Flash memory.
2162
  * @throws InvalidFirmwareException if interface 1 is not supported.
2163
  * @throws UsbException if a communication error occurs.
2164
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2165
  */
2166
    public int flashSectorSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2167
        if ( flashSectorSize < 0 ) // init variable
2168
            flashState();
2169
        return flashSectorSize;
2170
    }
2171
 
2172
// ******* flash2SectorSize ****************************************************
2173
// returns sector size of Flash 2 memory, if available
2174
/**
2175
  * Returns the sector size of the 2nd Flash memory or 0, if no 2nd Flash is installed.
2176
  * If required, the sector size is determined form the device first.
2177
  * @return the sector size of the 2nd Flash.
2178
  * @throws InvalidFirmwareException if interface 1 is not supported.
2179
  * @throws UsbException if a communication error occurs.
2180
  * @throws CapabilityException if 2nd Flash access is not supported by the firmware.
2181
  */
2182
    public int flash2SectorSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2183
        if ( flash2SectorSize < 0 ) // init variable
2184
            flash2State();
2185
        return flash2SectorSize;
2186
    }
2187
 
2188
// ******* flashSectors ********************************************************
2189
// returns number of sectors of Flash memory, if available
2190
/**
2191
  * Returns the number of sectors of the Flash memory or 0, if no Flash memory is installed.
2192
  * If required, the number of sectors is determined form the device first.
2193
  * @return the number of sectors of the Flash memory.
2194
  * @throws InvalidFirmwareException if interface 1 is not supported.
2195
  * @throws UsbException if a communication error occurs.
2196
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2197
  */
2198
    public int flashSectors () throws UsbException, InvalidFirmwareException, CapabilityException {
2199
        if ( flashSectors < 0 ) // init variable
2200
            flashState();
2201
        return flashSectors;
2202
    }
2203
 
2204
// ******* flash2Sectors *******************************************************
2205
// returns number of sectors of 2nd Flash memory, if available
2206
/**
2207
  * Returns the number of sectors of the 2nd Flash memory or 0, if no 2nd Flash is installed.
2208
  * If required, the number of sectors is determined form the device first.
2209
  * @return the number of sectors of the 2nd Flash memory.
2210
  * @throws InvalidFirmwareException if interface 1 is not supported.
2211
  * @throws UsbException if a communication error occurs.
2212
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
2213
  */
2214
    public int flash2Sectors () throws UsbException, InvalidFirmwareException, CapabilityException {
2215
        if ( flash2Sectors < 0 ) // init variable
2216
            flash2State();
2217
        return flash2Sectors;
2218
    }
2219
 
2220
// ******* flashSize ***********************************************************
2221
// returns size of Flash memory, if available
2222
/**
2223
  * Returns the size of Flash memory or 0, if no Flash memory is installed.
2224
  * If required, the Flash size is determined form the device first.
2225
  * @return the size of Flash memory.
2226
  * @throws InvalidFirmwareException if interface 1 is not supported.
2227
  * @throws UsbException if a communication error occurs.
2228
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2229
  */
2230
    public long flashSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2231
        return flashSectorSize() * (long)flashSectors();
2232
    }
2233
 
2234
// ******* flash2Size **********************************************************
2235
// returns size of 2nd Flash memory, if available
2236
/**
2237
  * Returns the size of 2nd Flash memory or 0, if no 2nd Flash memory is installed.
2238
  * If required, the 2nd Flash size is determined form the device first.
2239
  * @return the size of Flash memory.
2240
  * @throws InvalidFirmwareException if interface 1 is not supported.
2241
  * @throws UsbException if a communication error occurs.
2242
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
2243
  */
2244
    public long flash2Size () throws UsbException, InvalidFirmwareException, CapabilityException {
2245
        return flash2SectorSize() * (long)flash2Sectors();
2246
    }
2247
 
2248
// ******* printMmcState *******************************************************
2249
// returns true if Flash is available
2250
/**
2251
  * Prints out some debug information about *SD/MMC Flash cards in SPI mode.<br>
2252
  * <b>Only use this method if such kind of Flash is installed.</b>
2253
  * @return True if flash is installed and enabled.
2254
  * @throws InvalidFirmwareException if interface 1 is not supported.
2255
  * @throws UsbException if a communication error occurs.
2256
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
2257
  */
2258
    public boolean printMmcState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2259
        byte[] buf = new byte[23];
2260
        checkCapability(CAPABILITY_FLASH);
2261
        vendorRequest2(0x43, "MMC State", 0, 0, buf, 23);
2262
        System.out.println("status=" + Integer.toBinaryString(256+(buf[0] & 255)).substring(1) + "." + Integer.toBinaryString(256+(buf[1] & 255)).substring(1) +
2263
                "   lastCmd=" + buf[3] +
2264
                "   lastCmdResponse=" + Integer.toBinaryString(256+(buf[4] & 255)).substring(1) +
2265
                "   ec=" + buf[2] +
2266
                "   BUSY=" + buf[22] +
2267
                "   SDHC=" + buf[5] +
2268
                "   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));
2269
 
2270
        return flashEnabled == 1;
2271
    }
2272
 
2273
// ******* printMmc2State *******************************************************
2274
// returns true if 2nd Flash is available
2275
/**
2276
  * Prints out some debug information about *SD/MMC Flash cards in SPI mode.<br>
2277
  * <b>Only use this method if such kind of Flash is installed as 2nd Flash memory.</b>
2278
  * @return True if flash is installed and enabled.
2279
  * @throws InvalidFirmwareException if interface 1 is not supported.
2280
  * @throws UsbException if a communication error occurs.
2281
  * @throws CapabilityException if 2nd Flash memory access is not supported by the firmware.
2282
  */
2283
    public boolean printMmc2State ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2284
        byte[] buf = new byte[23];
2285
        checkCapability(CAPABILITY_FLASH2);
2286
        vendorRequest2(0x47, "MMC 2 State", 0, 0, buf, 23);
2287
        System.out.println("status=" + Integer.toBinaryString(256+(buf[0] & 255)).substring(1) + "." + Integer.toBinaryString(256+(buf[1] & 255)).substring(1) +
2288
                "   lastCmd=" + buf[3] +
2289
                "   lastCmdResponse=" + Integer.toBinaryString(256+(buf[4] & 255)).substring(1) +
2290
                "   ec=" + buf[2] +
2291
                "   BUSY=" + buf[22] +
2292
                "   SDHC=" + buf[5] +
2293
                "   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));
2294
 
2295
        return flash2Enabled == 1;
2296
    }
2297
 
2298
// ******* flashUploadBitstream ************************************************
2299
/*
2300
    Returns configuration time in ms.
2301
    The format of the boot sector (sector 0 of the Flash memory) is
2302
        0..7    ID
2303
        8..9    Number of BS sectors, or 0 is disabled
2304
        10..11  Number of bytes in the last sector, i.e. the total size of Bitstream is ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
2305
*/
2306
/**
2307
  * Uploads a Bitstream to the Flash.
2308
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
2309
  * it is possible to construct fully autonomous devices.
2310
  * <p>
2311
  * If configuration data is present information about bitstream are stored there and Bitstream starts
2312
  * at sector 0.
2313
  * <p>
2314
  * On all other devices the information about the bitstream is stored in sector 0.
2315
  * This so called boot sector has the following format:
2316
  * <table bgcolor="#404040" cellspacing=1 cellpadding=4>
2317
  *   <tr>
2318
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
2319
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
2320
  *   </tr>
2321
  *   <tr>
2322
  *     <td bgcolor="#ffffff" valign="top">0..7</td>
2323
  *     <td bgcolor="#ffffff" valign="top">ID, must be "ZTEXBS",1,1</td>
2324
  *   </tr>
2325
  *   <tr>
2326
  *     <td bgcolor="#ffffff" valign="top">8..9</td>
2327
  *     <td bgcolor="#ffffff" valign="top">The number of sectors used to store the Bitstream. 0 means no Bitstream.</td>
2328
  *   </tr>
2329
  *   <tr>
2330
  *     <td bgcolor="#ffffff" valign="top">10..11</td>
2331
  *     <td bgcolor="#ffffff" valign="top">The number of bytes in the last sector.</td>
2332
  *   </tr>
2333
  *   <tr>
2334
  *     <td bgcolor="#ffffff" valign="top">12..sectorSize-1</td>
2335
  *     <td bgcolor="#ffffff" valign="top">This data is reserved for future use and preserved by this method.</td>
2336
  *   </tr>
2337
  * </table>
2338
  * <p>
2339
  * The total size of the Bitstream is computed as ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
2340
  * where bs[i] denotes byte i of the boot sector.
2341
  * <p>
2342
  * The first sector of the Bitstream is sector 1.
2343
  * @param inputStream for reading the Bitstream.
2344
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2345
  * @return Configuration time in ms.
2346
  * @throws InvalidFirmwareException if interface 1 is not supported.
2347
  * @throws UsbException if a communication error occurs.
2348
  * @throws CapabilityException if Flash memory access is not possible.
2349
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2350
  * @see #flashResetBitstream()
2351
  */
2352
    public long flashUploadBitstream ( InputStream inputStream, int bs ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
2353
        int secNum = Math.max(1, 2048 / flashSectorSize());
2354
        final int bufferSize = secNum * flashSectorSize;
2355
        checkCapability(CAPABILITY_FPGA);
2356
        checkCapability(CAPABILITY_FLASH);
2357
        if ( ! flashEnabled() )
2358
            throw new CapabilityException(this, "No Flash memory installed or");
2359
        getFpgaState();
2360
 
2361
// read the Bitstream file      
2362
        byte[][] buffer = new byte[32768][];
2363
        byte[] buf1 = new byte[flashSectorSize()];
2364
 
2365
        int i,j,k,l;
2366
        try {
2367
            j = bufferSize;
2368
            for ( i=0; i<buffer.length && j==bufferSize; i++ ) {
2369
                buffer[i] = new byte[bufferSize];
2370
                j = 0;
2371
                do {
2372
                    k = inputStream.read( buffer[i], j, bufferSize-j );
2373
                    if ( k < 0 )
2374
                        k = 0;
2375
                    j += k;
2376
 
2377
                    // remove header because S6 FPGA's does not support bitstream start word detection
2378
                    if ( i==0 && !dev().fx3() && j==bufferSize && (l=detectBitstreamStart(buffer[0]))>0 ) {
2379
                        for (int m=0; m<bufferSize-l; m++ )
2380
                            buffer[0][m]=buffer[0][m+l];
2381
                        j-=l;
2382
                    }
2383
                }
2384
                while ( j<bufferSize && k>0 );
2385
 
2386
                // detect bitstream bit order and swap bits if necessary 
2387
                if ( (i==0) && ( bs<0 || bs>1 ) ) {
2388
                    bs = detectBitstreamBitOrder ( buffer[0] );
2389
//                  System.out.println(bs + "   " + (fpgaFlashBitSwap != (bs==1)));
2390
                }
2391
 
2392
                if ( fpgaFlashBitSwap != (bs==1) ) swapBits(buffer[i], j);
2393
            }
2394
 
2395
            try {
2396
                inputStream.close();
2397
            }
2398
            catch ( Exception e ) {
2399
            }
2400
        }
2401
        catch (IOException e) {
2402
            throw new BitstreamReadException(e.getLocalizedMessage());
2403
        }
2404
 
2405
 
2406
// upload the Bitstream file    
2407
        int startSector = 0;
2408
        long t0 = new Date().getTime();
2409
 
2410
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
2411
            config.setBitstreamSize( ((i-1)*secNum + (j-1)/flashSectorSize + 1)*flashSectorSize );
2412
            startSector = (config.getBitstreamStart()+flashSectorSize-1) / flashSectorSize;
2413
        }
2414
        else {
2415
            byte[] sector = new byte[flashSectorSize];
2416
            byte[] ID = new String("ZTEXBS").getBytes();
2417
 
2418
            flashReadSector(0,sector);                           // read the boot sector (only the first 16 bytes are overwritten if boot sector is valid)
2419
            boolean b = true;
2420
            for (k=0; k<6; k++) {
2421
                b = b && (sector[k] == ID[k]);
2422
                sector[k]=ID[k];
2423
            }
2424
            if ( ! b )
2425
            sector[6] = 1;
2426
            sector[7] = 1;
2427
            k = (i-1)*secNum + (j-1)/flashSectorSize + 1;
2428
            sector[8] = (byte) (k & 255);
2429
            sector[9] = (byte) ((k>>8) & 255);
2430
            k = ((j-1) % flashSectorSize) + 1;
2431
            sector[10] = (byte) (k & 255);
2432
            sector[11] = (byte) ((k>>8) & 255);
2433
            if ( ! b ) {
2434
                for ( k=12; k<flashSectorSize; k++ )
2435
                    sector[k]=0;
2436
            }
2437
            System.out.print("\rWriting boot sector");
2438
            flashWriteSector(0,sector);                          // write the boot sector
2439
 
2440
            startSector = 1;
2441
        }
2442
 
2443
        for (k=0; k<i-1; k++) {
2444
            System.out.print("\rWriting sector " + (k+1)*secNum + " of " + i*secNum);
2445
            flashWriteSector( startSector+k*secNum, secNum, buffer[k] );        // write the Bitstream sectors
2446
        }
2447
        System.out.println("\rWriting sector " + i*secNum + " of " + i*secNum);
2448
        flashWriteSector( startSector+k*secNum, (j-1)/flashSectorSize + 1, buffer[k] );
2449
 
2450
        return new Date().getTime() - t0;
2451
    }
2452
 
2453
/**
2454
  * Uploads a Bitstream to the Flash.
2455
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
2456
  * it is possible to construct fully autonomous devices.
2457
  * See {@link #flashUploadBitstream(InputStream,int)} for further details.
2458
  * @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).
2459
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
2460
  * @return Configuration time in ms.
2461
  * @throws InvalidFirmwareException if interface 1 is not supported.
2462
  * @throws UsbException if a communication error occurs.
2463
  * @throws CapabilityException if Flash memory access is not possible.
2464
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2465
  * @see #flashResetBitstream()
2466
  */
2467
    public long flashUploadBitstream ( String fwFileName, int bs ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
2468
        try {
2469
            return flashUploadBitstream ( JInputStream.getInputStream( fwFileName ), bs );
2470
        }
2471
        catch (IOException e) {
2472
            throw new BitstreamReadException(e.getLocalizedMessage());
2473
        }
2474
    }
2475
 
2476
/**
2477
  * Uploads a Bitstream to the Flash.
2478
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
2479
  * it is possible to construct fully autonomous devices.
2480
  * See {@link #flashUploadBitstream(InputStream,int)} for further details.
2481
  * @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).
2482
  * @return Configuration time in ms.
2483
  * @throws InvalidFirmwareException if interface 1 is not supported.
2484
  * @throws UsbException if a communication error occurs.
2485
  * @throws CapabilityException if Flash memory access is not possible.
2486
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
2487
  * @see #flashResetBitstream()
2488
  */
2489
    public long flashUploadBitstream ( String fwFileName ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
2490
        return flashUploadBitstream(fwFileName, -1);
2491
    }
2492
 
2493
// ******* flashResetBitstream *************************************************
2494
// Clears a Bitstream from the Flash.
2495
/**
2496
  * Clears a Bitstream from the Flash.
2497
  * This is achieved by writing 0 to bytes 8..9 of the boot sector, see {@link #flashUploadBitstream(String)}.
2498
  * If no boot sector is installed the method returns without any write action.
2499
  * @throws InvalidFirmwareException if interface 1 is not supported.
2500
  * @throws UsbException if a communication error occurs.
2501
  * @throws CapabilityException if Flash memory access is not possible.
2502
  */
2503
    public void flashResetBitstream ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2504
        checkCapability(CAPABILITY_FLASH);
2505
        if ( ! flashEnabled() )
2506
            throw new CapabilityException(this, "Flash memory not installed or");
2507
 
2508
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
2509
            config.setBitstreamSize(0);
2510
            return;
2511
        }
2512
 
2513
        byte[] sector = new byte[flashSectorSize()];
2514
        byte[] ID = new String("ZTEXBS").getBytes();
2515
 
2516
        flashReadSector(0,sector);                       // read the boot sector
2517
        for (int k=0; k<6; k++)
2518
            if ( sector[k] != ID[k] )
2519
                return;
2520
        if (sector[6]!=1 || sector[7]!=1 )
2521
            return;
2522
        sector[8] = 0;
2523
        sector[9] = 0;
2524
        flashWriteSector(0,sector);                      // write the boot sector
2525
    }
2526
 
2527
// ******* flashFirstFreeSector ************************************************
2528
 
2529
// Returns the first free sector of the Flash memory, i.e. the first sector behind the Bitstream
2530
/**
2531
  * Returns the first free sector of the Flash memory.
2532
  * 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).
2533
  * @return the first free sector of the Flash memory.
2534
  * @throws InvalidFirmwareException if interface 1 is not supported.
2535
  * @throws UsbException if a communication error occurs.
2536
  * @throws CapabilityException if Flash memory access is not possible.
2537
  */
2538
    public int flashFirstFreeSector ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2539
        checkCapability(CAPABILITY_FLASH);
2540
        if ( ! flashEnabled() )
2541
            throw new CapabilityException(this, "No Flash memory installed or");
2542
 
2543
        if ( config!=null && config.getMaxBitstreamSize()>0 ) {
2544
            return (config.getBitstreamStart()+flashSectorSize()-1) / flashSectorSize()  +  (Math.max(config.getMaxBitstreamSize(), config.getBitstreamSize())+flashSectorSize()-1) / flashSectorSize();
2545
        }
2546
 
2547
        byte[] sector = new byte[flashSectorSize()];
2548
        byte[] ID = new String("ZTEXBS").getBytes();
2549
 
2550
        flashReadSector(0,sector);                       // read the boot sector
2551
        for (int k=0; k<6; k++)
2552
            if ( sector[k] != ID[k] )
2553
                return 0;
2554
        if (sector[6]!=1 || sector[7]!=1 )
2555
            return 0;
2556
        return (sector[8] & 255) + ((sector[9] & 255) << 8) + 1;
2557
    }
2558
 
2559
// ******* toHumanStr **********************************************************
2560
/**
2561
  * Converts an integer into a base 1024 formatted string.
2562
  * E.g. the number 1234567890 is converted to 1G153M384K722.
2563
  * @param i an integer which may be large.
2564
  * @return a human readable string representation.
2565
  */
2566
    public String toHumanStr ( long i ) {
2567
        if ( i==0 ) return "0";
2568
        StringBuilder sb = new StringBuilder();
2569
        int k = 0;
2570
        if ( i<0 ) {
2571
            sb.append("-");
2572
            i=-i;
2573
            k=1;
2574
        }
2575
        if ( (i & 1023) != 0 ) sb.insert(k, i & 1023); i=i>>10;
2576
        if ( (i & 1023) != 0 ) sb.insert(k, (i & 1023) + "K"); i=i>>10;
2577
        if ( (i & 1023) != 0 ) sb.insert(k, (i & 1023) + "M"); i=i>>10;
2578
        if ( i != 0 ) sb.insert(k, i + "G");;
2579
        return sb.toString();
2580
    }
2581
 
2582
// ******* flashInfo ***********************************************************
2583
/**
2584
  * Returns information about Flash memory.
2585
  * The result contains the size and how much of the Flash is us used / reserved for / by the Bitstream.
2586
  * If no Flash memeory is suppported an empty string is returned.
2587
  * @return Information about Flash memory.
2588
  */
2589
    public String flashInfo ( ) {
2590
        StringBuilder sb = new StringBuilder();
2591
        try {
2592
            if ( flashSize() > 0 ) {
2593
                sb.append( "Size: " + toHumanStr(flashSize()) + " Bytes" );
2594
                if ( config!=null && config.getMaxBitstreamSize()>0 ) {
2595
                    sb.append( ";  Bitstream (start / used / reserved): " + toHumanStr(config.getBitstreamStart()) + " / "  + toHumanStr(config.getBitstreamSize()) + " / "  + toHumanStr(config.getMaxBitstreamSize()) + " Bytes" );
2596
                }
2597
                else {
2598
                    sb.append( ";  Bitstream (used): " + toHumanStr(flashFirstFreeSector()*flashSectorSize()) + " Bytes" );
2599
                }
2600
            }
2601
        }
2602
        catch ( Exception e ) {
2603
        }
2604
        return sb.toString();
2605
    }
2606
 
2607
// ******* flash2Info *********************************************************=
2608
/**
2609
  * Returns information about 2nd Flash memory.
2610
  * The result contains the size and how much of the Flash available.
2611
  * If no 2nd Flash memeory is suppported an empty string is returned.
2612
  * @return Information about 2nd Flash memory.
2613
  */
2614
    public String flash2Info ( ) {
2615
        String s = "";
2616
        try {
2617
            if ( flash2Size() > 0 ) {
2618
                s="Size: " + toHumanStr(flash2Size()) + " Bytes";
2619
            }
2620
        }
2621
        catch ( Exception e ) {
2622
        }
2623
        return s;
2624
    }
2625
 
2626
// ******* debugStackSize ******************************************************
2627
/**
2628
  * Returns the size of message stack in messages.
2629
  * @return the size of message stack in messages.
2630
  * @throws InvalidFirmwareException if interface 1 is not supported.
2631
  * @throws UsbException if a communication error occurs.
2632
  * @throws CapabilityException if Flash memory access is not possible.
2633
  */
2634
    public int debugStackSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2635
        checkCapability(CAPABILITY_DEBUG);
2636
        if ( debugStackSize<=0 || debugMsgSize<=0 ) {
2637
            byte[] buf = new byte[7];
2638
            vendorRequest2(0x28, "Read debug data", 0, 0, buf, 4);
2639
            debugStackSize = buf[2] & 255;
2640
            debugMsgSize = buf[3] & 255;
2641
        }
2642
        return debugStackSize;
2643
    }
2644
 
2645
// ******* debugMsgSize ********************************************************
2646
/**
2647
  * Returns the size of messages in bytes.
2648
  * @return the size of messages in bytes.
2649
  * @throws InvalidFirmwareException if interface 1 is not supported.
2650
  * @throws UsbException if a communication error occurs.
2651
  * @throws CapabilityException if Flash memory access is not possible.
2652
  */
2653
    public int debugMsgSize ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
2654
        checkCapability(CAPABILITY_DEBUG);
2655
        if ( debugMsgSize<=0 )
2656
            debugStackSize();
2657
 
2658
        return debugMsgSize;
2659
    }
2660
 
2661
// ******* debugLastMsg ********************************************************
2662
/**
2663
  * Returns the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
2664
  * @return the number of the last message read out by {@link #debugReadMessages(boolean,byte[])}
2665
  */
2666
    public final int debugLastMsg ( )  {
2667
        return debugLastMsg;
2668
    }
2669
 
2670
// ******* debugReadMessages ***************************************************
2671
/**
2672
  * Reads debug messages from message stack.
2673
  * The number of messages stored in buf is returned. The total number of new messages is stored in {@link #debugNewMessages}.
2674
  * The number of the latest message is returned by {@link #debugLastMsg()}.
2675
  * @param all If true, all messages from stack are written to buf. If it is false, only the new messages are written to buf.
2676
  * @param buf The buffer to store the messages.
2677
  * @return the size of messages stored in buffer.
2678
  * @throws InvalidFirmwareException if interface 1 is not supported.
2679
  * @throws UsbException if a communication error occurs.
2680
  * @throws CapabilityException if Flash memory access is not possible.
2681
  */
2682
    public int debugReadMessages ( boolean all, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException {
2683
        checkCapability(CAPABILITY_DEBUG);
2684
        byte buf2[] = new byte[ debugStackSize()*debugMsgSize() + 4 ];
2685
        vendorRequest2(0x28, "Read debug data", 0, 0, buf2, buf2.length);
2686
        int lm = (buf2[0] & 255) | ((buf2[1] & 255) << 8);
2687
        debugNewMessages = lm - debugLastMsg;
2688
 
2689
        int r = Math.min( Math.min( buf.length/debugMsgSize() , debugStackSize ), lm);
2690
        if ( !all ) r = Math.min(r,debugNewMessages);
2691
        for (int i = 0; i<r; i++) {
2692
            int k=(lm-r+i) % debugStackSize;
2693
            for (int j=0; j<debugMsgSize; j++ )
2694
                buf[i*debugMsgSize+j] = buf2[k*debugMsgSize+j+4];
2695
        }
2696
 
2697
        debugLastMsg = lm;
2698
        return r;
2699
    }
2700
 
2701
// ******* xmegaStrError *******************************************************
2702
/**
2703
  * Converts a given error code into a String.
2704
  * @param errNum The error code.
2705
  * @return an error message.
2706
  */
2707
    public String xmegaStrError ( int errNum ) {
2708
        switch ( errNum ) {
2709
            case XMEGA_EC_NO_ERROR:
2710
                return "USB error";
2711
            case XMEGA_EC_PDI_READ_ERROR:
2712
                return "PDI read error";
2713
            case XMEGA_EC_NVM_TIMEOUT:
2714
                return "NVM timeout error";
2715
            case XMEGA_EC_INVALID_DEVICE:
2716
                return "Invalid or unsupported ATxmega";
2717
            case XMEGA_EC_ADDRESS_ERROR:
2718
                return "Address error (invalid address or wrong page size)";
2719
            case XMEGA_EC_NVM_BUSY:
2720
                return "NVM busy";
2721
        }
2722
        return "Error " + errNum;
2723
    }
2724
 
2725
/**
2726
  * Gets the last ATxmega error from the device.
2727
  * @return an error message.
2728
  */
2729
    public String xmegaStrError ( ) {
2730
        try {
2731
            return xmegaStrError( xmegaState() );
2732
        }
2733
        catch ( Exception e ) {
2734
            return "Unknown error (Error receiving error code: "+e.getLocalizedMessage() +")";
2735
        }
2736
    }
2737
 
2738
// ******* xmegaState **********************************************************
2739
/**
2740
  * Read ATxmega error and status information from the device.
2741
  * @return The last error code.
2742
  * @throws InvalidFirmwareException if interface 1 is not supported.
2743
  * @throws UsbException if a communication error occurs.
2744
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2745
  */
2746
    public int xmegaState () throws UsbException, InvalidFirmwareException, CapabilityException {
2747
        byte[] buf = new byte[7];
2748
        checkCapability(CAPABILITY_XMEGA);
2749
        vendorRequest2(0x48, "Xmega state", 0, 0, buf, 7);
2750
        xmegaEC = buf[0] & 255;
2751
 
2752
        xmegaFlashPages = ((buf[2] & 255) << 8) | (buf[1] & 255);
2753
        xmegaEepromPages = ((buf[4] & 255) << 8) | (buf[3] & 255);
2754
        xmegaFlashPageSize = 1 << (buf[5] & 15);
2755
        xmegaEepromPageSize = 1 << (buf[6] & 15);
2756
        return xmegaEC;
2757
    }
2758
 
2759
// ******* xmegaEnabled ********************************************************
2760
/**
2761
  * Returns true if ATxmega controller is available.
2762
  * @return true if ATxmega controller is available.
2763
  * @throws InvalidFirmwareException if interface 1 is not supported.
2764
  * @throws UsbException if a communication error occurs.
2765
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2766
  */
2767
    public boolean xmegaEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
2768
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2769
            xmegaState();
2770
        return xmegaFlashPages > 0 && xmegaEepromPages > 0;
2771
    }
2772
 
2773
// ******* xmegaFlashPages *****************************************************
2774
/**
2775
  * Returns the number of the ATxmega Flash pages.
2776
  * @return The number of the ATxmega Flash pages.
2777
  * @throws InvalidFirmwareException if interface 1 is not supported.
2778
  * @throws UsbException if a communication error occurs.
2779
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2780
  */
2781
    public int xmegaFlashPages () throws UsbException, InvalidFirmwareException, CapabilityException {
2782
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2783
            xmegaState();
2784
        return xmegaFlashPages;
2785
    }
2786
 
2787
// ******* xmegaEepromPages ****************************************************
2788
/**
2789
  * Returns the number of the ATxmega EEPROM pages.
2790
  * @return The number of the ATxmega EEPROM pages.
2791
  * @throws InvalidFirmwareException if interface 1 is not supported.
2792
  * @throws UsbException if a communication error occurs.
2793
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2794
  */
2795
    public int xmegaEepromPages () throws UsbException, InvalidFirmwareException, CapabilityException {
2796
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2797
            xmegaState();
2798
        return xmegaEepromPages;
2799
    }
2800
 
2801
// ******* xmegaFlashPageSize **************************************************
2802
/**
2803
  * Returns the size of the ATxmega Flash pages.
2804
  * @return The size of the ATxmega Flash pages.
2805
  * @throws InvalidFirmwareException if interface 1 is not supported.
2806
  * @throws UsbException if a communication error occurs.
2807
  * @throws CapabilityException if ATxmega controllers are not supported by the firmware.
2808
  */
2809
    public int xmegaFlashPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2810
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2811
            xmegaState();
2812
        return xmegaFlashPageSize;
2813
    }
2814
 
2815
// ******* xmegaEEpromPageSize *************************************************
2816
/**
2817
  * Returns the size of the ATXmega EEPROM pages.
2818
  * @return The size of the ATXmega EEPROM pages.
2819
  * @throws InvalidFirmwareException if interface 1 is not supported.
2820
  * @throws UsbException if a communication error occurs.
2821
  * @throws CapabilityException if ATXmega controllers are not supported by the firmware.
2822
  */
2823
    public int xmegaEepromPageSize () throws UsbException, InvalidFirmwareException, CapabilityException {
2824
        if ( xmegaFlashPages < 0 || xmegaEepromPages < 0 ) // init variables
2825
            xmegaState();
2826
        return xmegaEepromPageSize;
2827
    }
2828
 
2829
// ******* xmegaReset **********************************************************
2830
/**
2831
  * Resets the ATxmega.
2832
  * @throws InvalidFirmwareException if interface 1 is not supported.
2833
  * @throws UsbException if a communication error occurs.
2834
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2835
  */
2836
    public void xmegaReset () throws UsbException, InvalidFirmwareException, CapabilityException {
2837
        checkCapability(CAPABILITY_XMEGA);
2838
        try {
2839
            vendorCommand( 0x49, "XMEGA Reset" );
2840
        }
2841
        catch ( UsbException e ) {
2842
            throw new UsbException( dev().dev(), "NVM Reset: " + xmegaStrError() );
2843
        }
2844
    }
2845
 
2846
 
2847
// ******* xmegaNvmRead ********************************************************
2848
/**
2849
  * Reads data from the NVM of ATxmega.
2850
  * @param addr The source address of the NVM (PDI address space).
2851
  * @param buf A buffer for the storage of the data.
2852
  * @param length The amount of bytes to be read.
2853
  * @throws InvalidFirmwareException if interface 1 is not supported.
2854
  * @throws UsbException if a communication error occurs.
2855
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2856
  */
2857
    public void xmegaNvmRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2858
        checkCapability(CAPABILITY_XMEGA);
2859
 
2860
        try {
2861
            vendorRequest2( 0x4a, "XMEGA NVM Read", addr, addr>> 16, buf, length );
2862
        }
2863
        catch ( UsbException e ) {
2864
            throw new UsbException( dev().dev(), "NVM Read: " + xmegaStrError() );
2865
        }
2866
        try {
2867
            Thread.sleep( 3 );
2868
        }
2869
        catch ( InterruptedException e) {
2870
        }
2871
    }
2872
 
2873
 
2874
// ******* xmegaFlashRead ******************************************************
2875
/**
2876
  * Reads data from Flash memory of ATxmega.
2877
  * @param addr The source address relative to the Flash memory base.
2878
  * @param buf A buffer for the storage of the data.
2879
  * @param length The amount of bytes to be read.
2880
  * @throws InvalidFirmwareException if interface 1 is not supported.
2881
  * @throws UsbException If a communication error occurs.
2882
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2883
  */
2884
    public void xmegaFlashRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2885
        checkCapability(CAPABILITY_XMEGA);
2886
 
2887
        try {
2888
            vendorRequest2( 0x4b, "XMEGA Flash Read", addr, addr>> 16, buf, length );
2889
        }
2890
        catch ( UsbException e ) {
2891
            throw new UsbException( dev().dev(), "XMEGA Flash Read: " + xmegaStrError() );
2892
        }
2893
        try {
2894
            Thread.sleep( 3 );
2895
        }
2896
        catch ( InterruptedException e) {
2897
        }
2898
    }
2899
 
2900
 
2901
 
2902
// ******* xmegaEepromRead *****************************************************
2903
/**
2904
  * Reads data from EEPROM memory of ATxmega.
2905
  * @param addr The source address relative to the EEPROM memory base.
2906
  * @param buf A buffer for the storage of the data.
2907
  * @param length The amount of bytes to be read.
2908
  * @throws InvalidFirmwareException if interface 1 is not supported.
2909
  * @throws UsbException If a communication error occurs.
2910
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2911
  */
2912
    public void xmegaEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2913
        checkCapability(CAPABILITY_XMEGA);
2914
 
2915
        try {
2916
            vendorRequest2( 0x4c, "XMEGA EEPROM Read", addr, addr>> 16, buf, length );
2917
        }
2918
        catch ( UsbException e ) {
2919
            throw new UsbException( dev().dev(), "XMEGA EEPROM Read: " + xmegaStrError() );
2920
        }
2921
        try {
2922
            Thread.sleep( 3 );
2923
        }
2924
        catch ( InterruptedException e) {
2925
        }
2926
    }
2927
 
2928
 
2929
// ******* xmegaFuseRead *******************************************************
2930
/**
2931
  * Reads data from Fuse memory of ATxmega.
2932
  * @param addr The source address relative to the Fuse memory base.
2933
  * @param buf A buffer for the storage of the data.
2934
  * @param length The amount of bytes to be read.
2935
  * @throws InvalidFirmwareException if interface 1 is not supported.
2936
  * @throws UsbException If a communication error occurs.
2937
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2938
  */
2939
    public void xmegaFuseRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
2940
        checkCapability(CAPABILITY_XMEGA);
2941
 
2942
        try {
2943
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, addr>> 16, buf, length );
2944
        }
2945
        catch ( UsbException e ) {
2946
            throw new UsbException( dev().dev(), "XMEGA Fuse Read: " + xmegaStrError() );
2947
        }
2948
        try {
2949
            Thread.sleep( 3 );
2950
        }
2951
        catch ( InterruptedException e) {
2952
        }
2953
    }
2954
 
2955
/**
2956
  * Reads data one Fuse of ATxmega.
2957
  * @param addr The index of th Fuse.
2958
  * @return The Fuse read.
2959
  * @throws InvalidFirmwareException if interface 1 is not supported.
2960
  * @throws UsbException If a communication error occurs.
2961
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
2962
  */
2963
    public int xmegaFuseRead ( int addr ) throws UsbException, InvalidFirmwareException, CapabilityException {
2964
        byte[] buf = new byte[1];
2965
        checkCapability(CAPABILITY_XMEGA);
2966
        try {
2967
            vendorRequest2( 0x4d, "XMEGA Fuse Read", addr, 0, buf, 1 );
2968
        }
2969
        catch ( UsbException e ) {
2970
            throw new UsbException( dev().dev(), "XMEGA Fuse Read: " + xmegaStrError() );
2971
        }
2972
        try {
2973
            Thread.sleep( 3 );
2974
        }
2975
        catch ( InterruptedException e) {
2976
        }
2977
        return buf[0] & 255;
2978
    }
2979
 
2980
 
2981
// ******* xmegaFlashPageWrite *************************************************
2982
/**
2983
  * Writes data to Flash memory of ATxmega.
2984
  * @param addr The source address relative to the Flash memory base.
2985
  * @param buf A buffer that stores the data.
2986
  * @throws InvalidFirmwareException if interface 1 is not supported.
2987
  * @throws UsbException if a communication error occurs.
2988
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
2989
  * @throws IndexOutOfBoundsException If the buffer is smaller than the Flash page size.
2990
*/
2991
    public void xmegaFlashPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
2992
        checkCapability(CAPABILITY_XMEGA);
2993
 
2994
        if ( buf.length < xmegaFlashPageSize() )
2995
            throw new IndexOutOfBoundsException( "Buffer smaller than the Flash page size: " + buf.length + " < " + xmegaFlashPageSize);
2996
 
2997
        try {
2998
            vendorCommand2( 0x4b, "XMEGA Flash page write", addr, addr>> 16, buf, xmegaFlashPageSize );
2999
        }
3000
        catch ( UsbException e ) {
3001
            throw new UsbException( dev().dev(), "XMEGA Flash page write: " + xmegaStrError() );
3002
        }
3003
        try {
3004
            Thread.sleep( 3 );
3005
        }
3006
        catch ( InterruptedException e) {
3007
        }
3008
    }
3009
 
3010
// ******* xmegaEpromPageWrite *************************************************
3011
/**
3012
  * Writes data to EEPROM memory of ATxmega.
3013
  * @param addr The source address relative to the EEPROM memory base.
3014
  * @param buf A buffer that stores the data.
3015
  * @throws InvalidFirmwareException if interface 1 is not supported.
3016
  * @throws UsbException if a communication error occurs.
3017
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
3018
  * @throws IndexOutOfBoundsException If the buffer is smaller than the EEPROM page size.
3019
*/
3020
    public void xmegaEepromPageWrite ( int addr, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
3021
        checkCapability(CAPABILITY_XMEGA);
3022
 
3023
        if ( buf.length < xmegaEepromPageSize() )
3024
            throw new IndexOutOfBoundsException( "Buffer smaller than the EEPROM page size: " + buf.length + " < " + xmegaEepromPageSize);
3025
 
3026
        try {
3027
            vendorCommand2( 0x4c, "XMEGA EEPROM page write", addr, addr>> 16, buf, xmegaEepromPageSize );
3028
        }
3029
        catch ( UsbException e ) {
3030
            throw new UsbException( dev().dev(), "XMEGA EEPROM page write: " + xmegaStrError() );
3031
        }
3032
        try {
3033
            Thread.sleep( 3 );
3034
        }
3035
        catch ( InterruptedException e) {
3036
        }
3037
    }
3038
 
3039
// ******* xmegaFuseWrite ******************************************************
3040
/**
3041
  * Writes one Fuse of the ATxmega.
3042
  * @param addr The index of th Fuse.
3043
  * @param val The value of th Fuse.
3044
  * @throws InvalidFirmwareException if interface 1 is not supported.
3045
  * @throws UsbException if a communication error occurs.
3046
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
3047
*/
3048
    public void xmegaFuseWrite ( int addr, int val ) throws UsbException, InvalidFirmwareException, CapabilityException {
3049
        checkCapability(CAPABILITY_XMEGA);
3050
 
3051
        try {
3052
            vendorCommand( 0x4d, "XMEGA Fuse write", val, addr);
3053
        }
3054
        catch ( UsbException e ) {
3055
            throw new UsbException( dev().dev(), "XMEGA Fuse write: " + xmegaStrError() );
3056
        }
3057
        try {
3058
            Thread.sleep( 3 );
3059
        }
3060
        catch ( InterruptedException e) {
3061
        }
3062
    }
3063
 
3064
// ******* xmegaImgWrite *******************************************************
3065
/**
3066
  * Uploads data to NVM
3067
*/
3068
    private long xmegaImgWrite ( boolean toFlash, ImgFile imgFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
3069
        final int maxTries = 3;  // maximum amount of tries
3070
        int pageSize = toFlash ? xmegaFlashPageSize() : xmegaEepromPageSize();
3071
        checkCapability(CAPABILITY_XMEGA);
3072
 
3073
        long t0 = new Date().getTime();
3074
 
3075
        byte buf1[] = new byte[pageSize];
3076
        byte buf2[] = new byte[pageSize];
3077
 
3078
        for (int i = 0; i<65536; i+=pageSize ) {
3079
 
3080
            boolean b = false;
3081
            boolean c = true;
3082
            for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
3083
                boolean d = (imgFile.data[i+j]>=0) && (imgFile.data[i+j]<=255);  // data vaild ?
3084
                b |= d;
3085
                c &= d;
3086
            }
3087
            if ( b ) {   // page contains data ==> has to be written
3088
//              System.out.print("Page " + i +": " );
3089
 
3090
                // read page, if firmware image contains undefined bytes
3091
                if ( ! c ) {
3092
//                  System.out.print("R");
3093
                    if ( toFlash )
3094
                        xmegaFlashRead ( i, buf1, pageSize );
3095
                    else
3096
                        xmegaEepromRead ( i, buf1, pageSize );
3097
                }
3098
 
3099
                // prepare the page buffer
3100
                for ( int j=0; (j < pageSize ) && ( i+j < 65536 ); j++ ) {
3101
                    if ( (imgFile.data[i+j]>=0) && (imgFile.data[i+j]<=255) )
3102
                        buf1[j]= (byte) imgFile.data[i+j];
3103
                }
3104
 
3105
                for ( int k=1; b ; k++ ) {
3106
                    // write the page
3107
//                  System.out.print("W");
3108
                    if ( toFlash )
3109
                        xmegaFlashPageWrite ( i, buf1 );
3110
                    else
3111
                        xmegaEepromPageWrite ( i, buf1 );
3112
 
3113
                    // verify it
3114
//                  System.out.print("V");
3115
                    if ( toFlash )
3116
                        xmegaFlashRead ( i, buf2, pageSize );
3117
                    else
3118
                        xmegaEepromRead ( i, buf2, pageSize );
3119
                    b=false;
3120
                    for ( int j=0; (j < pageSize) && (! b ); j++ ) {
3121
                        b |= buf1[j] != buf2[j];
3122
                    }
3123
                    if ( b ) {
3124
                        if ( k<maxTries ) {
3125
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page" + i + " failed (try " + k +")" );
3126
                        }
3127
                        else {
3128
                            System.err.println("Warning: xmegaWriteFirmware: Verification of " + ( toFlash ? "Flash" : "EEPROM" ) + " page " + i + " failed");
3129
                        }
3130
                    }
3131
                    b = false;
3132
 
3133
//                  System.out.println();
3134
                }
3135
            }
3136
        }
3137
 
3138
        return new Date().getTime() - t0;
3139
    }
3140
 
3141
 
3142
 
3143
// ******* xmegaWriteFirmware **************************************************
3144
/**
3145
  * Uploads firmware to the flash memory
3146
  * @param imgFile The firmware / data image.
3147
  * @throws InvalidFirmwareException if interface 1 is not supported.
3148
  * @throws UsbException if a communication error occurs.
3149
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
3150
  * @throws FirmwareUploadException if the verification fails.
3151
  * @return the upload time in ms.
3152
*/
3153
    public long xmegaWriteFirmware ( ImgFile imgFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
3154
        return xmegaImgWrite( true, imgFile);
3155
    }
3156
 
3157
 
3158
// ******* xmegaWriteEeprom ****************************************************
3159
/**
3160
  * Uploads data to the EEPROM memory
3161
  * @param imgFile The firmware / data image.
3162
  * @throws InvalidFirmwareException if interface 1 is not supported.
3163
  * @throws UsbException if a communication error occurs.
3164
  * @throws CapabilityException if NVRAM access to ATxmega is not supported by the firmware.
3165
  * @throws FirmwareUploadException if the verification fails.
3166
  * @return the upload time in ms.
3167
*/
3168
    public long xmegaWriteEeprom ( ImgFile imgFile ) throws UsbException, InvalidFirmwareException, CapabilityException, FirmwareUploadException {
3169
        return xmegaImgWrite( false, imgFile);
3170
    }
3171
 
3172
 
3173
// ******* toString ************************************************************
3174
/**
3175
  * Returns a lot of useful information about the corresponding device.
3176
  * @return a lot of useful information about the corresponding device.
3177
  */
3178
    public String toString () {
3179
        String str = dev().toString();
3180
        try {
3181
            str += "\n   " + getFpgaConfigurationStr();
3182
        }
3183
        catch ( Exception e ) {
3184
        }
3185
        return str;
3186
    }
3187
 
3188
// ******* capabilityInfo ******************************************************
3189
/**
3190
  * Creates a String with capability information.
3191
  * @param pf A separator between the single capabilities, e.g. ", "
3192
  * @return a string of the supported capabilities.
3193
  */
3194
    public String capabilityInfo ( String pf ) {
3195
        String str = "";
3196
        for ( int i=0; i<6; i++ )
3197
            for (int j=0; j<8; j++ )
3198
                if ( dev().interfaceCapabilities(i,j) ) {
3199
                    if ( ! str.equals("") )
3200
                        str+=pf;
3201
                    if (i*8+j < capabilityStrings.length)
3202
                        str+=capabilityStrings[i*8+j];
3203
                    else
3204
                        str+=i+"."+j;
3205
                }
3206
        return str;
3207
    }
3208
// ******* configureFpgaHS *****************************************************
3209
//  returns configuration time in ms
3210
/**
3211
  * Upload a Bitstream to the FPGA using high speed mode.
3212
  * @param inputStream for reading the Bitstream.
3213
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
3214
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
3215
  * @return Configuration time in ms.
3216
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
3217
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
3218
  * @throws AlreadyConfiguredException if the FPGA is already configured.
3219
  * @throws InvalidFirmwareException if interface 1 is not supported.
3220
  * @throws UsbException if a communication error occurs.
3221
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
3222
  */
3223
    public long configureFpgaHS ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
3224
        final int transactionBytes = 64*1024;
3225
        long t0 = 0;
3226
        byte[] settings = new byte[2];
3227
        boolean releaseIF;
3228
 
3229
        checkCapability(CAPABILITY_HS_FPGA);
3230
        vendorRequest2(0x33, "getHSFpgaSettings", settings, 2);
3231
 
3232
        if ( !force && getFpgaConfiguration() )
3233
            throw new AlreadyConfiguredException();
3234
 
3235
        releaseIF = ! getInterfaceClaimed(settings[1] & 255);
3236
//      System.out.println("EP "+ settings[0] + "    IF "+settings[1]+ "   claim " + releaseIF);
3237
 
3238
// read the Bitstream file      
3239
        ByteBuffer[] buffers = new ByteBuffer[64*1024*1024/transactionBytes];
3240
        byte[] buf = new byte[transactionBytes];
3241
 
3242
        int size = 0;
3243
        try {
3244
            int j = transactionBytes;
3245
            for ( int i=0; i<buffers.length && j==transactionBytes; i++ ) {
3246
                int k;
3247
                // 512 bytes dummy data
3248
                if ( i== 0 ) {
3249
                    for (int l=0; l<512; l++ ) buf[l]=0;
3250
                    j=512;
3251
                }
3252
                else  {
3253
                    j = 0;
3254
                }
3255
                do {
3256
                    k = inputStream.read( buf, j, transactionBytes-j );
3257
                    if ( k < 0 ) k = 0;
3258
                    j += k;
3259
                }
3260
                while ( j<transactionBytes && k>0 );
3261
 
3262
                if ( (i==0) && ( bs<0 || bs>1 ) ) {
3263
                    bs = detectBitstreamBitOrder ( buf );
3264
//                  System.out.println(bs);
3265
                }
3266
 
3267
                if ( bs == 1 ) swapBits(buf, j);
3268
 
3269
                buffers[i] = allocateByteBuffer(buf, 0, j);
3270
                size += j;
3271
            }
3272
 
3273
            try {
3274
                inputStream.close();
3275
            }
3276
            catch ( Exception e ) {
3277
            }
3278
        }
3279
        catch (IOException e) {
3280
            throw new BitstreamReadException(e.getLocalizedMessage());
3281
        }
3282
 
3283
        if ( size < 64 )
3284
            throw new BitstreamReadException("Invalid file size: " + size );
3285
 
3286
// remove NOP's from the end
3287
/*      System.out.println(size);
3288
        while ( size-2>=0 && buffer[(size-2) / transactionBytes][(size-2) % transactionBytes] == 4 && buffer[(size-1) / transactionBytes][(size-1) % transactionBytes]==0 )
3289
            size-=2;
3290
        System.out.println(size);
3291
*/
3292
 
3293
// claim interface if required
3294
        if ( releaseIF ) claimInterface( settings[1] & 255 );
3295
 
3296
//      System.out.println(size & 127);
3297
 
3298
// upload the Bitstream file    
3299
        for ( int tries=3; tries>0; tries-- ) {
3300
            vendorCommand(0x34, "initHSFPGAConfiguration" );
3301
 
3302
            try {
3303
                t0 = -new Date().getTime();
3304
                for ( int i=0; i<buffers.length && i*transactionBytes < size; i++ ) {
3305
                    int j = size-i*transactionBytes;
3306
                    if (j>transactionBytes)
3307
                        j = transactionBytes;
3308
 
3309
                    if ( j>0 ) {
3310
                        int l = bulkWrite(settings[0] & 255, buffers[i], 1000);
3311
                        if ( l < 0 ) l = bulkWrite(settings[0] & 255, buffers[i], 1000);   // one retry
3312
                        if ( l < 0 )
3313
                            throw new UsbException("Error sending Bitstream: " + l + ": " + LibUsb.strError(l));
3314
                        else if ( l != j )
3315
                            throw new UsbException("Error sending Bitstream: Sent " + l +" of " + j + " bytes");
3316
                    }
3317
                }
3318
 
3319
                try {
3320
                    Thread.sleep( (size % transactionBytes) / 1000 + 10 );
3321
                }
3322
                catch ( InterruptedException e) {
3323
                }
3324
 
3325
                vendorCommand(0x35, "finishHSFPGAConfiguration" );
3326
                t0 += new Date().getTime();
3327
 
3328
                getFpgaState();
3329
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+size+")   fpgaInitB="+fpgaInitB + "  time=" + t0);
3330
                if ( ! fpgaConfigured ) {
3331
                    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") + ")" );
3332
                }
3333
 
3334
                if ( enableExtraFpgaConfigurationChecks ) {
3335
                    if ( fpgaBytes!=0 && fpgaBytes!=size )
3336
                        System.err.println("Warning: Possible FPGA configuration data loss: " + (size - fpgaBytes) + " bytes got lost");
3337
                    if ( fpgaInitB!=222 )
3338
                        System.err.println("Warning: Possible Bitstream CRC error: INIT_B_HIST=" + fpgaInitB );
3339
                }
3340
 
3341
                tries = 0;
3342
            }
3343
            catch ( BitstreamUploadException e ) {
3344
                if (tries == 1)
3345
                    throw e;
3346
                else if ( tries<3 || enableExtraFpgaConfigurationChecks )
3347
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
3348
            }
3349
        }
3350
 
3351
        if ( releaseIF ) releaseInterface( settings[1] & 255 );
3352
 
3353
        try {
3354
            Thread.sleep( 25 );
3355
        }
3356
        catch ( InterruptedException e) {
3357
        }
3358
 
3359
        return t0;
3360
    }
3361
 
3362
/**
3363
  * Upload a Bitstream to the FPGA using high speed mode.
3364
  * @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).
3365
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
3366
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
3367
  * @return Configuration time in ms.
3368
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
3369
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
3370
  * @throws AlreadyConfiguredException if the FPGA is already configured.
3371
  * @throws InvalidFirmwareException if interface 1 is not supported.
3372
  * @throws UsbException if a communication error occurs.
3373
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
3374
  */
3375
    public long configureFpgaHS ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
3376
        try {
3377
            return configureFpgaHS( JInputStream.getInputStream( fwFileName ), force, bs );
3378
        }
3379
        catch (IOException e) {
3380
            throw new BitstreamReadException(e.getLocalizedMessage());
3381
        }
3382
    }
3383
 
3384
// ******* configureFpga *****************************************************
3385
//  returns configuration time in ms
3386
/**
3387
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
3388
  * @param inputStream for reading the Bitstream.
3389
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
3390
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
3391
  * @return Configuration time in ms.
3392
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
3393
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
3394
  * @throws AlreadyConfiguredException if the FPGA is already configured.
3395
  * @throws InvalidFirmwareException if interface 1 is not supported.
3396
  * @throws UsbException if a communication error occurs.
3397
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
3398
  * @throws IOException if mark/reset is not supported
3399
  */
3400
    public long configureFpga ( InputStream inputStream, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException, IOException {
3401
        try {
3402
            inputStream.mark(64*1024*1024);
3403
            return configureFpgaHS( inputStream, force, bs );
3404
        }
3405
        catch ( CapabilityException e ) {
3406
            return configureFpgaLS( inputStream, force, bs );
3407
        }
3408
        catch ( UsbException e ) {
3409
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
3410
            inputStream.reset();
3411
            return configureFpgaLS( inputStream, force, bs );
3412
        }
3413
        catch ( BitstreamUploadException e ) {
3414
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
3415
            inputStream.reset();
3416
            return configureFpgaLS( inputStream, force, bs );
3417
        }
3418
    }
3419
 
3420
/**
3421
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
3422
  * @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).
3423
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
3424
  * @param bs 0: disable bit swapping, 1: enable bit swapping, all other values: automatic detection of bit order.
3425
  * @return Configuration time in ms.
3426
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
3427
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
3428
  * @throws AlreadyConfiguredException if the FPGA is already configured.
3429
  * @throws InvalidFirmwareException if interface 1 is not supported.
3430
  * @throws UsbException if a communication error occurs.
3431
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
3432
  */
3433
    public long configureFpga ( String fwFileName, boolean force, int bs ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
3434
        try {
3435
            return configureFpgaHS( fwFileName, force, bs );
3436
        }
3437
        catch ( CapabilityException e ) {
3438
            return configureFpgaLS( fwFileName, force, bs );
3439
        }
3440
        catch ( UsbException e ) {
3441
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
3442
            return configureFpgaLS( fwFileName, force, bs );
3443
        }
3444
        catch ( BitstreamUploadException e ) {
3445
            System.err.println("Warning: High speed FPGA configuration failed, trying low speed mode:" + e.getLocalizedMessage() +": Trying low speed mode");
3446
            return configureFpgaLS( fwFileName, force, bs );
3447
        }
3448
    }
3449
 
3450
/**
3451
  * Upload a Bitstream to the FPGA using high speed mode (if available) or low speed mode.
3452
  * @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).
3453
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
3454
  * @return Configuration time in ms.
3455
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
3456
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
3457
  * @throws AlreadyConfiguredException if the FPGA is already configured.
3458
  * @throws InvalidFirmwareException if interface 1 is not supported.
3459
  * @throws UsbException if a communication error occurs.
3460
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
3461
  */
3462
    public long configureFpga ( String fwFileName, boolean force ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
3463
        return configureFpga(fwFileName, force, -1);
3464
    }
3465
 
3466
// ******* macEepromWrite ******************************************************
3467
/**
3468
  * Writes data to the MAC EEPROM.
3469
  * @param addr The destination address of the MAC EEPROM.
3470
  * @param buf The data.
3471
  * @param length The amount of bytes to be sent.
3472
  * @throws InvalidFirmwareException if interface 1 is not supported.
3473
  * @throws UsbException if a communication error occurs.
3474
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware or if configuration data is present and there is a write to addresses 0 to 79. In order to override this behavior set {@link #config} variable to null.
3475
  */
3476
    public void macEepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
3477
        checkCapability(CAPABILITY_MAC_EEPROM);
3478
        if ( ( config != null ) && ( addr<80 ))
3479
            throw new CapabilityException(this, "Overwriting configuration data in MAC EEPROM");
3480
        vendorCommand2( 0x3C, "MAC EEPROM Write", addr, 0, buf, length );
3481
        try {
3482
            Thread.sleep( 10 );
3483
        }
3484
        catch ( InterruptedException e) {
3485
        }
3486
    }
3487
 
3488
// ******* macEepromRead *******************************************************
3489
/**
3490
  * Reads data from the MAC EEPROM.
3491
  * @param addr The source address of the MAC EEPROM.
3492
  * @param buf A buffer for the storage of the data.
3493
  * @param length The amount of bytes to be read.
3494
  * @throws InvalidFirmwareException if interface 1 is not supported.
3495
  * @throws UsbException if a communication error occurs.
3496
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
3497
  */
3498
    public void macEepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
3499
        checkCapability(CAPABILITY_MAC_EEPROM);
3500
        vendorRequest2( 0x3B, "MAC EEPROM Read", addr, 0, buf, length );
3501
        try {
3502
            Thread.sleep( 10 );
3503
        }
3504
        catch ( InterruptedException e) {
3505
        }
3506
    }
3507
 
3508
// ******* macEepromState ******************************************************
3509
// returns true if MAC EEPROM is ready
3510
/**
3511
  * Reads the current MAC EEPROM status.
3512
  * @throws InvalidFirmwareException if interface 1 is not supported.
3513
  * @throws UsbException if a communication error occurs.
3514
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
3515
  * @return true if MAC EEPROM is ready.
3516
  */
3517
    public boolean macEepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
3518
        byte[] buf = new byte[1];
3519
        checkCapability(CAPABILITY_MAC_EEPROM);
3520
        vendorRequest2(0x3D, "MAC EEPROM State", 0, 0, buf, 1);
3521
        return buf[0] == 0;
3522
    }
3523
 
3524
// ******* macRead *************************************************************
3525
/**
3526
  * Reads MAC address from MAC EEPROM.
3527
  * @param buf A buffer with a minimum size of 6 bytes.
3528
  * @throws InvalidFirmwareException if interface 1 is not supported.
3529
  * @throws UsbException if a communication error occurs.
3530
  * @throws CapabilityException if MAC EEPROM access is not supported by the firmware.
3531
  * @throws IndexOutOfBoundsException If the buffer is smaller than 6 bytes.
3532
  */
3533
    public void macRead ( byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
3534
        if ( buf.length < 6 )
3535
            throw new IndexOutOfBoundsException( "macRead: Buffer smaller than 6 Bytes" );
3536
        macEepromRead(250, buf, 6);
3537
    }
3538
 
3539
// ******* numberOfFpgas *******************************************************
3540
/**
3541
  * Returns the number of FPGA's
3542
  * @throws InvalidFirmwareException if interface 1 is not supported.
3543
  * @throws UsbException if a communication error occurs.
3544
  * @return number of FPGA's
3545
  */
3546
    public int numberOfFpgas ( ) throws UsbException, InvalidFirmwareException {
3547
        if ( numberOfFpgas < 0 ) {
3548
            try {
3549
                byte[] buffer = new byte[3];
3550
                checkCapability(CAPABILITY_MULTI_FPGA);
3551
                vendorRequest2(0x50, "getMultiFpgaInfo", buffer, 3);
3552
                numberOfFpgas = (buffer[0] & 255)+1;
3553
                selectedFpga = buffer[1] & 255;
3554
                parallelConfigSupport = buffer[2]==1;
3555
            }
3556
            catch ( CapabilityException e ) {
3557
                numberOfFpgas = 1;
3558
                selectedFpga = 0;
3559
                parallelConfigSupport = false;
3560
            }
3561
        }
3562
        return numberOfFpgas;
3563
    }
3564
 
3565
// ******* selectFpga **********************************************************
3566
/**
3567
  * Select a FPGA
3568
  * @param num FPGA to select. Valid values are 0 to {@link #numberOfFpgas()}-1
3569
  * @throws InvalidFirmwareException if interface 1 is not supported.
3570
  * @throws UsbException if a communication error occurs.
3571
  * @throws IndexOutOfBoundsException If FPGA number is not in range.
3572
  */
3573
    public void selectFpga ( int num ) throws UsbException, InvalidFirmwareException, IndexOutOfBoundsException {
3574
        numberOfFpgas();
3575
        if ( num<0 || num>=numberOfFpgas )
3576
            throw new IndexOutOfBoundsException( "selectFPGA: Invalid FPGA number" );
3577
 
3578
        if ( numberOfFpgas != 1 ) {
3579
            try {
3580
                checkCapability(CAPABILITY_MULTI_FPGA);
3581
                vendorCommand( 0x51, "selectFPGA", num, 0);
3582
            }
3583
            catch ( CapabilityException e ) {
3584
                // should'nt occur
3585
            }
3586
        }
3587
        selectedFpga = num;
3588
    }
3589
 
3590
// ******* TempSensorRead ******************************************************
3591
/**
3592
  * Read temperature sensor data.
3593
  * @param idx Temperature sensor index
3594
  * @return Temperature in deg. C
3595
  * @throws InvalidFirmwareException If interface 1 or temperature sensor protocol is not supported.
3596
  * @throws UsbException If a communication error occurs.
3597
  * @throws CapabilityException If NVRAM access to ATxmega is not supported by the firmware.
3598
  * @throws IndexOutOfBoundsException If idx is not in range.
3599
  */
3600
    public double tempSensorRead ( int idx ) throws UsbException, InvalidFirmwareException, CapabilityException, IndexOutOfBoundsException {
3601
        int[] xIdx = { 3, 4, 1, 2 };
3602
 
3603
        checkCapability(CAPABILITY_TEMP_SENSOR);
3604
 
3605
        int len = 0;
3606
 
3607
        if ( tempSensorUpdateInterval < 40 )
3608
            tempSensorUpdateInterval = 40;
3609
 
3610
        if ( new Date().getTime() > lastTempSensorReadTime+tempSensorUpdateInterval ) {
3611
            len = vendorRequest( 0x58, "Temperature Sensor Read", 0, 0, tempSensorBuf, tempSensorBuf.length );
3612
            lastTempSensorReadTime = new Date().getTime();
3613
 
3614
            if ( len != 5 || tempSensorBuf[0] != 1 )
3615
                throw new InvalidFirmwareException("tempSensorRead: Invalid temperature sensor protocol");
3616
        }
3617
 
3618
        if ( idx<0 || idx>3 )
3619
            throw new IndexOutOfBoundsException( "tempSensorRead: Invalid temperature sensor index" );
3620
 
3621
        return ((tempSensorBuf[xIdx[idx]] & 255)-77.2727)/1.5454;
3622
    }
3623
 
3624
// ******* printSpiState *******************************************************
3625
// returns true if Flash is available
3626
/**
3627
  * Prints out some debug information about SPI Flash.<br>
3628
  * <b>Only use this method if such kind of Flash is installed.</b>
3629
  * @throws InvalidFirmwareException if interface 1 is not supported.
3630
  * @throws UsbException if a communication error occurs.
3631
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
3632
  * @return true if flash is enabled
3633
  */
3634
    public boolean printSpiState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
3635
        byte[] buf = new byte[10];
3636
        checkCapability(CAPABILITY_FLASH);
3637
        vendorRequest2(0x43, "SPI State", 0, 0, buf, 10);
3638
        System.out.println("ec=" + buf[0] +
3639
                "   vendor=" + Integer.toHexString(buf[1] & 255).toUpperCase() + "h" +
3640
                "   device=" + Integer.toHexString(buf[2] & 255).toUpperCase() + "h" +
3641
                "   memType=" + Integer.toHexString(buf[3] & 255).toUpperCase() + "h" +
3642
                "   eraseCmd=" + Integer.toHexString(buf[4] & 255).toUpperCase() + "h" +
3643
                "   lastCmd=" + Integer.toHexString(buf[5] & 255).toUpperCase() + "h" +
3644
                "   buf=" + (buf[6] & 255)+" "+(buf[7] & 255)+" "+(buf[8] & 255)+" "+(buf[9] & 255)
3645
            );
3646
        return flashEnabled == 1;
3647
    }
3648
 
3649
// ******* debug2GetMessage *******************************************************
3650
/**
3651
  * Reads a debug message with given Index in raw format.
3652
  * Valid indixes are {@link #debug2LastIdx()}-{@link #debug2Cnt()} to {@link #debug2LastIdx()}-1.
3653
  * Data format is:
3654
  * <table bgcolor="#404040" cellspacing=1 cellpadding=4>
3655
  *   <tr>
3656
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
3657
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
3658
  *   </tr>
3659
  *   <tr>
3660
  *     <td bgcolor="#ffffff" valign="top">0</td>
3661
  *     <td bgcolor="#ffffff" valign="top">Type</td>
3662
  *   </tr>
3663
  *   <tr>
3664
  *     <td bgcolor="#ffffff" valign="top">1..length</td>
3665
  *     <td bgcolor="#ffffff" valign="top">Message</td>
3666
  *   </tr>
3667
  * </table>
3668
  * @return A buffer with the raw message. (Length of the message is result.length-1)
3669
  * @param idx Index of message.
3670
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3671
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3672
  * @throws UsbException if a communication error occurs.
3673
  */
3674
    public byte[] debug2GetMessage ( int idx ) throws UsbException, InvalidFirmwareException, CapabilityException {
3675
        int length = idx < 0 ? 10 : 4096;
3676
        byte[] buf = new byte[length];
3677
        checkCapability(CAPABILITY_DEBUG2);
3678
        length = vendorRequest(0x28, "Read Debug 2 Message", idx>>16, idx & 65535, buf, length);
3679
        if ( length<10 ) throw new InvalidFirmwareException(this, "Invalid result from VR 0x28");
3680
        debug2EC = (buf[0] & 255);
3681
        debug2LastIdx = (buf[1] & 255) | ((buf[2] & 255) << 8) | ((buf[3] & 255) << 16) | ((buf[4] & 255) << 24);
3682
        debug2Cnt = (buf[5] & 255) | ((buf[6] & 255)<<8);
3683
        if ( idx < 0 ) {
3684
            buf[9] = -1;
3685
        }
3686
        return Arrays.copyOfRange(buf,9,length);
3687
    }
3688
 
3689
// ******* debug2LastIdx **********************************************************
3690
/**
3691
  * Returns index of last message + 1
3692
  * @return index of last message + 1
3693
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3694
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3695
  * @throws UsbException if a communication error occurs.
3696
  */
3697
    public int debug2LastIdx ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
3698
        debug2GetMessage(-1);
3699
        return debug2LastIdx;
3700
    }
3701
 
3702
// ******* debug2EC ************************************************************
3703
/**
3704
  * Returns an error code if a fatal error occurred (0 if no error occurred)
3705
  * @return error code.
3706
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3707
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3708
  * @throws UsbException if a communication error occurs.
3709
  */
3710
    public int debug2EC ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
3711
        debug2GetMessage(-1);
3712
        return debug2EC;
3713
    }
3714
 
3715
// ******* debug2Cnt ************************************************************
3716
/**
3717
  * Returns the number of messages in buffer.
3718
  * @return Returns the number of buffered messages.
3719
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3720
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3721
  * @throws UsbException if a communication error occurs.
3722
  */
3723
    public int debug2Cnt ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
3724
        debug2GetMessage(-1);
3725
        return debug2Cnt;
3726
    }
3727
 
3728
 
3729
// ******* debug2GetNextLogMessage *********************************************
3730
/**
3731
  * Reads the next log message in string format.
3732
  * The message index is {@link #debug2LogIdx} which is incremented by this function.
3733
  * null is returned if no log message is available.
3734
  * @return The log message.
3735
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3736
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3737
  * @throws UsbException if a communication error occurs.
3738
  */
3739
    public String debug2GetNextLogMessage () throws UsbException, InvalidFirmwareException, CapabilityException {
3740
        byte[] buf;
3741
        int i;
3742
        do {
3743
            buf = debug2GetMessage(debug2LogIdx);
3744
            if ( debug2LogIdx >= debug2LastIdx ) {
3745
                return null;
3746
            }
3747
            debug2LogIdx++;
3748
        } while ( buf[0]!=1 && buf[0]!=2 );
3749
 
3750
        return buf[0]==1 ? new String(buf,1,buf.length-1) : ( "Runtime error " + ( i = ((buf[1]&255) | ((buf[2]&255)<<8)) ) + " occured at line " + ( (buf[3]&255) | ((buf[4]&255)<<8) ) + " of " + new String(buf,5,buf.length-5)+": "+Fx3Errors.errStr(i));
3751
    }
3752
 
3753
// ******* debug2PrintNextLogMessages ******************************************
3754
/**
3755
  * Prints new log message. Index if the first message is {@link #debug2LogIdx} which is incremented by this function.
3756
  * Returns quietly if debug2 functionality is not supported.
3757
  * @param out destination for printing the messages.
3758
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3759
  * @throws UsbException if a communication error occurs.
3760
  */
3761
    public void debug2PrintNextLogMessages ( PrintStream out ) throws UsbException, InvalidFirmwareException {
3762
        try {
3763
            String str;
3764
            do {
3765
                str = debug2GetNextLogMessage();
3766
                if ( str != null ) out.println(str);
3767
            } while ( str != null );
3768
        } catch ( CapabilityException e ) {
3769
        }
3770
    }
3771
 
3772
 
3773
// ******* getUsb3Errors *******************************************************
3774
/**
3775
  * Reads USB 3.0 errors and stores them in {@link #usb3SndErrors} {@link #usb3RcvErrors}.
3776
  * @throws InvalidFirmwareException if interface 1 is not supported or invalid result is returned.
3777
  * @throws UsbException if a communication error occurs.
3778
  * @throws CapabilityException Debug2 feature is not supported by firmware.
3779
  */
3780
    public void getUsb3Errors () throws UsbException, InvalidFirmwareException, CapabilityException {
3781
        byte[] buf = new byte[4];
3782
        checkCapability(CAPABILITY_DEBUG2);
3783
        vendorRequest2(0x29, "Read Debug 2 Message", 0, 0, buf, 4);
3784
        usb3SndErrors = (buf[0] & 255) | ((buf[1] & 255) << 8);
3785
        usb3RcvErrors = (buf[2] & 255) | ((buf[3] & 255) << 8);
3786
    }
3787
 
3788
 
3789
// ******* flashUploadFirmware *************************************************
3790
//  returns upload time in ms
3791
/**
3792
  * Upload the firmware to the Flash.
3793
  * In order to start the uploaded firmware the device must be reset.
3794
  * @param imgFile The firmware image.
3795
  * @param force Skips the compatibility check if true.
3796
  * @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.)
3797
  * @throws InvalidFirmwareException if interface 1 is not supported.
3798
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
3799
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
3800
  */
3801
    private long flashUploadFirmware (ImgFile imgFile, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
3802
        checkCapability(CAPABILITY_FLASH);
3803
        checkCapability(CAPABILITY_FX3);
3804
        if ( !imgFile.isFx3 ) throw new IncompatibleFirmwareException("FX3 firmware required");
3805
 
3806
        final int pagesMax = 16*1024;
3807
        int pages = 0;
3808
        byte[][] buffer = new byte[pagesMax][];
3809
 
3810
        int pageSize;
3811
        try {
3812
            pageSize = flashSectorSize();
3813
        }
3814
        catch ( UsbException e ) {
3815
            throw new FirmwareUploadException(e.getLocalizedMessage());
3816
        }
3817
 
3818
 
3819
// check for compatibility
3820
        if ( (imgFile instanceof ZtexImgFile1) && (!force) && dev().valid() ) {
3821
            if ( ((ZtexImgFile1)imgFile).interfaceVersion() != 1 )
3822
                throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ((ZtexImgFile1)imgFile).interfaceVersion() );
3823
 
3824
            if ( ! dev().compatible ( ((ZtexImgFile1)imgFile).productId(0), ((ZtexImgFile1)imgFile).productId(1), ((ZtexImgFile1)imgFile).productId(2), ((ZtexImgFile1)imgFile).productId(3) ) )
3825
                throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev().productId())
3826
                    + "  Img File: " + ZtexDevice1.byteArrayString(((ZtexImgFile1)imgFile).productId()) );
3827
        }
3828
 
3829
        buffer[0] = new byte[pageSize];
3830
        buffer[0][0]='C';
3831
        buffer[0][1]='Y';
3832
        buffer[0][2]=32;         // execution binary, 30MHz SPI speed
3833
        buffer[0][3]=(byte) (0xb0 & 255);
3834
 
3835
        int ptr = 4, i = 0, cs = 0;
3836
 
3837
        while ( i < imgFile.data.length ) {
3838
            while (i<imgFile.data.length && (imgFile.data[i]<0 || imgFile.data[i]>255) )
3839
                i+=1;
3840
 
3841
            int j=0;
3842
            while ( i+j*4+3<imgFile.data.length &&
3843
                    (  (imgFile.data[i+j*4+0]>=0 && imgFile.data[i+j*4+0]<256)
3844
                    || (imgFile.data[i+j*4+1]>=0 && imgFile.data[i+j*4+1]<256)
3845
                    || (imgFile.data[i+j*4+2]>=0 && imgFile.data[i+j*4+2]<256)
3846
                    || (imgFile.data[i+j*4+3]>=0 && imgFile.data[i+j*4+3]<256) ) )
3847
                j+=1;
3848
            if ( j > 0 ) {
3849
                for (int k=ptr/pageSize + 1; k <= (ptr + 8+j*4+11)/pageSize; k++ )      // also considers 12 bytes for the last data block
3850
                    buffer[k] = new byte[pageSize];
3851
 
3852
                buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) (j & 255);          // length
3853
                buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) ((j >> 8) & 255);
3854
                buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((j >> 16) & 255);
3855
                buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) ((j >> 24) & 255);
3856
 
3857
                long a = ImgFile.uncompressAddr(i);
3858
//              System.out.println(i+"  "+Long.toHexString(a));             
3859
                if ( (a & 3) !=0 ) throw new InvalidFirmwareException("Invalid address alignment");
3860
                buffer[(ptr+4)/pageSize][(ptr+4) % pageSize] = (byte) (a & 255);                // address
3861
                buffer[(ptr+5)/pageSize][(ptr+5) % pageSize] = (byte) ((a >> 8) & 255);
3862
                buffer[(ptr+6)/pageSize][(ptr+6) % pageSize] = (byte) ((a >> 16) & 255);
3863
                buffer[(ptr+7)/pageSize][(ptr+7) % pageSize] = (byte) ((a >> 24) & 255);
3864
 
3865
                ptr+=8;
3866
                for ( int k=0; k<j*4; k++ )                                                      // data
3867
                    buffer[(ptr+k)/pageSize][(ptr+k) % pageSize] = (byte) imgFile.data[i+k];
3868
                for ( int k=0; k<j*4; k+=4 )                                                     // data
3869
                    cs += (imgFile.data[i+k] & 255) | ((imgFile.data[i+k+1] & 255)<<8) | ((imgFile.data[i+k+2] & 255)<<16) | ((imgFile.data[i+k+3] & 255) << 24);
3870
                ptr+=j*4;
3871
                i+=j*4;
3872
            }
3873
        }
3874
 
3875
        buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = 0;                                          // last record
3876
        buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = 0;
3877
        buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = 0;
3878
        buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = 0;
3879
 
3880
        buffer[(ptr+4)/pageSize][(ptr+4) % pageSize] = (byte) (imgFile.startVector & 255);              // start vector
3881
        buffer[(ptr+5)/pageSize][(ptr+5) % pageSize] = (byte) ((imgFile.startVector >> 8) & 255);
3882
        buffer[(ptr+6)/pageSize][(ptr+6) % pageSize] = (byte) ((imgFile.startVector >> 16) & 255);
3883
        buffer[(ptr+7)/pageSize][(ptr+7) % pageSize] = (byte) ((imgFile.startVector >> 24) & 255);
3884
 
3885
        buffer[(ptr+8)/pageSize][(ptr+8) % pageSize] = (byte) (cs & 255);                               // check sum
3886
        buffer[(ptr+9)/pageSize][(ptr+9) % pageSize] = (byte) ((cs >> 8) & 255);
3887
        buffer[(ptr+10)/pageSize][(ptr+10) % pageSize] = (byte) ((cs >> 16) & 255);
3888
        buffer[(ptr+11)/pageSize][(ptr+11) % pageSize] = (byte) ((cs >> 24) & 255);
3889
 
3890
        if ( config!=null && (ptr+11>config.getBitstreamStart()) ) {
3891
            throw new FirmwareUploadException("Firmware to large for the reserved area: " + toHumanStr(ptr+11) + " Bytes > " + toHumanStr(config.getBitstreamStart()) + " Bytes" );
3892
        }
3893
 
3894
/*      try {
3895
            FileOutputStream out = new FileOutputStream("test.img");
3896
            for (int k=0; k<=(ptr+11)/pageSize; k++ )
3897
                out.write(buffer[k], 0, Math.min(pageSize,ptr+12-k*pageSize));
3898
            out.close();
3899
        }
3900
        catch (Exception e) {
3901
            System.out.println("Error: "+e.getLocalizedMessage() );
3902
        } */
3903
 
3904
        // write firmware
3905
        long t0 = new Date().getTime();
3906
        try {
3907
            int j=(ptr+11)/pageSize;
3908
            for (int k=0; k<=j; k++) {
3909
                System.out.print("\rWriting sector " + (k+1) + " of " + (j+1));
3910
                flashWriteSector( k, 1, buffer[k] );    // write the Bitstream sectors
3911
            }
3912
            System.out.println();
3913
        }
3914
        catch ( UsbException e ) {
3915
            throw new FirmwareUploadException(e.getLocalizedMessage());
3916
        }
3917
 
3918
 
3919
        return new Date().getTime() - t0;
3920
    }
3921
 
3922
 
3923
// ******* flashDisableFirmware *************************************************
3924
/**
3925
  * Disables the firmware stored in the Flash.
3926
  * This is achieved by writing a "0" to the address 0.
3927
  * @throws InvalidFirmwareException if interface 1 is not supported.
3928
  * @throws CapabilityException if Flash access is not supported by the firmware.
3929
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
3930
  */
3931
    private void flashDisableFirmware ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
3932
        checkCapability(CAPABILITY_FLASH);
3933
        checkCapability(CAPABILITY_FX3);
3934
 
3935
        int pageSize;
3936
        try {
3937
            pageSize = flashSectorSize();
3938
        }
3939
        catch ( UsbException e ) {
3940
            throw new FirmwareUploadException(e.getLocalizedMessage());
3941
        }
3942
 
3943
        byte[] buf = new byte[pageSize];
3944
 
3945
        if ( config!=null && (config.getBitstreamStart()==0) ) {
3946
            System.err.println("Warning: No space reserved for firmware: firmware is not disabled");
3947
            return;
3948
        }
3949
 
3950
        try {
3951
            flashReadSector(0, 1, buf);
3952
            buf[0] = 0;
3953
            buf[1] = 0;
3954
            flashWriteSector(0, 1, buf);
3955
        }
3956
        catch ( UsbException e ) {
3957
            throw new FirmwareUploadException(e.getLocalizedMessage());
3958
        }
3959
    }
3960
 
3961
 
3962
// ******* defaultVersion *******************************************************
3963
/**
3964
  * Returns version of the default interface or 0 if default interface is not present.
3965
  * @return version of the default interface
3966
  * @throws InvalidFirmwareException if interface 1 is not supported.
3967
  * @throws UsbExcption if an error occurred while attempting to read default interface information.
3968
  */
3969
    public int defaultVersion ( ) throws InvalidFirmwareException, UsbException {
3970
        byte[] buf = new byte[4];
3971
 
3972
        if ( defaultVersion >= 0 ) return defaultVersion;
3973
        try {
3974
            checkCapability(CAPABILITY_DEFAULT);
3975
            vendorRequest2(0x64, "getDefaultInfo", buf, 4);
3976
            defaultVersion =  buf[0] & 255;
3977
            defaultOutEP =  buf[1] & 255;
3978
            defaultInEP =  buf[2] & 255;
3979
            defaultSubVersion =  buf[3] & 255;
3980
        }
3981
        catch ( CapabilityException e ) {
3982
            defaultVersion = 0;
3983
        }
3984
        return defaultVersion;
3985
    }
3986
 
3987
 
3988
// ******* defaultCheckVersion **************************************************
3989
/**
3990
  * Checks version of the default interface.
3991
  * If version number is less than required an exception it thrown.
3992
  * If the firmware is not up-to-date a warning is issued.
3993
  * @param version The minimum required version. Minimum valid version is 1.
3994
  * @throws InvalidFirmwareException if interface 1 is not supported.
3995
  * @throws CapabilityException if default interface if not present or version number is lower than required
3996
  * @throws UsbExcption if an error occurred while attempting to read default interface information.
3997
  */
3998
    public void defaultCheckVersion ( int version ) throws InvalidFirmwareException, UsbException, CapabilityException {
3999
        defaultVersion();
4000
        if ( defaultVersion < 1 ) throw new CapabilityException("Default interface not supported: Udpdate Default Firmware");
4001
        else if ( defaultVersion < version ) throw new CapabilityException("Invalid default interface version. Found: " + defaultVersion + ". Required: " + version + ". Update default firmware.");
4002
        if ( !defaultDisableWarnings && ((defaultVersion<defaultLatestVersion) || ((defaultVersion==defaultLatestVersion) && (defaultSubVersion<defaultLatestSubVersion)) ) ) {
4003
            System.err.println("Waning: Default interface is outdated. Update recommended.");
4004
            defaultDisableWarnings = true;
4005
        }
4006
    }
4007
 
4008
 
4009
// ******* defaultOutEP *********************************************************
4010
/**
4011
  * Returns output Endpoint of default interface
4012
  * used for high speed communication. The direction is seen from the host.
4013
  * @return output Endpoint for high speed communication of the default interface
4014
  * @throws InvalidFirmwareException if interface 1 is not supported.
4015
  * @throws CapabilityException if default interface if not present or version number is lower than required
4016
  * @throws UsbExcption if an error occurred while attempting to read default interface information.
4017
  */
4018
    public int defaultOutEP() throws InvalidFirmwareException, UsbException, CapabilityException {
4019
        defaultCheckVersion(1);
4020
        return defaultOutEP;
4021
    }
4022
 
4023
 
4024
// ******* defaultInEP **********************************************************
4025
/**
4026
  * Returns input Endpoint of default interface
4027
  * used for high speed communication. The direction is seen from the host. The result is or'ed with 128.
4028
  * @return input Endpoint for high speed communication of the default interface
4029
  * @throws InvalidFirmwareException if interface 1 is not supported.
4030
  * @throws CapabilityException if default interface if not present or version number is lower than required
4031
  * @throws UsbExcption if an error occurred while attempting to read default interface information.
4032
  */
4033
    public int defaultInEP() throws InvalidFirmwareException, UsbException, CapabilityException {
4034
        defaultCheckVersion(1);
4035
        return defaultInEP | 128;
4036
    }
4037
 
4038
 
4039
// ******* defaultSubVersion ***************************************************
4040
/**
4041
  * Returns sub-version of the default interface.
4042
  * @return sub-version of the default interface
4043
  * @throws InvalidFirmwareException if interface 1 is not supported.
4044
  * @throws UsbExcption if an error occurred while attempting to read default interface information.
4045
  */
4046
    public int defaultSubVersion ( ) throws InvalidFirmwareException, UsbException, CapabilityException {
4047
        defaultCheckVersion(1);
4048
        return defaultSubVersion;
4049
    }
4050
 
4051
// ******* defaultReset *********************************************************
4052
/**
4053
  * Assert the reset signal.
4054
  * @param leave if true, the signal is left active. Otherwise only a short impulse is sent.
4055
  * @throws InvalidFirmwareException if interface 1 is not supported.
4056
  * @throws CapabilityException if default interface if not present or version number is lower than required
4057
  * @throws UsbExcption if a communication error occurred.
4058
  */
4059
    public void defaultReset( boolean leave ) throws InvalidFirmwareException, UsbException, CapabilityException {
4060
        defaultCheckVersion(1);
4061
        vendorCommand (0x60, "Send reset signal", leave ? 1 : 0, 0);
4062
    }
4063
 
4064
// ******* defaultReset *********************************************************
4065
/**
4066
  * Assert the reset signal.
4067
  * Equvalent to defaultReset(false), see {@link #defaultReset(boolean)}
4068
  * @throws InvalidFirmwareException if interface 1 is not supported.
4069
  * @throws CapabilityException if default interface if not present or version number is lower than required
4070
  * @throws UsbExcption if a communication error occurred.
4071
  */
4072
    public void defaultReset () throws InvalidFirmwareException, UsbException, CapabilityException {
4073
        defaultReset(false);
4074
    }
4075
 
4076
// ******* defaultGpioCtl *******************************************************
4077
/**
4078
  * Reads and modifies the 4 GPIO pins.
4079
  * @param mask Bitmask for the pins which are modified. 1 means a bit is set. Only the lowest 4 bits are significant.
4080
  * @param value The bit values which are to be set. Only the lowest 4 bits are significant.
4081
  * @return current values of the GPIO's
4082
  * @throws InvalidFirmwareException if interface 1 is not supported.
4083
  * @throws CapabilityException if default interface if not present or version number is lower than required
4084
  * @throws UsbExcption if a communication error occurred.
4085
  */
4086
    public int defaultGpioCtl (int mask, int value) throws InvalidFirmwareException, UsbException, CapabilityException {
4087
        defaultCheckVersion(1);
4088
        byte[] buf = { 0 };
4089
        vendorRequest2 (0x61, "Set/get GPIO's", value, mask, buf, 1);
4090
        return buf[0];
4091
    }
4092
 
4093
 
4094
// ******* defaultLsiSet *******************************************************
4095
/**
4096
  * Send data to the low speed interface of default firmwares.
4097
  * It's implemented as a SRAM-like interface and is typically used used to read/write configuration data, debug information or other things.
4098
  * This function sets one register.
4099
  * @param addr The address. Valid values are 0 to 255.
4100
  * @param val The register data with a width of 32 Bit.
4101
  * @throws InvalidFirmwareException if interface 1 is not supported.
4102
  * @throws CapabilityException if default interface if not present or version number is lower than required
4103
  * @throws UsbExcption if a communication error occurred.
4104
  * @throws IndexOutOfBoundsException If the address is out of range.
4105
  */
4106
    public void defaultLsiSet (int addr, int val) throws InvalidFirmwareException, UsbException, CapabilityException, IndexOutOfBoundsException {
4107
        defaultCheckVersion(1);
4108
        if ((addr<0) || (addr>255)) throw new IndexOutOfBoundsException("LSI register address out of range: "+addr+". Valid values are 0..255");
4109
        byte[] buf = { (byte)(val), (byte)(val>>8), (byte)(val>>16), (byte)(val>>24), (byte)(addr & 255) };
4110
        vendorCommand2 (0x62, "Set lsi registers", 0,0, buf, 5);
4111
    }
4112
 
4113
 
4114
// ******* defaultLsiSet *******************************************************
4115
/**
4116
  * Send data to the low speed interface of default firmwares.
4117
  * It's implemented as a SRAM-like interface and is typically used used to read/write configuration data, debug information or other things.
4118
  * This function sets a sequential set of registers.
4119
  * @param addr The starting address address. Valid values are 0 to 255. Address is wrapped from 255 to 0.
4120
  * @param val The register data array with a word width of 32 Bit.
4121
  * @param length The length of the data array.
4122
  * @throws InvalidFirmwareException if interface 1 is not supported.
4123
  * @throws CapabilityException if default interface if not present or version number is lower than required
4124
  * @throws UsbExcption if a communication error occurred.
4125
  * @throws IndexOutOfBoundsException If the address is out of range or length is > 256
4126
  */
4127
    public void defaultLsiSet (int addr, int[] val, int length) throws InvalidFirmwareException, UsbException, CapabilityException, IndexOutOfBoundsException {
4128
        defaultCheckVersion(1);
4129
        if ((addr<0) || (addr>255)) throw new IndexOutOfBoundsException("LSI register address out of range: "+addr+". Valid values are 0..255");
4130
        if (length>256) throw new IndexOutOfBoundsException("LSI register set length to large: "+length+". Valid values are 1..256");
4131
        byte buf[] = new byte[length*5];
4132
        for (int i=0; i<length; i++) {
4133
            buf[i*5+0]=(byte)(val[i]);
4134
            buf[i*5+1]=(byte)(val[i]>>8);
4135
            buf[i*5+2]=(byte)(val[i]>>16);
4136
            buf[i*5+3]=(byte)(val[i]>>24);
4137
            buf[i*5+4]=(byte)(addr+i);
4138
        }
4139
        vendorCommand2 (0x62, "Write lsi registers", 0,0, buf, length*5);
4140
    }
4141
 
4142
 
4143
// ******* defaultLsiSet *******************************************************
4144
/**
4145
  * Send data to the low speed interface of default firmwares.
4146
  * It's implemented as a SRAM-like interface and is typically used used to read/write configuration data, debug information or other things.
4147
  * This function sets a random set of registers.
4148
  * @param addr The register addresses. Valid values are 0 to 255.
4149
  * @param val The register data array with a word width of 32 Bit.
4150
  * @param length The length of the data array.
4151
  * @throws InvalidFirmwareException if interface 1 is not supported.
4152
  * @throws CapabilityException if default interface if not present or version number is lower than required
4153
  * @throws UsbExcption if a communication error occurred.
4154
  * @throws IndexOutOfBoundsException If the address is out of range or length is > 256
4155
  */
4156
    public void defaultLsiSet (int[] addr, int[] val, int length) throws InvalidFirmwareException, UsbException, CapabilityException, IndexOutOfBoundsException {
4157
        defaultCheckVersion(1);
4158
        if (length>256) throw new IndexOutOfBoundsException("LSI register set length to large: "+addr+". Valid values are 1..256");
4159
        byte buf[] = new byte[length*5];
4160
        for (int i=0; i<length; i++) {
4161
            if ((addr[i]<0) || (addr[i]>255)) throw new IndexOutOfBoundsException("LSI register address out of range: "+addr[i]+". Valid values are 0..255");
4162
            buf[i*5+0]=(byte)(val[i]);
4163
            buf[i*5+1]=(byte)(val[i]>>8);
4164
            buf[i*5+2]=(byte)(val[i]>>16);
4165
            buf[i*5+3]=(byte)(val[i]>>24);
4166
            buf[i*5+4]=(byte)(addr[i]);
4167
        }
4168
        vendorCommand2 (0x62, "Write lsi registers", 0,0, buf, length*5);
4169
    }
4170
 
4171
// ******* defaultLsiGet *******************************************************
4172
/**
4173
  * Read data from the low speed interface of default firmwares.
4174
  * It's implemented as a SRAM-like interface and is typically used used to read/write configuration data, debug information or other things.
4175
  * This function reads one register.
4176
  * @param addr The address. Valid values are 0 to 255.
4177
  * @return The register value with a width of 32 Bit.
4178
  * @throws InvalidFirmwareException if interface 1 is not supported.
4179
  * @throws CapabilityException if default interface if not present or version number is lower than required
4180
  * @throws UsbExcption if a communication error occurred.
4181
  * @throws IndexOutOfBoundsException If the address is out of range.
4182
  */
4183
    public int defaultLsiGet (int addr) throws InvalidFirmwareException, UsbException, CapabilityException, IndexOutOfBoundsException {
4184
        byte buf[] = new byte[4];
4185
        defaultCheckVersion(1);
4186
        if ((addr<0) || (addr>255)) throw new IndexOutOfBoundsException("LSI register address out of range: "+addr+". Valid values are 0..255");
4187
        vendorRequest2 (0x63, "Read lsi registers", 0,addr, buf, 4);
4188
        return (buf[0] & 255) | ((buf[1] & 255)<<8) | ((buf[2] & 255)<<16) | ((buf[3] & 255)<<24);
4189
    }
4190
 
4191
// ******* defaultLsiGet *******************************************************
4192
/**
4193
  * Read data from the low speed interface of default firmwares.
4194
  * It's implemented as a SRAM-like interface and is typically used used to read/write configuration data, debug information or other things.
4195
  * This function reads a sequencial set of registers.
4196
  * @param addr The start address. Valid values are 0 to 255. Address is wrapped from 255 to 0.
4197
  * @param val The array where to store the register data with a word width of 32 Bit.
4198
  * @param length The amount of register to be read.
4199
  * @throws InvalidFirmwareException if interface 1 is not supported.
4200
  * @throws CapabilityException if default interface if not present or version number is lower than required
4201
  * @throws UsbExcption if a communication error occurred.
4202
  * @throws IndexOutOfBoundsException If the address is out of range or length is > 256
4203
  */
4204
    public void defaultLsiGet (int addr, int[] val, int length) throws InvalidFirmwareException, UsbException, CapabilityException, IndexOutOfBoundsException {
4205
        byte buf[] = new byte[length*4];
4206
        defaultCheckVersion(1);
4207
        if ((addr<0) || (addr>255)) throw new IndexOutOfBoundsException("LSI register address out of range: "+addr+". Valid values are 0..255");
4208
        if (length>256) throw new IndexOutOfBoundsException("LSI register set length to large: "+addr+". Valid values are 1..256");
4209
        vendorRequest2 (0x63, "Read lsi registers", 0,addr, buf, length*4);
4210
        for (int i=0; i<length; i++)
4211
            val[i] = (buf[i*4+0] & 255) | ((buf[i*4+1] & 255)<<8) | ((buf[i*4+2] & 255)<<16) | ((buf[i*4+3] & 255)<<24);
4212
    }
4213
 
4214
}

powered by: WebSVN 2.1.0

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