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

Subversion Repositories usb_dongle_fpga

[/] [usb_dongle_fpga/] [tags/] [version_1_5/] [sw/] [dongle.py] - Blame information for rev 43

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

Line No. Rev Author Line
1 2 nuubik
#! /usr/bin/python
2 17 nuubik
# -*- coding: ISO-8859-1 -*-
3
 
4 2 nuubik
##########################################################################
5
# LPC Dongle programming software 
6
#
7 23 nuubik
# Copyright (C) 2008 Artec Design
8 2 nuubik
# 
9
# This library is free software; you can redistribute it and/or
10
# modify it under the terms of the GNU Lesser General Public
11
# License as published by the Free Software Foundation; either
12
# version 2.1 of the License, or (at your option) any later version.
13
# 
14
# This software is distributed in the hope that it will be useful,
15
# but WITHOUT ANY WARRANTY; without even the implied warranty of
16
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
# Lesser General Public License for more details.
18
 
19
# You should have received a copy of the GNU Lesser General Public
20
# License along with this library; if not, write to the Free Software
21
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22
##########################################################################
23
 
24
#-------------------------------------------------------------------------
25
# Project:   LPC Dongle programming software 
26
# Name:      dongle.py
27
# Purpose:   Executable command line tool 
28
#
29 23 nuubik
# Author:    Jüri Toomessoo <jyrit@artecdesign.ee>
30
# Copyright: (c) 2008 by Artec Design
31 2 nuubik
# Licence:   LGPL
32
#
33
# Created:   06 Oct. 2006
34
# History:   12 oct. 2006  Version 1.0 released
35 8 nuubik
#            22 Feb. 2007  Test options added to test PCB board
36 23 nuubik
#            10 Nov. 2007  Added open retry code to dongle
37 17 nuubik
#            14 Nov. 2007  Moved dongle spesific code to class Dongle from USPP
38
#                          USPP is allmost standard now (standard USPP would work)
39
#                          Artec USPP has serial open retry
40
#            14 Nov. 2007  Improved help. 
41 23 nuubik
#            10 Mar. 2008  Forced code to hw flow control settings made linux 1 byte read to 2 bytes
42
#                          as dongle never reads 1 byte at the time
43 2 nuubik
#-------------------------------------------------------------------------
44
 
45
import os
46
import sys
47
import string
48
import time
49 23 nuubik
import struct
50 2 nuubik
from sets import *
51
from struct import *
52
 
53 23 nuubik
#### inline of artec FTDI spesific Uspp code ###################################################
54
 
55
##########################################################################
56
# USPP Library (Universal Serial Port Python Library)
57
#
58
# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
59
# 
60
# This library is free software; you can redistribute it and/or
61
# modify it under the terms of the GNU Lesser General Public
62
# License as published by the Free Software Foundation; either
63
# version 2.1 of the License, or (at your option) any later version.
64
# 
65
# This library is distributed in the hope that it will be useful,
66
# but WITHOUT ANY WARRANTY; without even the implied warranty of
67
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
68
# Lesser General Public License for more details.
69
 
70
# You should have received a copy of the GNU Lesser General Public
71
# License along with this library; if not, write to the Free Software
72
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
73
##########################################################################
74
 
75
#-------------------------------------------------------------------------
76
# Project:   USPP Library (Universal Serial Port Python Library)
77
# Name:      uspp.py
78
# Purpose:   Main module. Imports the correct module for the platform
79
#            in which it is running.
80
#
81
# Author:    Isaac Barona Martinez <ibarona@gmail.com>
82
# Contributors:
83
#            Damien Géranton <dgeranton@voila.fr>
84
#            Douglas Jones <dfj23@drexel.edu>
85
#            J.Grauheding <juergen.grauheding@a-city.de>
86
#            J.Toomessoo jyrit@artecdesign.ee
87
#
88
# Copyright: (c) 2006 by Isaac Barona Martinez
89
# Licence:   LGPL
90
#
91
# Created:   26 June 2001
92
# History:
93
#            05/08/2001: Release version 0.1.
94
#            24/02/2006: Final version 1.0.
95
#            10/11/2007: Added open retry code to dongle
96
#                        by Jyri Toomessoo jyrit@artecdesign.ee
97
#            14/11/2007: Moved dongle spesific code to class Dongle from USPP
98
#                        USPP is allmost standard now (standard USPP would work)
99
#                        Artec USPP has serial open retry
100
#                        by Jyri Toomessoo jyrit@artecdesign.ee
101
#            10/03/2008: Forced code to hw flow control settings made linux 1 byte read to 2 bytes
102
#                        as dongle never reads 1 byte at the time
103
#                        by Jyri Toomessoo jyrit@artecdesign.ee
104
#            10/03/2008: Copose single infile bundle for FTDI USB serial 1.2
105
#                        this is nonuniversal modification of the code to suite the need of Artec Design Dongle
106
#                        by Jyri Toomessoo jyrit@artecdesign.ee
107
#-------------------------------------------------------------------------
108
 
109
 
110
drv_ok = 0
111
if sys.platform=='win32':
112
    print "Windows platform detected:"
113
    if drv_ok == 0:
114
        try:
115
            from win32file import *
116
            from win32event import *
117
            import win32con
118
            import exceptions
119
 
120
            print "Using VCP FTDI driver"
121
        except ImportError,SerialPortException:
122
            print "Python for winiows extensions for COM not found"
123
            print "(see https://sourceforge.net/projects/pywin32/)"
124
            print "Could not find any usable support for FTDI chip in python"
125
            print "Try installing python support from one of the links."
126
            sys.exit()
127
elif sys.platform=='linux2':
128
    from termios import *
129
    import fcntl
130
    import exceptions
131
    import array
132
    print "Linux platform detected:"
133
else:
134
    sys.exit('Sorry, no implementation for this platform yet')
135
 
136
 
137
 
138
class SerialPortException(exceptions.Exception):
139
    """Exception raise in the SerialPort methods"""
140
    def __init__(self, args=None):
141
        self.args=args
142
    def __str__(self):
143
        return repr(self.args)
144
 
145
 
146
if sys.platform=='win32':
147
  class SerialPortWin:
148
    BaudRatesDic={110: CBR_110,
149
                  300: CBR_300,
150
                  600: CBR_600,
151
                  1200: CBR_1200,
152
                  2400: CBR_2400,
153
                  4800: CBR_4800,
154
                  9600: CBR_9600,
155
                  19200: CBR_19200,
156
                  38400: CBR_38400,
157
                  57600: CBR_57600,
158
                  115200: CBR_115200,
159
                  128000: CBR_128000,
160
                  256000: CBR_256000
161
                  }
162
 
163
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
164
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
165
        self.__mode=mode
166
        self.__params=params
167
        self.__speed = 0
168
        self.__reopen = 0
169
        while 1:
170
            try:
171
                self.__handle=CreateFile (dev,
172
                win32con.GENERIC_READ|win32con.GENERIC_WRITE,
173
                0, # exclusive access
174
                None, # no security
175
                win32con.OPEN_EXISTING,
176
                win32con.FILE_ATTRIBUTE_NORMAL,
177
                None)
178
                break
179
 
180
            except:
181
                n=0
182
                while (n < 2000000):
183
                    n += 1;
184
                self.__reopen = self.__reopen + 1
185
            if self.__reopen > 32:
186
                print "Port does not exist..."
187
                raise SerialPortException('Port does not exist...')
188
                break
189
                #sys.exit()
190
        self.__configure()
191
 
192
    def __del__(self):
193
        if self.__speed:
194
            try:
195
                CloseHandle(self.__handle)
196
            except:
197
                raise SerialPortException('Unable to close port')
198
 
199
 
200
 
201
 
202
    def __configure(self):
203
        if not self.__speed:
204
            self.__speed=115200
205
        # Tell the port we want a notification on each char
206
        SetCommMask(self.__handle, EV_RXCHAR)
207
        # Setup a 4k buffer
208
        SetupComm(self.__handle, 4096, 4096)
209
        # Remove anything that was there
210
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
211
                  PURGE_RXCLEAR)
212
        if self.__timeout==None:
213
            timeouts= 0, 0, 0, 0, 0
214
        elif self.__timeout==0:
215
            timeouts = win32con.MAXDWORD, 0, 0, 0, 1000
216
        else:
217
            timeouts= self.__timeout, 0, self.__timeout, 0 , 1000
218
        SetCommTimeouts(self.__handle, timeouts)
219
 
220
        # Setup the connection info
221
        dcb=GetCommState(self.__handle)
222
        dcb.BaudRate=SerialPortWin.BaudRatesDic[self.__speed]
223
        if not self.__params:
224
            dcb.ByteSize=8
225
            dcb.Parity=NOPARITY
226
            dcb.StopBits=ONESTOPBIT
227
            dcb.fRtsControl=RTS_CONTROL_ENABLE
228
            dcb.fOutxCtsFlow=1
229
        else:
230
            dcb.ByteSize, dcb.Parity, dcb.StopBits=self.__params
231
        SetCommState(self.__handle, dcb)
232
 
233
 
234
    def fileno(self):
235
        return self.__handle
236
 
237
 
238
    def read(self, num=1):
239
        (Br, buff) = ReadFile(self.__handle, num)
240
        if len(buff)<>num and self.__timeout!=0: # Time-out  
241
            print 'Expected %i bytes but got %i before timeout'%(num,len(buff))
242
            raise SerialPortException('Timeout')
243
        else:
244
            return buff
245
 
246
 
247
    def readline(self):
248
        s = ''
249
        while not '\n' in s:
250
            s = s+SerialPortWin.read(self,1)
251
 
252
        return s
253
 
254
 
255
    def write(self, s):
256
        """Write the string s to the serial port"""
257
        errCode = 0
258
        overlapped=OVERLAPPED()
259
        overlapped.hEvent=CreateEvent(None, 0,0, None)
260
        (errCode, bytesWritten) = WriteFile(self.__handle, s,overlapped)
261
        # Wait for the write to complete
262
        WaitForSingleObject(overlapped.hEvent, INFINITE)
263
        return bytesWritten
264
 
265
    def inWaiting(self):
266
        """Returns the number of bytes waiting to be read"""
267
        flags, comstat = ClearCommError(self.__handle)
268
        return comstat.cbInQue
269
 
270
    def flush(self):
271
        """Discards all bytes from the output or input buffer"""
272
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
273
                  PURGE_RXCLEAR)
274
 
275
 
276
 
277
if sys.platform=='linux2':
278
  class SerialPortLin:
279
    """Encapsulate methods for accesing to a serial port."""
280
 
281
    BaudRatesDic={
282
        110: B110,
283
        300: B300,
284
        600: B600,
285
        1200: B1200,
286
        2400: B2400,
287
        4800: B4800,
288
        9600: B9600,
289
        19200: B19200,
290
        38400: B38400,
291
        57600: B57600,
292
        115200: B115200,
293
        230400: B230400
294
        }
295
    buf = array.array('h', '\000'*4)
296
 
297
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
298
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
299
        self.__mode=mode
300
        self.__params=params
301
        self.__speed = 0
302
        self.__reopen = 0
303
        while 1:
304
            try:
305
                self.__handle=os.open(dev, os.O_RDWR)
306
                break
307
 
308
            except:
309
                n=0
310
                while (n < 2000000):
311
                    n += 1;
312
                self.__reopen = self.__reopen + 1
313
            if self.__reopen > 32:
314
                print "Port does not exist..."
315
                raise SerialPortException('Port does not exist...')
316
                break
317
 
318
        self.__configure()
319
 
320
    def __del__(self):
321
        if self.__speed:
322
            #tcsetattr(self.__handle, TCSANOW, self.__oldmode)
323
            pass
324
            try:
325
                pass
326
                os.close(self.__handle)
327
            except IOError:
328
                raise SerialPortException('Unable to close port')
329
 
330
 
331
    def __configure(self):
332
        if not self.__speed:
333
            self.__speed=115200
334
 
335
        # Save the initial port configuration
336
        self.__oldmode=tcgetattr(self.__handle)
337
        if not self.__params:
338
            # print "Create linux params for serialport..."
339
            # self.__params is a list of attributes of the file descriptor
340
            # self.__handle as follows:
341
            # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
342
            # where cc is a list of the tty special characters.
343
            self.__params=[]
344
            # c_iflag
345
            self.__params.append(IGNPAR)
346
            # c_oflag
347
            self.__params.append(0)
348
            # c_cflag
349
            self.__params.append(CS8|CREAD|CRTSCTS)
350
            # c_lflag
351
            self.__params.append(0)
352
            # c_ispeed
353
            self.__params.append(SerialPortLin.BaudRatesDic[self.__speed])
354
            # c_ospeed
355
            self.__params.append(SerialPortLin.BaudRatesDic[self.__speed])
356
            cc=[0]*NCCS
357
        if self.__timeout==None:
358
            # A reading is only complete when VMIN characters have
359
            # been received (blocking reading)
360
            cc[VMIN]=1
361
            cc[VTIME]=0
362
        elif self.__timeout==0:
363
            cc[VMIN]=0
364
            cc[VTIME]=0
365
        else:
366
            cc[VMIN]=0
367
            cc[VTIME]=self.__timeout #/100
368
        self.__params.append(cc)               # c_cc
369
 
370
        tcsetattr(self.__handle, TCSANOW, self.__params)
371
 
372
 
373
    def fileno(self):
374
        return self.__handle
375
 
376
 
377
    def __read1(self):
378
        tryCnt = 0
379
        byte = ""
380
        while(len(byte)==0 and tryCnt<10):
381
            tryCnt+=1
382
            byte = os.read(self.__handle, 2)
383
        if len(byte)==0 and self.__timeout!=0: # Time-out
384
            print 'Time out cnt was %i'%(tryCnt)
385
            print 'Expected 1 byte but got %i before timeout'%(len(byte))
386
            sys.stdout.flush()
387
            raise SerialPortException('Timeout')
388
        else:
389
            return byte
390
 
391
 
392
    def read(self, num=1):
393
        s=''
394
        for i in range(num/2):
395
            s=s+SerialPortLin.__read1(self)
396
        return s
397
 
398
 
399
    def readline(self):
400
 
401
        s = ''
402
        while not '\n' in s:
403
            s = s+SerialPortLin.__read1(self)
404
 
405
        return s
406
 
407
 
408
    def write(self, s):
409
        """Write the string s to the serial port"""
410
        return os.write(self.__handle, s)
411
 
412
    def inWaiting(self):
413
        """Returns the number of bytes waiting to be read"""
414
        data = struct.pack("L", 0)
415
        data=fcntl.ioctl(self.__handle, TIOCINQ, data)
416
        return struct.unpack("L", data)[0]
417
 
418
    def outWaiting(self):
419
        """Returns the number of bytes waiting to be write
420
        mod. by J.Grauheding
421
        result needs some finetunning
422
        """
423
        rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)
424
        return rbuf
425
 
426
 
427
    def flush(self):
428
        """Discards all bytes from the output or input buffer"""
429
        tcflush(self.__handle, TCIOFLUSH)
430
 
431
 
432
 
433
#### end inline of artec FTDI spesific Uspp code ###############################################
434
 
435
 
436
#### Dongle code starts here  ##################################################################
437
 
438
 
439 2 nuubik
#### global funcs ####
440
def usage(s):
441 43 nuubik
    print "Artec USB Dongle programming utility ver. 2.51"
442 17 nuubik
    print "Usage:"
443
    print "Write file      : ",s," [-vq] -c <name> <file> <offset>"
444
    print "Readback file   : ",s," [-vq] -c <name> [-vq] -r <offset> <length> <file>"
445 2 nuubik
    print "Options:"
446 17 nuubik
    print " <file> <offset> When file and offset are given file will be written to dongle"
447
    print "        file:    File name to be written to dongle"
448
    print "        offset:  Specifies data writing starting point in bytes to 4M window"
449
    print "                 For ThinCan boot code the offset = 4M - filesize. To write"
450
    print "                 256K file the offset must be 3840K"
451
    print " "
452
    print " -c <name>       Indicate port name where the USB Serial Device is"
453
    print "        name:    COM port name in Windows or Linux Examples: COM3,/dev/ttyS3"
454
    print "                 See Device Manager in windows for USB Serial Port number"
455
    print " "
456
    print " -v              Enable verbose mode. Displays more progress information"
457
    print " "
458
    print " -q              Perform flash query to see if dongle flash is responding"
459
    print " "
460
    print " -r <offset> <length> <file>  Readback data. Available window size is 4MB"
461 23 nuubik
    print "        offset:  Offset byte addres inside 4MB window. Example: 1M"
462
    print "                 use M for MegaBytes, K for KiloBytes, none for bytes"
463
    print "                 use 0x prefix to indicate hexademical number format"
464 17 nuubik
    print "        length:  Amount in bytes to read starting from offset. Example: 1M"
465
    print "                 use M for MegaBytes, K for KiloBytes, none for bytes"
466
    print "        file:    Filename where data will be written"
467
    print " "
468
    print " -e              Erase device. Erases Full 4 MegaBytes"
469 8 nuubik
    print "Board test options: "
470 17 nuubik
    print " -t              Marching one and zero test. Device must be empty"
471
    print "                 To test dongle erase the flash with command -e"
472
    print "                 Enables dongle memory tests to be executed by user"
473
    print " "
474 29 nuubik
    print " -b              Leave flash blank after test. Used with option -t"
475 23 nuubik
    print " -l              Fast poll loop test. Does poll loop 1024 times"
476
    print "                 used to stress test connection"
477 8 nuubik
    print ""
478 2 nuubik
    print "Examples:"
479
    print ""
480 17 nuubik
    print " ",s," -c COM3 loader.bin 0                       "
481
    print " ",s," -c /dev/ttyS3 boot.bin 3840K"
482
    print " ",s," -c COM3 -r 0x3C0000 256K flashcontent.bin"
483 2 nuubik
######################
484
 
485
 
486
class DongleMode:
487
    def __init__(self):
488
        self.v = 0
489
        self.f = 0
490
        self.d = 0
491
        self.q = 0
492
        self.r = 0
493 8 nuubik
        self.t = 0
494
        self.e = 0
495 23 nuubik
        self.b = 0
496
        self.l = 0
497 2 nuubik
        self.filename=""
498
        self.portname=""
499
        self.address=-1
500
        self.offset=-1
501
        self.length=-1
502 23 nuubik
        self.version=4
503 2 nuubik
 
504
    def convParamStr(self,param):
505
        mult = 1
506
        value = 0
507
        str = param
508
        if str.find("K")>-1:
509
            mult = 1024
510
            str=str.strip("K")
511
        if str.find("M")>-1:
512
            mult = 1024*1024
513
            str=str.strip("M")
514
        try:
515
            if str.find("x")>-1:
516
                value = int(str,0)*mult  #conver hex string to int
517
            else:
518
                value = int(str)*mult  #conver demical string to int
519
        except ValueError:
520
            print "Bad parameter format given for: ",param
521
 
522
        return value
523
 
524
 
525
 
526
 
527
class Dongle:
528
    def __init__(self,name, baud, timeout):  #time out in millis 1000 = 1s baud like 9600, 57600
529 23 nuubik
        self.mode = 0
530 2 nuubik
        try:
531 23 nuubik
            if sys.platform=='win32':
532
                self.tty = SerialPortWin(name,timeout, baud)
533
            else:
534
                self.tty = SerialPortLin(name,timeout, baud)
535
 
536 17 nuubik
        except SerialPortException , e:
537
            print "Unable to open port " + name
538 2 nuubik
            sys.exit();
539 9 nuubik
 
540
    def testReturn(self,byteCount):
541
        i=0
542
        while don.tty.inWaiting()<byteCount:
543
            i=i+1
544
            if i==10000*byteCount:
545
                break
546
        if i==10000*byteCount:
547
            return 0
548 23 nuubik
        j=don.tty.inWaiting()
549
        #print "Tested in waiting %i needed %i"%(j,byteCount)
550
        return j  ## ret two bytes            
551 9 nuubik
 
552 2 nuubik
    def getReturn(self,byteCount):
553
        i=0
554 23 nuubik
        #while don.tty.inWaiting()<byteCount:
555
        #    i=i+1
556
        #    time.sleep(0.1)
557
        #    if i==100*byteCount:
558
        #        print "Dongle not communicating"
559
        #        #print "Read in waiting %i needed %i was %i"%(i,byteCount,don.tty.inWaiting())
560
        #        sys.exit()
561
        #        break
562
 
563
        #i=don.tty.inWaiting()
564
        #print "Read in waiting %i needed %i was %i"%(i,byteCount,don.tty.inWaiting())
565
        buf = don.tty.read(byteCount)
566
        #print "Got bytes =%i "%(len(buf))
567
        return buf  ## ret two bytes
568 9 nuubik
 
569 2 nuubik
 
570
    def write_command(self,command):
571
        lsb = command&0xff
572
        msb = (command>>8)&0xff
573 17 nuubik
        self.write_2bytes(msb,lsb)
574
 
575
    def write_2bytes(self, msb,lsb):
576
        """Write one word MSB,LSB to the serial port MSB first"""
577
        s = pack('BB', msb, lsb)
578 23 nuubik
        ret = self.tty.write(s)
579
        if(ret<len(s)):
580
            print 'write_2byte: Wrote less then needed %i bytes from %i'%(ret,length(s))
581 17 nuubik
        # Wait for the write to complete
582
        #WaitForSingleObject(overlapped.hEvent, INFINITE)               
583 2 nuubik
 
584
    def get_address_buf(self,address):  #set word address
585
        lsbyte = address&0xff
586
        byte = (address>>8)&0xff
587
        msbyte = (address>>16)&0xff
588
        buffer = ""
589
        buffer += chr(lsbyte)
590
        buffer += chr(0xA0)
591
        buffer +=  chr(byte)
592
        buffer +=  chr(0xA1)
593
        buffer +=  chr(msbyte)
594
        buffer +=  chr(0xA2)
595
        evaluate = (address>>24)
596
        if evaluate != 0:
597
            print "Addressign fault. Too large address passed"
598
            sys.exit()
599
        return buffer
600
 
601
 
602
    def set_address(self,address):  #set word address
603
        lsbyte = address&0xff
604
        byte = (address>>8)&0xff
605
        msbyte = (address>>16)&0xff
606
        evaluate = (address>>24)
607
        if evaluate != 0:
608
            print "Addressign fault. Too large address passed"
609
            sys.exit()
610 17 nuubik
        self.write_2bytes(lsbyte,0xA0)            #set internal address to dongle
611
        self.write_2bytes(byte,0xA1)            #set internal address to dongle
612
        self.write_2bytes(msbyte,0xA2)            #send query command
613 2 nuubik
 
614
    def read_data(self,wordCount,address):
615
        command = 0
616
        byteCount = wordCount<<1  #calc byte count
617
        if wordCount>0 :
618
            command = (command|wordCount)<<8;
619
            command = command|0xCD
620
            self.set_address(address)    # send read address
621
            self.write_command(command)  # send get data command
622
            return self.getReturn(byteCount)
623
        else:
624
            print "Word count can't be under 1"
625
            sys.exit()
626 23 nuubik
 
627 2 nuubik
 
628 23 nuubik
    def issue_blk_read(self):
629
        command = 0
630
        wordCount = 0
631
        byteCount = wordCount<<1  #calc byte count
632
        command = (command|wordCount)<<8;
633
        command = command|0xCD
634
        self.write_command(command)  # send get data command
635
 
636
 
637
 
638
 
639 2 nuubik
    def read_status(self):
640
        don.write_command(0x0070) # 0x0098 //clear status
641
        command = 0
642
        wordCount= 1  #calc byte count
643
        byteCount = wordCount<<1
644
        command = (command|wordCount)<<8;
645
        command = command|0xCD
646
        self.write_command(command)  # send get data command
647
        return self.getReturn(byteCount)
648
 
649
 
650
    def get_block_no(self,address):
651
        return address >> 16 # 16 bit mode block is 64Kwords
652
 
653
    def wait_on_busy(self):
654
        exit=0
655
        while exit==0:
656
            buf=self.read_status()
657
            statReg = ord(buf[0])  #8 bit reg
658
            if statReg>>7 == 1:
659
                exit=1
660
 
661
    def parse_status(self):  # use only after wait on busy commad to get result of the operation
662
        exit = 0
663
        buf=self.read_status()
664
        statReg = ord(buf[0])  #8 bit reg
665
        if (statReg>>5)&1 == 1:
666
            print "Block erase suspended"
667
            exit = 1
668
        if (statReg>>4)&3 == 3:
669
            print "Error in command order"  #if bits 4 and 5 are set then 
670
            exit = 1
671
        if (statReg>>4)&3 == 1:
672
            print "Error in setting lock bit"
673
            exit = 1
674
        if (statReg>>3)&1 == 1:
675
            print "Low Programming Voltage Detected, Operation Aborted"
676
            exit = 1
677
        if (statReg>>2)&1 == 1:
678
            print "Programming suspended"
679
            exit = 1
680
        if (statReg>>1)&1 == 1:
681
            print "Block lock bit detected"
682
            exit = 1
683
        if exit == 1:
684
            sys.exit()
685
 
686
    def erase_block(self,blockNo):
687
        blockAddress = blockNo << 16
688
        command = 0x0020
689
        self.set_address(blockAddress)
690
        self.write_command(command)  #issue block erase
691
        command = 0x00D0
692
        self.write_command(command)  #issue block erase confirm
693 23 nuubik
        #self.wait_on_busy()
694
        #self.parse_status()
695 2 nuubik
 
696
    def buffer_write(self,wordCount,startAddress,buffer):
697
        # to speed up buffer writing compose all commands into one buffer
698
        # instead of multiple single writes this is needed as the FTDI chip
699
        # round lag is amazingly large with VCOM drivers
700
        #u = len(buffer)
701
        if len(buffer)<32:            #don't ever make unaligned writes
702
            i=len(buffer)
703
            while len(buffer)<32:
704
                buffer += "\xff"
705
        adrBuf = self.get_address_buf(startAddress)   #6 bytes total
706
        cmd_e8=""  #8 bytes total
707
        cmd_e8+= chr(16)   #make it always 16 wordCount
708
        cmd_e8+= chr(0xE8)
709
        cmd_wcnt=""  #10 bytes total
710
        cmd_wcnt+= chr(0x00)
711
        cmd_wcnt+= chr(16-1)
712
        cmd_buf=""  #12 bytes total
713
        cmd_buf+= chr(0x00)
714
        cmd_buf+= chr(0xD0)
715
        wr_buffer_cmd = adrBuf + cmd_e8 + cmd_wcnt + buffer + cmd_buf   #44 bytes total
716 17 nuubik
        self.write_buf_cmd(wr_buffer_cmd)
717 23 nuubik
 
718
        if self.mode.version <5:
719
            n = 0
720
            if sys.platform=='win32':
721
                while (n < 1024):
722
                    n += 1;
723
            elif sys.platform=='linux2':
724
                #Linux FTDI VCP driver is way faster and needs longer grace time than windows driver
725
                while (n < 1024*8):
726
                    n += 1;
727 17 nuubik
 
728
    def write_buf_cmd(self, buffer):
729
        """Write one word MSB,LSB to the serial port MSB first"""
730
        a=0
731
        s=""
732
        if (len(buffer) < 44):  # if buffer is shorter than expected then pad with read array mode commands
733
            i=0
734
            while i<len(buffer):
735
                print '0x%02x'%(ord(buffer[i]))
736
                i+=1
737
            while(a < len(buffer)):
738
                if a < 10:
739
                    s= pack('2c', buffer[a], buffer[a+1])
740
                    self.tty.write(s)
741
                elif a < len(buffer)-2:
742
                    s= pack('2c', buffer[a+1], buffer[a])
743
                    self.tty.write(s)
744
                elif  len(buffer)==2:
745
                    s=pack('2c', buffer[a], buffer[a+1])
746
                    self.tty.write(s)
747
                else:
748
                     s=pack('2c', buffer[a], chr(0xFF))
749
                     self.tty.write(s)
750
                a+=2
751
        else:
752
            #first 10 bytes are in correct order + 32 data bytes are in wrong order and + 2 confirm bytes are in correct order
753
            s=pack('44c',
754
            buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
755
            buffer[8], buffer[9], buffer[11], buffer[10], buffer[13], buffer[12], buffer[15], buffer[14],
756
            buffer[17], buffer[16], buffer[19], buffer[18], buffer[21], buffer[20], buffer[23], buffer[22],
757
            buffer[25], buffer[24], buffer[27], buffer[26], buffer[29], buffer[28], buffer[31], buffer[30],
758
            buffer[33], buffer[32], buffer[35], buffer[34], buffer[37], buffer[36], buffer[39], buffer[38],
759
            buffer[41], buffer[40], buffer[42], buffer[43]
760
            )
761 23 nuubik
 
762
            ret = self.tty.write(s)
763
 
764 2 nuubik
 
765
 
766
################## Main program #########################
767
 
768
 
769
last_ops = 0
770
mode = DongleMode()
771
# PARSE ARGUMENTS 
772
for arg in sys.argv:
773
    if len(sys.argv) == 1: # if no arguments display help
774 8 nuubik
       #usage(sys.argv[0])
775
       usage("dongle.py")
776 2 nuubik
       sys.exit()
777
    if arg in ("-h","--help","/help","/h"):
778 8 nuubik
        #usage(sys.argv[0])
779
        usage("dongle.py")
780 2 nuubik
        sys.exit()
781
    if arg in ("-c"):
782
        last_ops = sys.argv.index(arg) + 1  #if remains last set of options from here start ordered strings
783
        i = sys.argv.index(arg)
784
        print "Opening port: "+sys.argv[i+1]
785
        mode.portname = sys.argv[i+1]   # next element after -c open port for usage
786
    if arg[0]=="-" and arg[1]!="c": # if other opptions
787
        # parse all options in this
788
        last_ops = sys.argv.index(arg)  #if remains last set of options from here start ordered strings
789
        ops = arg[1:]# get all besides the - sign
790
        for op in ops:
791
            if op=="q":
792
                mode.q = 1
793
            if op=="v":
794
                mode.v = 1
795
            if op=="f":
796
                mode.f = 1
797
            if op=="d":
798
                mode.d = 1
799
            if op=="r":
800 8 nuubik
                mode.r = 1
801
            if op=="t":
802
                mode.t = 1
803
            if op=="e":
804
                mode.e = 1
805
            if op=="b":
806 23 nuubik
                mode.b = 1
807
            if op=="l":
808
                mode.l = 1
809 2 nuubik
    else:
810
        i = sys.argv.index(arg)
811
        if i ==  last_ops + 1:
812
            if mode.r==1:
813
                mode.offset=mode.convParamStr(arg)
814
            else:
815
                mode.filename=arg
816
        if i ==  last_ops + 2:
817
            if mode.r==1:
818
                mode.length=mode.convParamStr(arg)
819
            else:
820
                mode.address=mode.convParamStr(arg)
821
 
822
        if i ==  last_ops + 3:
823
            if mode.r==1:
824
                mode.filename=arg
825
            else:
826
                print "Too many parameters provided"
827
                sys.exit()
828
        if i >  last_ops + 3:
829
             print "Too many parameters provided"
830
             sys.exit()
831
 
832
# END PARSE ARGUMENTS             
833
 
834
if mode.portname=="":
835
    print "No port name given see -h for help"
836
    sys.exit()
837
else:
838
    # test PC speed to find sutable delay for linux driver
839
    # to get 250 us 
840
    mytime = time.clock()
841
    n = 0
842
    while (n < 100000):
843
        n += 1;
844
    k10Time = time.clock() - mytime   # time per 10000 while cycles
845
    wait = k10Time/100000.0     # time per while cycle
846
    wait = (0.00025/wait) * 1.20   # count for 250us + safe margin
847
    # ok done
848 9 nuubik
    reopened = 0
849
 
850 23 nuubik
 
851
    if sys.platform=='win32':
852
        don  = Dongle(mode.portname,256000,6000)
853
    elif sys.platform=='linux2':
854
        don  = Dongle(mode.portname,230400,6000)
855
        #don.tty.cts()
856
    else:
857
        sys.exit('Sorry, no implementation for this platform yet')
858
 
859
 
860 9 nuubik
    don.tty.wait = wait
861
    while 1:
862
        don.write_command(0x0050) # 0x0098
863
        don.write_command(0x00C5)            #send dongle check internal command
864
        don_ret=don.testReturn(2)
865
        if don_ret==2:
866
            break
867
        if reopened == 3:
868
             print 'Dongle connected, but does not communicate'
869
             sys.exit()
870
        reopened = reopened + 1
871
        # reopen and do new cycle
872 23 nuubik
        if sys.platform=='win32':
873
            don  = Dongle(mode.portname,256000,6000)
874
        elif sys.platform=='linux2':
875
            don  = Dongle(mode.portname,230400,6000)
876
            #self.tty.cts()
877
        else:
878
            sys.exit('Sorry, no implementation for this platform yet')
879 9 nuubik
        don.tty.wait = wait
880
 
881 2 nuubik
    buf=don.getReturn(2)  # two bytes expected to this command
882
    if ord(buf[1])==0x32 and  ord(buf[0])==0x10:
883
        print "Dongle OK"
884
    else:
885
        print 'Dongle returned on open: %02x %02x '%(ord(buf[1]), ord(buf[0]))
886 23 nuubik
    don.write_command(0x01C5)            #try getting dongle HW ver (works since 05 before that returns 0x3210)
887
    buf=don.getReturn(2)  # two bytes expected to this command
888
    if ord(buf[1])==0x86 and  ord(buf[0])>0x04:
889
        mode.version = ord(buf[0])
890
        don.mode = mode
891
        print 'Dongle HW version code is  %02x %02x'%(ord(buf[1]), ord(buf[0]))
892
    else:
893
        don.mode = mode
894
        print 'Dongle HW version code is smaller than 05 some features have been improved on'
895
        print 'HW code and Quartus FPGA binary file are available at:'
896
        print 'http://www.opencores.org/projects.cgi/web/usb_dongle_fpga/overview'
897 29 nuubik
        print 'Programming is possible with Altera Quartus WE and BYTEBLASTER II cable or'
898
        print 'compatible clone like X-Blaster http://www.customcircuitsolutions.com/cable.html'
899 2 nuubik
 
900
if mode.q == 1:   # perform a query from dongle
901 9 nuubik
 
902
    buf=don.read_data(4,0x0)  # word count and word address
903 2 nuubik
    don.write_command(0x0050) # 0x0098
904
    don.write_command(0x0098) # 0x0098
905
    buf=don.read_data(3,0x000010)  # word count and word address
906
    if ord(buf[0])==0x51 and  ord(buf[2])==0x52 and  ord(buf[4])==0x59:
907
        buf=don.read_data(2,0x000000)  # word count and word address
908 23 nuubik
        print 'Query  OK, Flash Factory Code is: 0x%02x device: 0x%02x '%(ord(buf[0]),ord(buf[2]))
909 2 nuubik
        buf=don.read_data(2,0x000002)
910
        print 'lock bit is 0x%02x 0x%02x'%(ord(buf[0]),ord(buf[1]))
911
    else:
912 23 nuubik
        print "Got bad Flash query data:"
913 2 nuubik
        print 'Query address 0x10 = 0x%02x%02x '%(ord(buf[1]),ord(buf[0]))
914 9 nuubik
        print 'Query address 0x12 = 0x%02x%02x '%(ord(buf[3]),ord(buf[2]))
915
        print 'Query address 0x14 = 0x%02x%02x '%(ord(buf[5]),ord(buf[4]))
916 2 nuubik
        print "Read byte count:",len(buf)
917
 
918
    don.write_command(0x00FF) # 0x0098
919 9 nuubik
    buf=don.read_data(4,0xff57c0>>1)  # word count and word address
920
 
921 2 nuubik
    print 'Data: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x '%(ord(buf[1]),ord(buf[0]),ord(buf[3]),ord(buf[2]),ord(buf[5]),ord(buf[4]),ord(buf[7]),ord(buf[6]) )
922
 
923
 
924
 
925
if mode.filename!="" and mode.address!=-1:
926
    #Calculate number of blocks and start of blocks
927
    size = 0
928
    mode.address = mode.address>>1  #make word address
929
    try:
930
        f=open(mode.filename,"rb")
931
        f.seek(0,2) #seek to end
932
        size = f.tell()
933
        f.seek(0) #seek to start
934
        print 'File size %iK '%(size/1024)
935
        f.close()
936
    except IOError:
937 42 nuubik
         print "IO Error on file open. File missing or no premission to open."
938 2 nuubik
         sys.exit()
939
    #clear blockLock bits
940
    don.write_command(0x0060) # 0x0098
941
    don.write_command(0x00D0) # 0x0098
942 23 nuubik
    if mode.version < 5:
943
        don.wait_on_busy()
944
        don.parse_status()
945 2 nuubik
    wordSize = (size+ (size&1))>> 1    # round byte count up and make word address
946
    endBlock = don.get_block_no(mode.address+wordSize - 1)
947
    startBlock = don.get_block_no(mode.address)
948 42 nuubik
    if endBlock > 32:
949
        print "Given file does not fit into remaining space. File size is %i KB"%(size/1024)
950
        print "Space left from given offset is %i KB"%((4*1024*1024-mode.address*2)/1024)
951
        sys.exit()
952 2 nuubik
    i=startBlock
953 9 nuubik
    print 'Erasing from block %i to %i '%(i,endBlock)
954 2 nuubik
    while i <= endBlock:
955 9 nuubik
        if mode.v == 1:
956
            print 'Erasing block %i '%(i)
957
        else:
958
            sys.stdout.write(".")
959
            sys.stdout.flush()
960 2 nuubik
        don.erase_block(i)
961 23 nuubik
        if mode.version < 5:
962
            don.wait_on_busy()
963
            don.parse_status()   #do this after programming all but uneaven ending
964 2 nuubik
        i=i+1
965 9 nuubik
    if mode.v == 0:
966
        print " "
967 2 nuubik
    #don.write_command(0x00FF) # 0x0098
968
    #buf=don.read_data(4,0x000000)  # word count and word address     
969
    #print 'Data: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x '%(ord(buf[0]),ord(buf[1]),ord(buf[2]),ord(buf[3]),ord(buf[4]),ord(buf[5]),ord(buf[6]),ord(buf[7]) )
970
 
971
    f=open(mode.filename,"rb")
972
    f.seek(0) #seek to start
973
    address= mode.address
974
    #don.set_address(address)
975 9 nuubik
    print 'Writing %iK'%(size/1024)
976 2 nuubik
    while 1:
977 9 nuubik
        if (address/(1024*64) != (address-16)/(1024*64)) and address != mode.address:  # get bytes from words if 512
978
            if mode.v == 1:
979
                print 'Progress: %iK of %iK at 0x%06x'%((address-mode.address)/512,size/1024,address)
980
            else:
981
                sys.stdout.write(".")
982
                sys.stdout.flush()
983 2 nuubik
        buf = f.read(32)  #16 words is maximum write here bytes are read
984
        if len(buf)==32:
985
            don.buffer_write(16,address,buf)
986
            address = address + 16
987
        elif len(buf)>0:
988
            don.parse_status()   #do this after programming all but uneaven ending
989
            print "Doing an unaligned write..."
990
            length = len(buf)
991
            length = (length + (length&1))>> 1   #round up to get even word count
992
            buf = buf+"\xff"   #pad just in case rounding took place
993
            don.buffer_write(len,address,buf)
994
            address = address + 16     #inc word address
995
            break
996
        else:
997
            break
998 9 nuubik
    if mode.v == 0:
999
        print " "
1000 23 nuubik
    if mode.version >= 5:
1001
        print "Waiting for buffers to empty"
1002
        don.wait_on_busy()
1003
        don.parse_status()   #do this after programming all but uneaven ending        
1004 2 nuubik
    print "Write DONE!"
1005
    don.parse_status()   #do this after programming all but uneaven ending
1006
    f.close()
1007
 
1008
if mode.r == 1:   # perform a readback
1009
    if mode.offset!=-1 and mode.length!=-1 and mode.filename!="":
1010 23 nuubik
        if mode.version >= 5:
1011
            ##################### from hw ver 5 readback code ##################################################
1012
            blockCount = (mode.length>>17)+1 #read this many 64K word blocks
1013
            mode.offset=mode.offset>>1    #make word offset
1014
            lastLength = mode.length&0x0001FFFF
1015
            mode.length= mode.length>>1   #make word length
1016
            if mode.length < 512:
1017
                print 'Reading %i bytes in single block '%(lastLength)
1018
            else:
1019
                print 'Reading %iK in %i blocks '%(mode.length/512,blockCount)
1020 2 nuubik
            don.write_command(0x00FF) #  put flash to data read mode
1021 23 nuubik
            try:
1022
                f=open(mode.filename,"wb")  #if this fails no point in reading as there is nowhere to write
1023
                address = mode.offset    # set word address
1024
                don.set_address(address)
1025
                i=0
1026
                while (i<blockCount):
1027
                    don.issue_blk_read()  # request 64K words from current address
1028
                    buf=don.getReturn(65536*2) #Read all words
1029
                    if (i==blockCount-1):  #last block
1030
                        f.write(buf[:lastLength])
1031
                    else:
1032
                        f.write(buf) ## must tuncate the buffer
1033 9 nuubik
                    if mode.v == 1:
1034 23 nuubik
                        print 'Got block %i'%(i+1)
1035 9 nuubik
                    else:
1036
                        sys.stdout.write(".")
1037
                        sys.stdout.flush()
1038 23 nuubik
                    i+=1
1039
                f.close()
1040
            except IOError:
1041
                print "IO Error on file open"
1042
                sys.exit()
1043
            ##################### end from hw ver 5 readback code  ############################################ 
1044
        else:
1045
            ##################### before hw ver 5 readback code ###############################################
1046
            mode.offset=mode.offset>>1    #make word offset
1047
            mode.length= mode.length>>1   #make word length
1048
            print 'Reading %iK'%(mode.length/512)
1049
            try:
1050
                f=open(mode.filename,"wb")
1051
                don.write_command(0x00FF) #  put flash to data read mode
1052
                address = mode.offset    # set word address
1053
                while 1:
1054
                    if address/(1024*32) != (address-128)/(1024*32):  # get K bytes from words if 512
1055
                        if mode.v == 1:
1056
                            print 'Progress: %iK of %iK'%((address-mode.offset)/512,mode.length/512)
1057
                        else:
1058
                            sys.stdout.write(".")
1059
                            sys.stdout.flush()
1060
                    buf=don.read_data(128,address)  # word count and byte address read 64 words to speed up
1061
                    f.write(buf)
1062
                    #print "from address:",address<<1," ", len(buf)
1063
                    if address+128 >= (mode.offset + mode.length):  # 2+64 estimates the end to end in right place
1064
                        break
1065
                    address = address + 128    #this is word address
1066
                f.close()
1067
                if mode.v == 0:
1068
                    print " "
1069
                print "Readback done!"
1070
            except IOError:
1071
                print "IO Error on file open"
1072
                sys.exit()
1073
       ##################### end before hw ver 5 readback code  ################################################ 
1074 2 nuubik
    else:
1075
       print "Some of readback parameters missing..."
1076
       print mode.offset,mode.length, mode.filename
1077
       sys.exit()
1078 8 nuubik
 
1079
if mode.t == 1:   # perform dongle test
1080
        print "Dongle TEST"
1081
        if mode.e == 1:
1082
            #Erase Dongle
1083 9 nuubik
            print "Erasing"
1084 8 nuubik
            don.write_command(0x0060) # 0x0098
1085
            don.write_command(0x00D0) # 0x0098
1086
            don.wait_on_busy()
1087
            don.parse_status()
1088
            endBlock = 31
1089
            startBlock = 0
1090
            i=startBlock
1091
            while i <= endBlock:
1092 9 nuubik
                if mode.v == 1:
1093
                    print 'Erasing block %i '%(i)
1094
                else:
1095
                     sys.stdout.write(".")
1096
                     sys.stdout.flush()
1097 8 nuubik
                don.erase_block(i)
1098
                don.wait_on_busy()
1099
                don.parse_status()   #do this after programming all but uneaven ending
1100 9 nuubik
                i=i+1
1101
            if mode.v == 0: # add CRTL return to dots
1102
                print ""
1103 8 nuubik
        #Do marching one test on data and address
1104
        mode.length= 0   #make word length
1105
        try:
1106
            #Marching one test
1107
            #---------------------------------------------------------------------------
1108
            address = 0x100000    # set word address
1109
            data = 0x100000
1110
            while mode.length<20: # last address to test 0x20 0000  
1111
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1112
                don.buffer_write(2,address,buf1)
1113
                don.parse_status()   #do this after programming all but uneaven ending
1114
                don.write_command(0x00FF) #  put flash to data read mode   
1115
                buf2=don.read_data(2,address)  # word count and byte address read 64 words to speed up
1116
                if buf1 != buf2:
1117
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1118
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1119
                    print "Test FAIL!!!!!"
1120
                    sys.exit()
1121
                address = address >> 1
1122
                if address == 0x2:
1123
                    address = address >> 1  # 0x2 is written and will return zero on read as write new write will fail
1124
                data = data >> 1
1125
                mode.length =  mode.length + 1
1126
                buf2=don.read_data(1,0)  #read first byte
1127
                if ord(buf2[0]) != 0xFF:
1128
                    print "Test FAIL (At least one address line const. 0)!!!!!"
1129 9 nuubik
                    sys.exit()
1130 8 nuubik
            #-----------------------------------------------------------------------
1131
            #Marching zero test
1132
            address = 0xFFEFFFFF    # set word address
1133
            data = 0x100000
1134
            while mode.length<18: # last address to test 0x20 0000  
1135
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1136
                don.buffer_write(2,address,buf1)
1137
                don.parse_status()   #do this after programming all but uneaven ending
1138
                don.write_command(0x00FF) #  put flash to data read mode   
1139
                buf2=don.read_data(2,address&0x1FFFFF)  # word count and byte address read 64 words to speed up
1140
                if buf1 != buf2:
1141
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1142
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1143
                    print "Test FAIL!!!!!"
1144
                    sys.exit()
1145
                address = (address >> 1)|0xFF000000
1146
                data = data >> 1
1147
                mode.length =  mode.length + 1
1148
                buf2=don.read_data(1,0x1FFFFF)  #read first byte
1149
                if ord(buf2[0]) != 0xFF:
1150
                    print "Test FAIL (At least two address lines bonded)!!!!!"
1151 9 nuubik
                    sys.exit()
1152 8 nuubik
            if mode.b == 1:
1153
                #Erase Dongle
1154 9 nuubik
                print "Erasing"
1155 8 nuubik
                don.write_command(0x0060) # 0x0098
1156
                don.write_command(0x00D0) # 0x0098
1157
                don.wait_on_busy()
1158
                don.parse_status()
1159
                endBlock = 31
1160
                startBlock = 0
1161
                i=startBlock
1162
                while i <= endBlock:
1163 9 nuubik
                    if mode.v == 1:
1164
                        print 'Blanking block %i '%(i)
1165
                    else:
1166
                        sys.stdout.write(".")
1167
                        sys.stdout.flush()
1168 8 nuubik
                    don.erase_block(i)
1169 23 nuubik
                    if mode.version < 5:
1170
                        don.wait_on_busy()
1171
                        don.parse_status()   #do this after programming all but uneaven ending
1172 9 nuubik
                    i=i+1
1173
                if mode.v == 0:
1174
                    print " "
1175 8 nuubik
            print "Test SUCCESSFUL!"
1176 9 nuubik
            sys.exit()
1177 8 nuubik
        except IOError:
1178
            print "IO Error on file open"
1179
            sys.exit()
1180
 
1181 9 nuubik
if mode.e == 1:   # perform dongle test
1182
            #Erase Dongle
1183
            print "Erasing all"
1184
            don.write_command(0x0060) # 0x0098
1185
            don.write_command(0x00D0) # 0x0098
1186 23 nuubik
            if mode.version < 5:
1187
                don.wait_on_busy()
1188
                don.parse_status()
1189 9 nuubik
            endBlock = 31
1190
            startBlock = 0
1191
            i=startBlock
1192
            while i <= endBlock:
1193
                if mode.v == 1:
1194
                    print 'Erasing block %i '%(i)
1195
                else:
1196
                     sys.stdout.write(".")
1197
                     sys.stdout.flush()
1198
                don.erase_block(i)
1199 23 nuubik
                if mode.version < 5:
1200
                    don.wait_on_busy()
1201
                    don.parse_status()   #do this after programming all but uneaven ending
1202 9 nuubik
                i=i+1
1203
            if mode.v == 0: # add CRTL return to dots
1204
                print ""
1205 23 nuubik
            if mode.version >= 5:
1206
                print "Waiting for buffers to empty"
1207
                don.wait_on_busy()
1208
                don.parse_status()   #do this after programming all but uneaven ending
1209 9 nuubik
            print "Erase done."
1210 23 nuubik
 
1211
if mode.l == 1:   # perform dongle test            
1212
            #Erase Dongle
1213
            print "Status Loop test"
1214
            i=1024
1215
            startTime = time.clock()
1216
            while i > 0:
1217
                sys.stdout.write(".")
1218
                sys.stdout.flush()
1219
                don.wait_on_busy()
1220
                don.parse_status()   #do this after programming all but uneaven ending
1221
                i=i-1
1222
            if sys.platform=='win32':
1223
                endTime = (time.clock()-startTime)/1024.0
1224
                print "\nSystem round delay is %4f ms"%(endTime*1000.0)
1225
            sys.stdout.flush()
1226 2 nuubik
##########################################################

powered by: WebSVN 2.1.0

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