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

Subversion Repositories usb_fpga_1_11

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

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

Line No. Rev Author Line
1 2 ZTEX
/*!
2
   Java Driver API for the ZTEX Firmware Kit
3
   Copyright (C) 2009-2010 ZTEX e.K.
4
   http://www.ztex.de
5
 
6
   This program is free software; you can redistribute it and/or modify
7
   it under the terms of the GNU General Public License version 3 as
8
   published by the Free Software Foundation.
9
 
10
   This program is distributed in the hope that it will be useful, but
11
   WITHOUT ANY WARRANTY; without even the implied warranty of
12
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
   General Public License for more details.
14
 
15
   You should have received a copy of the GNU General Public License
16
   along with this program; if not, see http://www.gnu.org/licenses/.
17
!*/
18
 
19
/*
20
    Functions for USB devices with ZTEX descriptor 1, Interface 1
21
    Interface capabilities and vendor requests (VR) / commands (VC):
22
    0.0  : EEPROM support
23
        VR 0x38 : read from EEPROM
24
            Returns:
25
                EEPROM data
26
        VC 0x39 : write to EEPROM
27
        VR 0x3a : EEPROM state
28
            Returns:
29
                Offs    Description
30
                0-1     bytes written
31
                2       checksum
32
                3       0:idle, 1:busy or error
33
 
34
    0.1  : FPGA Configuration
35
        VR 0x30 : get FPGA state
36
            Returns:
37
                Offs    Description
38
 
39
                1       checksum
40
                2-5     transferred bytes
41
                6       INIT_B state
42
        VC 0x31 : reset FPGA
43
        VC 0x32 : send FPGA configuration data (Bitstream)
44
 
45
    0.2  : Flash memory support
46
        VR 0x40 : Flash state
47
            Returns:
48
                Offs    Description
49
 
50
                1-2     Sector size
51
                3-6     Number of sectors
52
                7       Error code
53
        VR 0x41 : read from Flash
54
        VR 0x42 : write to Flash
55
*/
56
package ztex;
57
 
58
import java.io.*;
59
import java.util.*;
60
 
61
import ch.ntb.usb.*;
62
 
63
/**
64
  * This class implements the communication protocol of the interface version 1 for the interaction with the ZTEX firmware.
65
  * <p>
66
  * The features supported by this interface can be accessed via vendor commands and vendor requests via Endpoint 0.
67
  * Each feature can be enabled or disabled by the firmware and also depends from the hardware.
68
  * The presence of a feature is indicated by a 1 in the corresponding feature bit of the ZTEX descriptor 1, see {@link ZtexDevice1}.
69
  * The following table gives an overview about the features
70
  * <table bgcolor="#404040" cellspacing=1 cellpadding=10>
71
  *   <tr>
72
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Capability bit</b></td>
73
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
74
  *   </tr>
75
  *   <tr>
76
  *     <td bgcolor="#ffffff" valign="top">0.0</td>
77
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
78
  *       EEPROM support<p>
79
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
80
  *         <tr>
81
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
82
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
83
  *         </tr>
84
  *         <tr>
85
  *           <td bgcolor="#ffffff" valign="top">VR 0x38</td>
86
  *           <td bgcolor="#ffffff" valign="top">Read from EEPROM</td>
87
  *         </tr>
88
  *         <tr>
89
  *           <td bgcolor="#ffffff" valign="top">VC 0x39</td>
90
  *           <td bgcolor="#ffffff" valign="top">Write to EEPROM</td>
91
  *         </tr>
92
  *         <tr>
93
  *           <td bgcolor="#ffffff" valign="top">VR 0x3a</td>
94
  *           <td bgcolor="#ffffff" valign="top">Get EEPROM state. Returns:
95
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
96
  *               <tr>
97
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
98
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
99
  *               </tr>
100
  *               <tr>
101
  *                 <td bgcolor="#ffffff" valign="top">0-1</td>
102
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes written.</td>
103
  *               </tr>
104
  *               <tr>
105
  *                 <td bgcolor="#ffffff" valign="top">2</td>
106
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
107
  *               </tr>
108
  *               <tr>
109
  *                 <td bgcolor="#ffffff" valign="top">3</td>
110
  *                 <td bgcolor="#ffffff" valign="top">0:idle, 1:busy or error</td>
111
  *               </tr>
112
  *             </table>
113
  *           </td>
114
  *         </tr>
115
  *       </table>
116
  *     </td>
117
  *   </tr>
118
  *   <tr>
119
  *     <td bgcolor="#ffffff" valign="top">0.1</td>
120
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
121
  *       FPGA Configuration<p>
122
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
123
  *         <tr>
124
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
125
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
126
  *         </tr>
127
  *         <tr>
128
  *           <td bgcolor="#ffffff" valign="top">VR 0x30</td>
129
  *           <td bgcolor="#ffffff" valign="top">Get FPGA state. Returns:
130
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
131
  *               <tr>
132
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
133
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
134
  *               </tr>
135
  *               <tr>
136
  *                 <td bgcolor="#ffffff" valign="top">0</td>
137
  *                 <td bgcolor="#ffffff" valign="top">1: unconfigured, 0:configured</td>
138
  *               </tr>
139
  *               <tr>
140
  *                 <td bgcolor="#ffffff" valign="top">1</td>
141
  *                 <td bgcolor="#ffffff" valign="top">Checksum</td>
142
  *               </tr>
143
  *               <tr>
144
  *                 <td bgcolor="#ffffff" valign="top">2-5</td>
145
  *                 <td bgcolor="#ffffff" valign="top">Number of bytes transferred.</td>
146
  *               </tr>
147
  *               <tr>
148
  *                 <td bgcolor="#ffffff" valign="top">6</td>
149
  *                 <td bgcolor="#ffffff" valign="top">INIT_B states (Must be 222).</td>
150
  *               </tr>
151
  *             </table>
152
  *           </td>
153
  *         </tr>
154
  *         <tr>
155
  *           <td bgcolor="#ffffff" valign="top">VC 0x31</td>
156
  *           <td bgcolor="#ffffff" valign="top">Reset FPGA</td>
157
  *         </tr>
158
  *         <tr>
159
  *           <td bgcolor="#ffffff" valign="top">VR 0x32</td>
160
  *           <td bgcolor="#ffffff" valign="top">Send Bitstream</td>
161
  *         </tr>
162
  *       </table>
163
  *     </td>
164
  *   </tr>
165
  *   <tr>
166
  *     <td bgcolor="#ffffff" valign="top">0.2</td>
167
  *     <td bgcolor="#ffffff" valign="top" colspan=2>
168
  *       Flash memory support<p>
169
  *       <table bgcolor="#404040" cellspacing=1 cellpadding=6>
170
  *         <tr>
171
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Vendor request (VR)<br> or command (VC)</b></td>
172
  *           <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
173
  *         </tr>
174
  *         <tr>
175
  *           <td bgcolor="#ffffff" valign="top">VR 0x40</td>
176
  *           <td bgcolor="#ffffff" valign="top">Get Flash state. Returns:
177
  *             <table bgcolor="#404040" cellspacing=1 cellpadding=4>
178
  *               <tr>
179
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
180
  *                 <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
181
  *               </tr>
182
  *               <tr>
183
  *                 <td bgcolor="#ffffff" valign="top">0</td>
184
  *                 <td bgcolor="#ffffff" valign="top">1:enabled, 0:disabled</td>
185
  *               </tr>
186
  *               <tr>
187
  *                 <td bgcolor="#ffffff" valign="top">1-2</td>
188
  *                 <td bgcolor="#ffffff" valign="top">Sector size</td>
189
  *               </tr>
190
  *               <tr>
191
  *                 <td bgcolor="#ffffff" valign="top">3-6</td>
192
  *                 <td bgcolor="#ffffff" valign="top">Number of sectors</td>
193
  *               </tr>
194
  *               <tr>
195
  *                 <td bgcolor="#ffffff" valign="top">7</td>
196
  *                 <td bgcolor="#ffffff" valign="top">Error code</td>
197
  *               </tr>
198
  *             </table>
199
  *           </td>
200
  *         </tr>
201
  *         <tr>
202
  *           <td bgcolor="#ffffff" valign="top">VR 0x41</td>
203
  *           <td bgcolor="#ffffff" valign="top">Read one sector from Flash</td>
204
  *         </tr>
205
  *         <tr>
206
  *           <td bgcolor="#ffffff" valign="top">VC 0x42</td>
207
  *           <td bgcolor="#ffffff" valign="top">Write one sector to Flash</td>
208
  *         </tr>
209
  *       </table>
210
  *     </td>
211
  *   </tr>
212
  * </table>
213
  * @see ZtexDevice1
214
  * @see Ztex1
215
  */
216
 
217
public class Ztex1v1 extends Ztex1 {
218
    /** * The names of the capabilities */
219
    public static final String capabilityStrings[] = {
220
        "EEPROM read/write" ,
221
        "FPGA configuration" ,
222
        "Flash memory support"
223
    };
224
 
225
    private boolean fpgaConfigured = false;
226
    private int fpgaChecksum = 0;
227
    private int fpgaBytes = 0;
228
    private int fpgaInitB = 0;
229
    private int fpgaFlashResult = 255;
230
    private boolean fpgaFlashBitSwap = false;
231
 
232
    /** * Number of bytes written to EEPROM. (Obtained by {@link #eepromState()}.) */
233
    public int eepromBytes = 0;
234
    /** * Checksum of the last EEPROM transfer. (Obtained by {@link #eepromState()}.) */
235
    public int eepromChecksum = 0;
236
 
237
    private int flashEnabled = -1;
238
    private int flashSectorSize = -1;
239
    private int flashSectors = -1;
240
 
241
    /** * Last Flash error code obtained by {@link #flashState()}. See FLASH_EC_* for possible error codes. */
242
    public int flashEC = 0;
243
    /** * Means no error. */
244
    public static final int FLASH_EC_NO_ERROR = 0;
245
    /** * Signals an error while attempting to execute a command. */
246
    public static final int FLASH_EC_CMD_ERROR = 1;
247
    /** * Signals that a timeout occurred. */
248
    public static final int FLASH_EC_TIMEOUT = 2;
249
    /** * Signals that Flash memory it busy. */
250
    public static final int FLASH_EC_BUSY = 3;
251
    /** * Signals that another Flash operation is pending. */
252
    public static final int FLASH_EC_PENDING = 4;
253
    /** * Signals an error while attempting to read from Flash. */
254
    public static final int FLASH_EC_READ_ERROR = 5;
255
    /** * Signals an error while attempting to write to Flash. */
256
    public static final int FLASH_EC_WRITE_ERROR = 6;
257
    /** * Signals the the installed Flash memeory is not supported. */
258
    public static final int FLASH_EC_NOTSUPPORTED = 7;
259
 
260
// ******* Ztex1v1 *************************************************************
261
/**
262
  * Constructs an instance from a given device.
263
  * @param pDev The given device.
264
  * @throws UsbException if an communication error occurred.
265
  */
266
    public Ztex1v1 ( ZtexDevice1 pDev ) throws UsbException {
267
        super ( pDev );
268
    }
269
 
270
// ******* valid ***************************************************************
271
/**
272
  * Returns true if ZTEX interface 1 is available.
273
  * @return true if ZTEX interface 1 is available.
274
  */
275
    public boolean valid ( ) {
276
        return dev().valid() && dev().interfaceVersion()==1;
277
    }
278
 
279
/**
280
  * Returns true if ZTEX interface 1 and capability i.j are available.
281
  * @param i byte index of the capability
282
  * @param j bit index of the capability
283
  * @return true if ZTEX interface 1 and capability i.j are available.
284
  */
285
    public boolean valid ( int i, int j) {
286
        return dev().valid() && dev().interfaceVersion()==1 && dev().interfaceCapabilities(i,j);
287
    }
288
 
289
// ******* compatible **********************************************************
290
/**
291
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.<br>
292
  * The given product ID is compatible
293
  * <pre>if ( this.productId(0)==0 || productId0<=0 || this.productId(0)==productId0 ) &&
294
   ( this.productId(0)==0 || productId1<=0 || this.productId(1)==productId1 ) &&
295
   ( this.productId(2)==0 || productId2<=0 || this.productId(2)==productId2 ) &&
296
   ( this.productId(3)==0 || productId3<=0 || this.productId(3)==productId3 ) </pre>
297
  * @param productId0 Byte 0 of the given product ID
298
  * @param productId1 Byte 1 of the given product ID
299
  * @param productId2 Byte 2 of the given product ID
300
  * @param productId3 Byte 3 of the given product ID
301
  * @return true if the given product ID is compatible and interface 1 is supported.
302
  */
303
    public boolean compatible ( int productId0, int productId1, int productId2, int productId3 ) {
304
        return dev().valid() && dev().compatible ( productId0, productId1, productId2, productId3 ) && dev().interfaceVersion()==1;
305
    }
306
 
307
// ******* checkValid **********************************************************
308
/**
309
  * Checks whether ZTEX descriptor 1 is available and interface 1 is supported.
310
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
311
  */
312
    public void checkValid () throws InvalidFirmwareException {
313
        super.checkValid();
314
        if ( dev().interfaceVersion() != 1 )
315
            throw new InvalidFirmwareException(this, "Wrong interface: " + dev().interfaceVersion() + ", expected: 1" );
316
    }
317
 
318
// ******* checkCapability *****************************************************
319
/**
320
  * Checks whether ZTEX descriptor 1 is available and interface 1 and a given capability are supported.
321
  * @param i byte index of the capability
322
  * @param j bit index of the capability
323
  * @throws InvalidFirmwareException if ZTEX descriptor 1 is not available or interface 1 is not supported.
324
  * @throws CapabilityException if the given capability is not supported.
325
  */
326
    public void checkCapability ( int i, int j ) throws InvalidFirmwareException, CapabilityException {
327
        checkValid();
328
        if ( ! dev().interfaceCapabilities(i,j) ) {
329
            int k = i*8 + j;
330
            if ( k>=0 && k<capabilityStrings.length )
331
            throw new CapabilityException( this, ( k>=0 && k<=capabilityStrings.length ) ? capabilityStrings[k] : ("Capabilty " + i + "," + j) );
332
        }
333
    }
334
 
335
// ******* checkCompatible *****************************************************
336
/**
337
  * Checks whether the given product ID is compatible to the device corresponding to this class and whether interface 1 is supported.
338
  * See {@link #compatible(int,int,int,int)}.
339
  * @param productId0 Byte 0 of the given product ID
340
  * @param productId1 Byte 1 of the given product ID
341
  * @param productId2 Byte 2 of the given product ID
342
  * @param productId3 Byte 3 of the given product ID
343
  * @throws InvalidFirmwareException if the given product ID is not compatible or interface 1 is not supported.
344
  */
345
    public void checkCompatible ( int productId0, int productId1, int productId2, int productId3 ) throws InvalidFirmwareException {
346
        checkValid();
347
        if ( ! dev().compatible ( productId0, productId1, productId2, productId3 ) )
348
            throw new InvalidFirmwareException(this, "Incompatible Product ID");
349
    }
350
 
351
// ******* getFpgaState ********************************************************
352
    private void getFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
353
        byte[] buffer = new byte[9];
354
        checkCapability(0,1);
355
        vendorRequest2(0x30, "getFpgaState", buffer, 9);
356
        fpgaConfigured = buffer[0] == 0;
357
        fpgaChecksum = buffer[1] & 0xff;
358
        fpgaBytes = ((buffer[5] & 0xff)<<24) | ((buffer[4] & 0xff)<<16) | ((buffer[3] & 0xff)<<8) | (buffer[2] & 0xff);
359
        fpgaInitB = buffer[6] & 0xff;
360
        fpgaFlashResult = buffer[7];
361
        fpgaFlashBitSwap = buffer[8] != 0;
362
    }
363
 
364
// ******* printFpgaState ******************************************************
365
/**
366
  * Prints out the FPGA state.
367
  * @throws InvalidFirmwareException if interface 1 is not supported.
368
  * @throws UsbException if a communication error occurs.
369
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
370
  */
371
    public void printFpgaState () throws UsbException, InvalidFirmwareException, CapabilityException {
372
        getFpgaState();
373
        System.out.println( "size=" + fpgaBytes + ";  checksum=" + fpgaChecksum + "; INIT_B_HIST=" + fpgaInitB +" (should be 222); flash_configuration_result=" + fpgaFlashResult );
374
    }
375
 
376
// ******* getFpgaConfiguration ************************************************
377
/**
378
  * Returns true if the FPGA is configured.
379
  * @return true if the FPGA is configured.
380
  * @throws InvalidFirmwareException if interface 1 is not supported.
381
  * @throws UsbException if a communication error occurs.
382
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
383
  */
384
    public boolean getFpgaConfiguration () throws UsbException, InvalidFirmwareException, CapabilityException {
385
        getFpgaState ();
386
        return fpgaConfigured;
387
    }
388
 
389
// ******* getFpgaConfigurationStr *********************************************
390
/**
391
  * Returns a string that indicates the FPGA configuration status.
392
  * @return a string that indicates the FPGA configuration status.
393
  * @throws InvalidFirmwareException if interface 1 is not supported.
394
  * @throws UsbException if a communication error occurs.
395
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
396
  */
397
    public String getFpgaConfigurationStr () throws UsbException, InvalidFirmwareException, CapabilityException {
398
        getFpgaState ();
399
        return fpgaConfigured ? "FPGA configured" : "FPGA unconfigured";
400
    }
401
 
402
// ******* resetFGPA ***********************************************************
403
/**
404
  * Resets the FPGA.
405
  * @throws InvalidFirmwareException if interface 1 is not supported.
406
  * @throws UsbException if a communication error occurs.
407
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
408
  */
409
    public void resetFpga () throws UsbException, InvalidFirmwareException, CapabilityException {
410
        checkCapability(0,1);
411
        vendorCommand(0x31, "resetFpga" );
412
    }
413
 
414
// ******* configureFpga *******************************************************
415
//  returns configuration time in ms
416
/**
417
  * Upload a Bitstream to the FPGA.
418
  * @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).
419
  * @param force If set to true existing configurations will be overwritten. (By default an {@link AlreadyConfiguredException} is thrown).
420
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
421
  * @throws BitstreamUploadException if an error occurred while attempting to upload the Bitstream.
422
  * @throws AlreadyConfiguredException if the FPGA is already configured.
423
  * @throws InvalidFirmwareException if interface 1 is not supported.
424
  * @throws UsbException if a communication error occurs.
425
  * @throws CapabilityException if FPGA configuration is not supported by the firmware.
426
  */
427
    public long configureFpga ( String fwFileName, boolean force ) throws BitstreamReadException, UsbException, BitstreamUploadException, AlreadyConfiguredException, InvalidFirmwareException, CapabilityException {
428
        final int transactionBytes = certainWorkarounds ? 256 : 2048;
429
        long t0 = 0;
430
 
431
        checkCapability(0,1);
432
 
433
        if ( !force && getFpgaConfiguration() )
434
            throw new AlreadyConfiguredException();
435
 
436
// read the Bitstream file      
437
        byte[][] buffer = new byte[4*1024*1024/transactionBytes][];
438
        int size = 0;
439
        try {
440
            InputStream inputStream = JInputStream.getInputStream( fwFileName );
441
            int j = transactionBytes;
442
            for ( int i=0; i<buffer.length && j==transactionBytes; i++ ) {
443
                buffer[i] = new byte[transactionBytes];
444
                j = inputStream.read( buffer[i] );
445
                if ( j < 0 )
446
                    j = 0;
447
                if ( j < transactionBytes && j % 64 == 0 )       // ensures size % 64 != 0
448
                    j+=1;
449
                size += j;
450
            }
451
 
452
            try {
453
                inputStream.close();
454
            }
455
            catch ( Exception e ) {
456
                System.err.println( "Warning: Error closing file " + fwFileName + ": " + e.getLocalizedMessage() );
457
            }
458
        }
459
        catch (IOException e) {
460
            throw new BitstreamReadException(e.getLocalizedMessage());
461
        }
462
        if ( size < 64 || size % 64 == 0 )
463
            throw new BitstreamReadException("Invalid file size: " + size );
464
 
465
// upload the Bitstream file    
466
        for ( int tries=10; tries>0; tries-- ) {
467
 
468
            resetFpga();
469
 
470
            try {
471
                t0 = -new Date().getTime();
472
                int cs = 0;
473
                int bs = 0;
474
 
475
                for ( int i=0; i<buffer.length && i*transactionBytes < size; i++ ) {
476
                    int j = size-i*transactionBytes;
477
                    if (j>transactionBytes)
478
                        j = transactionBytes;
479
                    vendorCommand2(0x32, "sendFpgaData", 0,0, buffer[i], j);
480
 
481
                    bs+=j;
482
                    for ( int k=0; k<buffer[i].length; k++ )
483
                        cs = ( cs + (buffer[i][k] & 0xff) ) & 0xff;
484
                }
485
 
486
                getFpgaState();
487
//              System.err.println("fpgaConfigred=" + fpgaConfigured + "   fpgaBytes="+fpgaBytes + " ("+bs+")   fpgaChecksum="+fpgaChecksum + " ("+cs+")   fpgaInitB="+fpgaInitB );
488
                if ( ! fpgaConfigured ) {
489
                    throw new BitstreamUploadException( "FPGA configuration failed: DONE pin does not go high (size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes went lost;  checksum="
490
                        + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB +", should be 222)" );
491
                }
492
//              System.out.println( "FPGA configuration: size=" + fpgaBytes + " ,  " + (bs - fpgaBytes) + " bytes went lost;  checksum=" + fpgaChecksum + " , should be " + cs + ";  INIT_B_HIST=" + fpgaInitB +", should be 222" );
493
//              if ( fpgaInitB != 222 )
494
//                  System.err.println ( "Warning: FPGA configuration may have failed: DONE pin has gone high but INIT_B states are wrong: " + fpgaInitB +", should be 222");
495
 
496
                tries = 0;
497
                t0 += new Date().getTime();
498
 
499
            }
500
            catch ( BitstreamUploadException e ) {
501
                if ( tries>1 )
502
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
503
                else
504
                    throw e;
505
            }
506
        }
507
 
508
        try {
509
            Thread.sleep( 200 );
510
        }
511
        catch ( InterruptedException e) {
512
        }
513
 
514
        return t0;
515
    }
516
 
517
// ******* eepromState *********************************************************
518
// returns true if EEPROM is ready
519
/**
520
  * Reads the current EEPROM status.
521
  * This method also sets the varibles {@link #eepromBytes} and {@link #eepromChecksum}.
522
  * @throws InvalidFirmwareException if interface 1 is not supported.
523
  * @throws UsbException if a communication error occurs.
524
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
525
  * @return true if EEPROM is ready.
526
  */
527
    public boolean eepromState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
528
        byte[] buf = new byte[4];
529
        checkCapability(0,0);
530
        vendorRequest2(0x3A, "EEPROM State", 0, 0, buf, 4);
531
        eepromBytes = (buf[0] & 255) | (buf[1] & 255)<<8;
532
        eepromChecksum = buf[2] & 255;
533
        return buf[3] == 0;
534
    }
535
 
536
// ******* eepromWrite *********************************************************
537
/**
538
  * Writes data to the EEPROM.
539
  * @param addr The destination address of the EEPROM.
540
  * @param buf The data.
541
  * @param length The amount of bytes to be sent.
542
  * @throws InvalidFirmwareException if interface 1 is not supported.
543
  * @throws UsbException if a communication error occurs.
544
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
545
  */
546
    public void eepromWrite ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
547
        checkCapability(0,0);
548
        vendorCommand2( 0x39, "EEPROM Write", addr, 0, buf, length );
549
        try {
550
            Thread.sleep( 10 );
551
        }
552
        catch ( InterruptedException e) {
553
        }
554
    }
555
 
556
// ******* eepromRead **********************************************************
557
/**
558
  * Reads data from the EEPROM.
559
  * @param addr The source address of the EEPROM.
560
  * @param buf A buffer for the storage of the data.
561
  * @param length The amount of bytes to be read.
562
  * @throws InvalidFirmwareException if interface 1 is not supported.
563
  * @throws UsbException if a communication error occurs.
564
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
565
  */
566
    public void eepromRead ( int addr, byte[] buf, int length ) throws UsbException, InvalidFirmwareException, CapabilityException {
567
        checkCapability(0,0);
568
        vendorRequest2( 0x38, "EEPROM Read", addr, 0, buf, length );             // sometimes a little bit slow
569
        try {
570
            Thread.sleep( 10 );
571
        }
572
        catch ( InterruptedException e) {
573
        }
574
    }
575
 
576
// ******* eepromUpload ********************************************************
577
//  returns upload time in ms
578
/**
579
  * Upload the firmware to the EEPROM.
580
  * In order to start the uploaded firmware the device must be reset.
581
  * @param ihxFileName The file name of the firmware image in ihx format. The file can be a regular file or a system resource (e.g. a file from the current jar archive).
582
  * @param force Skips the compatibility check if true.
583
  * @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.)
584
  * @throws InvalidFirmwareException if interface 1 is not supported.
585
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
586
  * @throws FirmwareUploadException if an error occurred while attempting to upload the firmware.
587
  */
588
    public long eepromUpload ( String ihxFileName, boolean force ) throws IncompatibleFirmwareException, FirmwareUploadException, InvalidFirmwareException, CapabilityException {
589
        final int pagesMax = 256;
590
        final int pageSize = 256;
591
        int pages = 0;
592
        byte[][] buffer = new byte[pagesMax][];
593
 
594
        checkCapability(0,0);
595
 
596
// load the ihx file
597
        ZtexIhxFile1 ihxFile;
598
        try {
599
            ihxFile = new ZtexIhxFile1( ihxFileName );
600
        }
601
        catch ( IOException e ) {
602
            throw new FirmwareUploadException( e.getLocalizedMessage() );
603
        }
604
        catch ( IhxFileDamagedException e ) {
605
            throw new FirmwareUploadException( e.getLocalizedMessage() );
606
        }
607
//      ihxFile.dataInfo(System.out);
608
//      System.out.println(ihxFile);
609
 
610
// check for compatibility
611
        if ( ! force && dev().valid() ) {
612
            if ( ihxFile.interfaceVersion() != 1 )
613
                throw new IncompatibleFirmwareException("Wrong interface version: Expected 1, got " + ihxFile.interfaceVersion() );
614
 
615
            if ( ! dev().compatible ( ihxFile.productId(0), ihxFile.productId(1), ihxFile.productId(2), ihxFile.productId(3) ) )
616
                throw new IncompatibleFirmwareException("Incompatible productId's: Current firmware: " + ZtexDevice1.byteArrayString(dev().productId())
617
                    + "  Ihx File: " + ZtexDevice1.byteArrayString(ihxFile.productId()) );
618
        }
619
 
620
        Usb_Device_Descriptor dd = dev().dev().getDescriptor();
621
        int vid = dd.getIdVendor() & 65535;
622
        int pid = dd.getIdProduct() & 65535;
623
 
624
        buffer[0] = new byte[pageSize];
625
        buffer[0][0] = (byte) 0xc2;
626
        buffer[0][1] = (byte) (vid & 255);
627
        buffer[0][2] = (byte) ((vid >> 8) & 255);
628
        buffer[0][3] = (byte) (pid & 255);
629
        buffer[0][4] = (byte) ((pid >> 8) & 255);
630
        buffer[0][5] = 0;
631
        buffer[0][6] = 0;
632
        buffer[0][7] = 0;
633
 
634
        int ptr = 8, i = 0;
635
 
636
        while ( i < ihxFile.ihxData.length ) {
637
            if ( ihxFile.ihxData[i]>=0 && ihxFile.ihxData[i]<256 ) {                     // new data block
638
                int j = 1;
639
                while ( i+j<ihxFile.ihxData.length && ihxFile.ihxData[i+j]>=0 && ihxFile.ihxData[i+j]<255 )
640
                    j++;
641
 
642
                for (int k=ptr/pageSize + 1; k < (ptr+j+4)/pageSize + 1; k++ )  // also considers 5 bytes for the last data block
643
                    buffer[k] = new byte[pageSize];
644
 
645
                buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) ((j >> 8) & 255);
646
                buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) (j & 255);                // length
647
                buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) ((i >> 8) & 255);
648
                buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) (i & 255);                // address
649
                ptr+=4;
650
                for ( int k=0; k<j; k++ )                                        // data
651
                    buffer[(ptr+k)/pageSize][(ptr+k) % pageSize] = (byte) ihxFile.ihxData[i+k];
652
                ptr+=j;
653
                i+=j;
654
            }
655
            else {
656
                i+=1;
657
            }
658
        }
659
 
660
        buffer[(ptr+0)/pageSize][(ptr+0) % pageSize] = (byte) 0x80;               // last data block
661
        buffer[(ptr+1)/pageSize][(ptr+1) % pageSize] = (byte) 0x01;
662
        buffer[(ptr+2)/pageSize][(ptr+2) % pageSize] = (byte) 0xe6;
663
        buffer[(ptr+3)/pageSize][(ptr+3) % pageSize] = (byte) 0x00;
664
        buffer[(ptr+3)/pageSize][(ptr+4) % pageSize] = (byte) 0x00;
665
        ptr+=5;
666
 
667
 
668
        long t0 = new Date().getTime();
669
        byte[] rbuf = new byte[pageSize];
670
 
671
        for ( i=(ptr-1)/pageSize; i>=0; i-- ) {
672
 
673
            int k = (i+1)*pageSize < ptr ? pageSize : ptr-i*pageSize;
674
            int cs = 0;
675
            for (int j=0; j<k; j++ ) {
676
                cs = ( cs + (buffer[i][j] & 255) ) & 255;
677
            }
678
 
679
            for ( int tries=3; tries>0; tries-- ) {
680
                try {
681
                    eepromWrite(i*pageSize, buffer[i], k);
682
                    eepromState();
683
                    if ( eepromBytes!=k )
684
                        throw new FirmwareUploadException("Error writing data to EEPROM: Wrote " + eepromBytes + " bytes instead of "  + k + " bytes" );
685
                    if ( eepromChecksum!=cs )
686
                        throw new FirmwareUploadException("Error writing data to EEPROM: Checksum error");
687
 
688
                    eepromRead(i*pageSize, rbuf, k);
689
                    for (int j=0; j<k; j++ ) {
690
                        if ( rbuf[j] != buffer[i][j] )
691
                            throw new FirmwareUploadException("Error writing data to EEPROM: Verification failed");
692
                    }
693
                    tries = 0;
694
                }
695
                catch ( Exception e ) {
696
                    if ( tries > 1 ) {
697
                        System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
698
                    }
699
                    else {
700
                        throw new FirmwareUploadException(e.getLocalizedMessage());
701
                    }
702
                }
703
            }
704
        }
705
 
706
        return new Date().getTime() - t0;
707
    }
708
 
709
 
710
// ******* eepromDisable ********************************************************
711
/**
712
  * Disables the firmware stored in the EEPROM.
713
  * This is achived by writing a "0" to the address 0 of the EEPROM.
714
  * @throws InvalidFirmwareException if interface 1 is not supported.
715
  * @throws CapabilityException if EEPROM access is not supported by the firmware.
716
  * @throws FirmwareUploadException if an error occurred while attempting to disable the firmware.
717
  */
718
    public void eepromDisable ( ) throws FirmwareUploadException, InvalidFirmwareException, CapabilityException {
719
        byte[] buf = { 0 };
720
 
721
        for ( int tries=3; tries>0; tries-- ) {
722
            try {
723
                eepromWrite(0, buf, 1);
724
 
725
                eepromRead(0, buf, 1);
726
                if ( buf[0] != 0 )
727
                    throw new FirmwareUploadException("Error disabeling EEPROM firmware: Verification failed");
728
                tries = 0;
729
 
730
            }
731
            catch ( Exception e ) {
732
                if ( tries > 1 ) {
733
                    System.err.println("Warning: " + e.getLocalizedMessage() +": Retrying it ...");
734
                }
735
                else {
736
                    throw new FirmwareUploadException(e.getLocalizedMessage());
737
                }
738
            }
739
        }
740
    }
741
 
742
// ******* flashStrError *******************************************************
743
/**
744
  * Converts a given error code into a String.
745
  * @param errNum The error code.
746
  * @return an error message.
747
  */
748
    public static String flashStrError ( int errNum ) {
749
        switch ( errNum ) {
750
            case FLASH_EC_NO_ERROR:
751
                return "USB error: " + LibusbJava.usb_strerror();
752
            case FLASH_EC_CMD_ERROR:
753
                return "Command error";
754
            case FLASH_EC_TIMEOUT:
755
                return "Timeout error";
756
            case FLASH_EC_BUSY:
757
                return "Busy";
758
            case FLASH_EC_PENDING:
759
                return "Another operation is pending";
760
            case FLASH_EC_READ_ERROR:
761
                return "Read error";
762
            case FLASH_EC_WRITE_ERROR:
763
                return "Write error";
764
            case FLASH_EC_NOTSUPPORTED:
765
                return "Not supported";
766
        }
767
        return "Error " + errNum;
768
    }
769
 
770
/**
771
  * Gets the last Flash error from the device.
772
  * @return an error message.
773
  */
774
    public String flashStrError ( ) {
775
        try {
776
            return flashStrError( getFlashEC() );
777
        }
778
        catch ( Exception e ) {
779
            return "Unknown error (Error receiving errorcode: "+e.getLocalizedMessage() +")";
780
        }
781
    }
782
 
783
// ******* flashState **********************************************************
784
/**
785
  * Reads the the Flash memory status and information.
786
  * This method also sets the variables {@link #flashEnabled}, {@link #flashSectorSize} and {@link #flashSectors}.
787
  * @return true if Flash memory is installed.
788
  * @throws InvalidFirmwareException if interface 1 is not supported.
789
  * @throws UsbException if a communication error occurs.
790
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
791
  */
792
    public boolean flashState () throws UsbException, InvalidFirmwareException, CapabilityException {
793
        byte[] buf = new byte[8];
794
        checkCapability(0,2);
795
 
796
        // device may be busy due to initialization, we try it up to up to 4s
797
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
798
        flashEC = buf[7] & 255;
799
        int tries=20;
800
        while ( flashEC==FLASH_EC_BUSY && tries>0 )
801
        {
802
            try {
803
                Thread.sleep( 200 );
804
            }
805
            catch ( InterruptedException e) {
806
            }
807
            tries-=1;
808
            vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
809
            flashEC = buf[7] & 255;
810
        }
811
        flashEnabled = buf[0] & 255;
812
        flashSectorSize = flashEnabled == 1 ? ((buf[2] & 255) << 8) | (buf[1] & 255) : 0;
813
        flashSectors = flashEnabled == 1 ? ((buf[6] & 255) << 24) | ((buf[5] & 255) << 16) | ((buf[4] & 255) << 8) | (buf[3] & 255) : 0;
814
        return flashEnabled == 1;
815
    }
816
 
817
// ******* getFlashEC **********************************************************
818
// reads the current error code
819
/**
820
  * Gets the last Flash error from the device.
821
  * @throws InvalidFirmwareException if interface 1 is not supported.
822
  * @throws UsbException if a communication error occurs.
823
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
824
  */
825
    public int getFlashEC () throws UsbException, InvalidFirmwareException, CapabilityException {
826
        byte[] buf = new byte[8];
827
        checkCapability(0,2);
828
        vendorRequest2(0x40, "Flash State", 0, 0, buf, 8);
829
        flashEC = buf[7] & 255;
830
        return flashEC;
831
    }
832
 
833
// ******* flashReadSector ****************************************************
834
// read exactly one sector
835
/**
836
  * Reads one sector from the Flash.
837
  * @param sector The sector number to be read.
838
  * @param buf A buffer for the storage of the data.
839
  * @throws InvalidFirmwareException if interface 1 is not supported.
840
  * @throws UsbException if a communication error occurs.
841
  * @throws CapabilityException if Flash memory access is not possible.
842
  */
843
    public void flashReadSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException {
844
        checkCapability(0,2);
845
        if ( ! flashEnabled() )
846
            throw new CapabilityException(this, "No Flash memory installed or");
847
 
848
        try {
849
            vendorRequest2( 0x41, "Flash Read", sector, sector >> 16, buf, flashSectorSize );
850
        }
851
        catch ( UsbException e ) {
852
            throw new UsbException( dev().dev(), "Flash Read: " + flashStrError() );
853
        }
854
    }
855
 
856
// ******* flashWriteSector ***************************************************
857
// write exactly one sector
858
/**
859
  * Writes one sector to the Flash.
860
  * @param sector The sector number to be written.
861
  * @param buf The data.
862
  * @throws InvalidFirmwareException if interface 1 is not supported.
863
  * @throws UsbException if a communication error occurs.
864
  * @throws CapabilityException if Flash memory access is not possible.
865
  */
866
    public void flashWriteSector ( int sector, byte[] buf ) throws UsbException, InvalidFirmwareException, CapabilityException {
867
        checkCapability(0,2);
868
        if ( ! flashEnabled() )
869
            throw new CapabilityException(this, "No Flash memory installed or");
870
 
871
        try {
872
            vendorCommand2( 0x42, "Flash Write", sector, sector >> 16, buf, flashSectorSize );
873
        }
874
        catch ( UsbException e ) {
875
            throw new UsbException( dev().dev(), "Flash Write: " + flashStrError() );
876
        }
877
    }
878
 
879
// ******* flashEnabled ********************************************************
880
// returns enabled / disabled state 
881
/**
882
  * Returns true if Flash memory is installed.
883
  * @return true if Flash memory is installed.
884
  * @throws InvalidFirmwareException if interface 1 is not supported.
885
  * @throws UsbException if a communication error occurs.
886
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
887
  */
888
    public boolean flashEnabled () throws UsbException, InvalidFirmwareException, CapabilityException {
889
        if ( flashEnabled < 0 ) // init variable
890
            flashState();
891
        return flashEnabled == 1;
892
    }
893
 
894
// ******* flashSectorSize *****************************************************
895
// returns sector size of Flash memory, if available
896
/**
897
  * Returns the sector size of the Flash memory or 0, if no flash memory is installed.
898
  * If required, the sector size is determined form the device first.
899
  * @return the sector size of the Flash memory.
900
  * @throws InvalidFirmwareException if interface 1 is not supported.
901
  * @throws UsbException if a communication error occurs.
902
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
903
  */
904
    public int flashSectorSize () throws UsbException, InvalidFirmwareException, CapabilityException {
905
        if ( flashSectorSize < 0 ) // init variable
906
            flashState();
907
        return flashSectorSize;
908
    }
909
 
910
// ******* flashSectors ********************************************************
911
// returns number of sectors of Flash memory, if available
912
/**
913
  * Returns the number of sectors of the Flash memory or 0, if no Flash memory is installed.
914
  * If required, the number of sectors is determined form the device first.
915
  * @return the number of sectors of the Flash memory.
916
  * @throws InvalidFirmwareException if interface 1 is not supported.
917
  * @throws UsbException if a communication error occurs.
918
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
919
  */
920
    public int flashSectors () throws UsbException, InvalidFirmwareException, CapabilityException {
921
        if ( flashSectors < 0 ) // init variable
922
            flashState();
923
        return flashSectors;
924
    }
925
 
926
// ******* flashSize ***********************************************************
927
// returns size of Flash memory, if available
928
/**
929
  * Returns the size of Flash memory or 0, if no Flash memory is installed.
930
  * If required, the Flash size is determined form the device first.
931
  * @return the size of Flash memory.
932
  * @throws InvalidFirmwareException if interface 1 is not supported.
933
  * @throws UsbException if a communication error occurs.
934
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
935
  */
936
    public long flashSize () throws UsbException, InvalidFirmwareException, CapabilityException {
937
        return flashSectorSize() * (long)flashSectors();
938
    }
939
 
940
// ******* printMmcState *******************************************************
941
// returns true if Flash is available
942
/**
943
  * Prints out some debug information about *SD/MMC Flash cards in SPI mode.<br>
944
  * <b>Only use this method if such kind of Flash is installed.</b>
945
  * @throws InvalidFirmwareException if interface 1 is not supported.
946
  * @throws UsbException if a communication error occurs.
947
  * @throws CapabilityException if Flash memory access is not supported by the firmware.
948
  */
949
    public boolean printMmcState ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
950
        byte[] buf = new byte[23];
951
        checkCapability(0,2);
952
        vendorRequest2(0x43, "MMC State", 0, 0, buf, 23);
953
        System.out.println("status=" + Integer.toBinaryString(256+(buf[0] & 255)).substring(1) + "." + Integer.toBinaryString(256+(buf[1] & 255)).substring(1) +
954
                "   lastCmd=" + buf[3] +
955
                "   lastCmdResponse=" + Integer.toBinaryString(256+(buf[4] & 255)).substring(1) +
956
                "   ec=" + buf[2] +
957
                "   BUSY=" + buf[22] +
958
                "   SDHC=" + buf[5] +
959
                "   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));
960
 
961
        return flashEnabled == 1;
962
    }
963
 
964
// ******* flashUploadBitstream ************************************************
965
/*
966
    Returns configuration time in ms.
967
    The format of the boot sector (sector 0 of the Flash memory) is
968
        0..7
969
        8..9    Number of sectors, or 0 is disabled
970
        10..11  Number of bytes in the last sector, i.e. th total size of Bitstream is ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
971
*/
972
/**
973
  * Uploads a Bitstream to the Flash.
974
  * This allows the firmware to load the Bitstream from Flash. Together with installation of the firmware in EEPROM
975
  * it is possible to construct fully autonomous devices.
976
  * <p>
977
  * Information about the bitstream is stored in sector 0.
978
  * This so called boot sector has the following format:
979
  * <table bgcolor="#404040" cellspacing=1 cellpadding=4>
980
  *   <tr>
981
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Bytes</b></td>
982
  *     <td bgcolor="#d0d0d0" valign="bottom"><b>Description</b></td>
983
  *   </tr>
984
  *   <tr>
985
  *     <td bgcolor="#ffffff" valign="top">0..7</td>
986
  *     <td bgcolor="#ffffff" valign="top">ID, must be "ZTEXBS",1,1</td>
987
  *   </tr>
988
  *   <tr>
989
  *     <td bgcolor="#ffffff" valign="top">8..9</td>
990
  *     <td bgcolor="#ffffff" valign="top">The number of sectors used to store the Bitstream. 0 means no Bitstream.</td>
991
  *   </tr>
992
  *   <tr>
993
  *     <td bgcolor="#ffffff" valign="top">10..11</td>
994
  *     <td bgcolor="#ffffff" valign="top">The number of bytes in the last sector.</td>
995
  *   </tr>
996
  *   <tr>
997
  *     <td bgcolor="#ffffff" valign="top">12..sectorSize-1</td>
998
  *     <td bgcolor="#ffffff" valign="top">This data is reserved for future use and preserved by this method.</td>
999
  *   </tr>
1000
  * </table>
1001
  * <p>
1002
  * The total size of the Bitstream is computed as ((bs[8] | (bs[9]<<8) - 1) * flash_sector_size + ((bs[10] | (bs[11]<<8))
1003
  * where bs[i] denotes byte i of the boot sector.
1004
  * <p>
1005
  * The first sector of the Bitstream is sector 1.
1006
  * @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).
1007
  * @throws InvalidFirmwareException if interface 1 is not supported.
1008
  * @throws UsbException if a communication error occurs.
1009
  * @throws CapabilityException if Flash memory access is not possible.
1010
  * @throws BitstreamReadException if an error occurred while attempting to read the Bitstream.
1011
  */
1012
    public long flashUploadBitstream ( String fwFileName ) throws BitstreamReadException, UsbException, InvalidFirmwareException, CapabilityException {
1013
        checkCapability(0,1);
1014
        checkCapability(0,2);
1015
        if ( ! flashEnabled() )
1016
            throw new CapabilityException(this, "No Flash memory installed or");
1017
        getFpgaState();
1018
 
1019
// read the Bitstream file      
1020
        byte[][] buffer = new byte[2048][];
1021
        int i,j;
1022
        try {
1023
            InputStream inputStream = JInputStream.getInputStream( fwFileName );
1024
            j = flashSectorSize;
1025
            for ( i=0; i<buffer.length && j==flashSectorSize; i++ ) {
1026
                buffer[i] = new byte[flashSectorSize];
1027
                j = inputStream.read( buffer[i] );
1028
                if ( fpgaFlashBitSwap ) {
1029
                    for (int k=0; k<flashSectorSize; k++ ) {
1030
                        byte b = buffer[i][k];
1031
                        buffer[i][k] = (byte) ( ((b & 128) >> 7) |
1032
                                                ((b &  64) >> 5) |
1033
                                                ((b &  32) >> 3) |
1034
                                                ((b &  16) >> 1) |
1035
                                                ((b &   8) << 1) |
1036
                                                ((b &   4) << 3) |
1037
                                                ((b &   2) << 5) |
1038
                                                ((b &   1) << 7));
1039
                    }
1040
                }
1041
                if ( j < 0 )
1042
                    j = 0;
1043
            }
1044
 
1045
            try {
1046
                inputStream.close();
1047
            }
1048
            catch ( Exception e ) {
1049
                System.err.println( "Warning: Error closing file " + fwFileName + ": " + e.getLocalizedMessage() );
1050
            }
1051
        }
1052
        catch (IOException e) {
1053
            throw new BitstreamReadException(e.getLocalizedMessage());
1054
        }
1055
 
1056
// upload the Bitstream file    
1057
        byte[] sector = new byte[flashSectorSize];
1058
        byte[] ID = new String("ZTEXBS").getBytes();
1059
 
1060
        flashReadSector(0,sector);                       // read the boot sector (only the first 16 bytes are overwritten)
1061
        for (int k=0; k<6; k++)
1062
            sector[k]=ID[k];
1063
        sector[6] = 1;
1064
        sector[7] = 1;
1065
        sector[8] = (byte) (i & 255);
1066
        sector[9] = (byte) ((i>>8) & 255);
1067
        sector[10] = (byte) (j & 255);
1068
        sector[11] = (byte) ((j>>8) & 255);
1069
        long t0 = new Date().getTime();
1070
        flashWriteSector(0,sector);                      // write the boot sector
1071
        for (int k=0; k<i; k++)
1072
            flashWriteSector(k+1,buffer[k]);            // write the Bitstream sectors
1073
 
1074
        return new Date().getTime() - t0;
1075
    }
1076
 
1077
// ******* flashResetBitstream *************************************************
1078
// Clears a Bitstream from the Flash.
1079
/**
1080
  * Clears a Bitstream from the Flash.
1081
  * This is achieved by writing 0 to bytes 8..9 of the boot sector, see {@link #flashUploadBitstream(String)}.
1082
  * If no boot sector is installed the method returns without any write action.
1083
  * @throws InvalidFirmwareException if interface 1 is not supported.
1084
  * @throws UsbException if a communication error occurs.
1085
  * @throws CapabilityException if Flash memory access is not possible.
1086
  */
1087
    public void flashResetBitstream ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1088
        checkCapability(0,2);
1089
        if ( ! flashEnabled() )
1090
            throw new CapabilityException(this, "No Flash memory installed or");
1091
        byte[] sector = new byte[flashSectorSize];
1092
        byte[] ID = new String("ZTEXBS").getBytes();
1093
 
1094
        flashReadSector(0,sector);                       // read the boot sector
1095
        for (int k=0; k<6; k++)
1096
            if ( sector[k] != ID[k] )
1097
                return;
1098
        if (sector[6]!=1 || sector[7]!=1 )
1099
            return;
1100
        sector[8] = 0;
1101
        sector[9] = 0;
1102
        flashWriteSector(0,sector);                      // write the boot sector
1103
    }
1104
 
1105
// ******* flashFirstFreeSector ************************************************
1106
// Returns the first free sector of the Flash memory, i.e. the first sector behind the Bitstream
1107
/**
1108
  * Returns the first free sector of the Flash memory.
1109
  * 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).
1110
  * @return the first free sector of the Flash memory.
1111
  * @throws InvalidFirmwareException if interface 1 is not supported.
1112
  * @throws UsbException if a communication error occurs.
1113
  * @throws CapabilityException if Flash memory access is not possible.
1114
  */
1115
    public int flashFirstFreeSector ( ) throws UsbException, InvalidFirmwareException, CapabilityException {
1116
        checkCapability(0,2);
1117
        if ( ! flashEnabled() )
1118
            throw new CapabilityException(this, "No Flash memory installed or");
1119
 
1120
        byte[] sector = new byte[flashSectorSize];
1121
        byte[] ID = new String("ZTEXBS").getBytes();
1122
 
1123
        flashReadSector(0,sector);                       // read the boot sector
1124
        for (int k=0; k<6; k++)
1125
            if ( sector[k] != ID[k] )
1126
                return 0;
1127
        if (sector[6]!=1 || sector[7]!=1 )
1128
            return 0;
1129
        return (sector[8] & 255) + ((sector[9] & 255) << 8) + 1;
1130
    }
1131
 
1132
// ******* toString ************************************************************
1133
/**
1134
  * Returns a lot of useful information about the corresponding device.
1135
  * @return a lot of useful information about the corresponding device.
1136
  */
1137
    public String toString () {
1138
        String str = dev().toString();
1139
        try {
1140
            str += "\n   " + getFpgaConfigurationStr();
1141
        }
1142
        catch ( Exception e ) {
1143
        }
1144
        return str;
1145
    }
1146
 
1147
// ******* capabilityInfo ******************************************************
1148
/**
1149
  * Creates a String with capability information.
1150
  * @param pf A separator between the single capabilities, e.g. ", "
1151
  * @return a string of the supported capabilities.
1152
  */
1153
    public String capabilityInfo ( String pf ) {
1154
        String str = "";
1155
        for ( int i=0; i<6; i++ )
1156
            for (int j=0; j<8; j++ )
1157
                if ( dev().interfaceCapabilities(i,j) ) {
1158
                    if ( ! str.equals("") )
1159
                        str+=pf;
1160
                    if (i*8+j < capabilityStrings.length)
1161
                        str+=capabilityStrings[i*8+j];
1162
                    else
1163
                        str+=i+"."+j;
1164
                }
1165
        return str;
1166
    }
1167
}
1168
 

powered by: WebSVN 2.1.0

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