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

Subversion Repositories usb_dongle_fpga

[/] [usb_dongle_fpga/] [trunk/] [sw/] [dongle.py] - Blame information for rev 44

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

powered by: WebSVN 2.1.0

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