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

Subversion Repositories usb_fpga_1_2

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

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

powered by: WebSVN 2.1.0

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