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

Subversion Repositories usb_dongle_fpga

[/] [usb_dongle_fpga/] [tags/] [version_1_4/] [sw/] [dongle.py] - Blame information for rev 8

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

Line No. Rev Author Line
1 2 nuubik
#! /usr/bin/python
2
# -*- coding: utf-8 -*-
3
##########################################################################
4
# LPC Dongle programming software 
5
#
6
# Copyright (C) 2006 Artec Design
7
# 
8
# This library is free software; you can redistribute it and/or
9
# modify it under the terms of the GNU Lesser General Public
10
# License as published by the Free Software Foundation; either
11
# version 2.1 of the License, or (at your option) any later version.
12
# 
13
# This software is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
# Lesser General Public License for more details.
17
 
18
# You should have received a copy of the GNU Lesser General Public
19
# License along with this library; if not, write to the Free Software
20
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
##########################################################################
22
 
23
#-------------------------------------------------------------------------
24
# Project:   LPC Dongle programming software 
25
# Name:      dongle.py
26
# Purpose:   Executable command line tool 
27
#
28
# Author:    Jüri Toomessoo <jyrit@artecdesign.ee>
29 8 nuubik
# Copyright: (c) 2006 by Artec Design
30 2 nuubik
# Licence:   LGPL
31
#
32
# Created:   06 Oct. 2006
33
# History:   12 oct. 2006  Version 1.0 released
34 8 nuubik
#            22 Feb. 2007  Test options added to test PCB board
35 2 nuubik
#            
36
#
37
#-------------------------------------------------------------------------
38
 
39
import os
40
import sys
41
import string
42
import time
43
from sets import *
44
from struct import *
45
from Uspp.uspp import *
46
 
47
#### global funcs ####
48
def usage(s):
49
    print "Artec USB Dongle programming utility"
50
    print "Usage: ",s," -c comport [-fvdq] filename address"
51
    print "       ",s," [-fvdqr] offset length filename"
52 8 nuubik
    print ""
53 2 nuubik
    print "Options:"
54
    print " -c        COM port"
55
    print " -v        Verbose"
56
    print " -f        Forced"
57
    print " -d        Debug"
58
    print " -q        Query"
59
    print " -r        Readback "
60 8 nuubik
    print ""
61
    print "Board test options: "
62
    print " -t        Marching one and zero test address + data (Device must be empty)"
63
    print " -e        Erase before test "
64
    print " -b        Leave flash blanc after test "
65
    print ""
66 2 nuubik
    print "Examples:"
67
    print ""
68
    print " ",s," -c COM3 loader.bin 0"
69
    print " ",s," -c /dev/ttyS3 content.bin 256K"
70
    print " ",s," -c COM3 device 1M"
71
    print " ",s," -c COM3 -r 0x0000 256 flashcontent.bin"
72
######################
73
 
74
 
75
class DongleMode:
76
    def __init__(self):
77
        self.v = 0
78
        self.f = 0
79
        self.d = 0
80
        self.q = 0
81
        self.r = 0
82 8 nuubik
        self.t = 0
83
        self.e = 0
84
        self.b = 0
85 2 nuubik
        self.filename=""
86
        self.portname=""
87
        self.address=-1
88
        self.offset=-1
89
        self.length=-1
90
 
91
    def convParamStr(self,param):
92
        mult = 1
93
        value = 0
94
        str = param
95
        if str.find("K")>-1:
96
            mult = 1024
97
            str=str.strip("K")
98
        if str.find("M")>-1:
99
            mult = 1024*1024
100
            str=str.strip("M")
101
        try:
102
            if str.find("x")>-1:
103
                value = int(str,0)*mult  #conver hex string to int
104
            else:
105
                value = int(str)*mult  #conver demical string to int
106
        except ValueError:
107
            print "Bad parameter format given for: ",param
108
 
109
        return value
110
 
111
 
112
 
113
 
114
class Dongle:
115
    def __init__(self,name, baud, timeout):  #time out in millis 1000 = 1s baud like 9600, 57600
116
        try:
117
            self.tty = SerialPort(name,timeout, baud)
118
        except:
119
            print "Unable to open port"
120
            sys.exit();
121
 
122
    def getReturn(self,byteCount):
123
        i=0
124
        while don.tty.inWaiting()<byteCount:
125
            i=i+1
126
            if i==10000*byteCount:
127
                break
128
        if i==10000*byteCount:
129
            print "Dongle not connected to port or not communicating"
130
            sys.exit()
131
        return don.tty.read(byteCount)  ## ret two bytes
132
 
133
    def write_command(self,command):
134
        lsb = command&0xff
135
        msb = (command>>8)&0xff
136
        self.tty.write_2bytes(msb,lsb)
137
 
138
    def get_address_buf(self,address):  #set word address
139
        lsbyte = address&0xff
140
        byte = (address>>8)&0xff
141
        msbyte = (address>>16)&0xff
142
        buffer = ""
143
        buffer += chr(lsbyte)
144
        buffer += chr(0xA0)
145
        buffer +=  chr(byte)
146
        buffer +=  chr(0xA1)
147
        buffer +=  chr(msbyte)
148
        buffer +=  chr(0xA2)
149
        evaluate = (address>>24)
150
        if evaluate != 0:
151
            print "Addressign fault. Too large address passed"
152
            sys.exit()
153
        return buffer
154
 
155
 
156
    def set_address(self,address):  #set word address
157
        lsbyte = address&0xff
158
        byte = (address>>8)&0xff
159
        msbyte = (address>>16)&0xff
160
        evaluate = (address>>24)
161
        if evaluate != 0:
162
            print "Addressign fault. Too large address passed"
163
            sys.exit()
164
        self.tty.write_2bytes(lsbyte,0xA0)            #set internal address to dongle
165
        self.tty.write_2bytes(byte,0xA1)            #set internal address to dongle
166
        self.tty.write_2bytes(msbyte,0xA2)            #send query command
167
 
168
    def read_data(self,wordCount,address):
169
        command = 0
170
        byteCount = wordCount<<1  #calc byte count
171
        if wordCount>0 :
172
            command = (command|wordCount)<<8;
173
            command = command|0xCD
174
            self.set_address(address)    # send read address
175
            self.write_command(command)  # send get data command
176
            return self.getReturn(byteCount)
177
        else:
178
            print "Word count can't be under 1"
179
            sys.exit()
180
 
181
    def read_status(self):
182
        don.write_command(0x0070) # 0x0098 //clear status
183
        command = 0
184
        wordCount= 1  #calc byte count
185
        byteCount = wordCount<<1
186
        command = (command|wordCount)<<8;
187
        command = command|0xCD
188
        self.write_command(command)  # send get data command
189
        return self.getReturn(byteCount)
190
 
191
 
192
    def get_block_no(self,address):
193
        return address >> 16 # 16 bit mode block is 64Kwords
194
 
195
    def wait_on_busy(self):
196
        exit=0
197
        while exit==0:
198
            buf=self.read_status()
199
            statReg = ord(buf[0])  #8 bit reg
200
            if statReg>>7 == 1:
201
                exit=1
202
 
203
    def parse_status(self):  # use only after wait on busy commad to get result of the operation
204
        exit = 0
205
        buf=self.read_status()
206
        statReg = ord(buf[0])  #8 bit reg
207
        if (statReg>>5)&1 == 1:
208
            print "Block erase suspended"
209
            exit = 1
210
        if (statReg>>4)&3 == 3:
211
            print "Error in command order"  #if bits 4 and 5 are set then 
212
            exit = 1
213
        if (statReg>>4)&3 == 1:
214
            print "Error in setting lock bit"
215
            exit = 1
216
        if (statReg>>3)&1 == 1:
217
            print "Low Programming Voltage Detected, Operation Aborted"
218
            exit = 1
219
        if (statReg>>2)&1 == 1:
220
            print "Programming suspended"
221
            exit = 1
222
        if (statReg>>1)&1 == 1:
223
            print "Block lock bit detected"
224
            exit = 1
225
        if exit == 1:
226
            sys.exit()
227
 
228
    def erase_block(self,blockNo):
229
        blockAddress = blockNo << 16
230
        command = 0x0020
231
        self.set_address(blockAddress)
232
        self.write_command(command)  #issue block erase
233
        command = 0x00D0
234
        self.write_command(command)  #issue block erase confirm
235
        self.wait_on_busy()
236
        self.parse_status()
237
 
238
    def buffer_write(self,wordCount,startAddress,buffer):
239
        # to speed up buffer writing compose all commands into one buffer
240
        # instead of multiple single writes this is needed as the FTDI chip
241
        # round lag is amazingly large with VCOM drivers
242
        #u = len(buffer)
243
        if len(buffer)<32:            #don't ever make unaligned writes
244
            i=len(buffer)
245
            while len(buffer)<32:
246
                buffer += "\xff"
247
        adrBuf = self.get_address_buf(startAddress)   #6 bytes total
248
        cmd_e8=""  #8 bytes total
249
        cmd_e8+= chr(16)   #make it always 16 wordCount
250
        cmd_e8+= chr(0xE8)
251
        cmd_wcnt=""  #10 bytes total
252
        cmd_wcnt+= chr(0x00)
253
        cmd_wcnt+= chr(16-1)
254
        cmd_buf=""  #12 bytes total
255
        cmd_buf+= chr(0x00)
256
        cmd_buf+= chr(0xD0)
257
        wr_buffer_cmd = adrBuf + cmd_e8 + cmd_wcnt + buffer + cmd_buf   #44 bytes total
258
        self.tty.write_buf_cmd(wr_buffer_cmd)
259
        # no wait needad as the FTDI chip is so slow
260
 
261
 
262
################## Main program #########################
263
 
264
 
265
last_ops = 0
266
mode = DongleMode()
267
# PARSE ARGUMENTS 
268
for arg in sys.argv:
269
    if len(sys.argv) == 1: # if no arguments display help
270 8 nuubik
       #usage(sys.argv[0])
271
       usage("dongle.py")
272 2 nuubik
       sys.exit()
273
    if arg in ("-h","--help","/help","/h"):
274 8 nuubik
        #usage(sys.argv[0])
275
        usage("dongle.py")
276 2 nuubik
        sys.exit()
277
    if arg in ("-c"):
278
        last_ops = sys.argv.index(arg) + 1  #if remains last set of options from here start ordered strings
279
        i = sys.argv.index(arg)
280
        print "Opening port: "+sys.argv[i+1]
281
        mode.portname = sys.argv[i+1]   # next element after -c open port for usage
282
    if arg[0]=="-" and arg[1]!="c": # if other opptions
283
        # parse all options in this
284
        last_ops = sys.argv.index(arg)  #if remains last set of options from here start ordered strings
285
        ops = arg[1:]# get all besides the - sign
286
        for op in ops:
287
            if op=="q":
288
                mode.q = 1
289
            if op=="v":
290
                mode.v = 1
291
            if op=="f":
292
                mode.f = 1
293
            if op=="d":
294
                mode.d = 1
295
            if op=="r":
296 8 nuubik
                mode.r = 1
297
            if op=="t":
298
                mode.t = 1
299
            if op=="e":
300
                mode.e = 1
301
            if op=="b":
302
                mode.b = 1
303 2 nuubik
    else:
304
        i = sys.argv.index(arg)
305
        if i ==  last_ops + 1:
306
            if mode.r==1:
307
                mode.offset=mode.convParamStr(arg)
308
            else:
309
                mode.filename=arg
310
        if i ==  last_ops + 2:
311
            if mode.r==1:
312
                mode.length=mode.convParamStr(arg)
313
            else:
314
                mode.address=mode.convParamStr(arg)
315
 
316
        if i ==  last_ops + 3:
317
            if mode.r==1:
318
                mode.filename=arg
319
            else:
320
                print "Too many parameters provided"
321
                sys.exit()
322
        if i >  last_ops + 3:
323
             print "Too many parameters provided"
324
             sys.exit()
325
 
326
# END PARSE ARGUMENTS             
327
 
328
if mode.portname=="":
329
    print "No port name given see -h for help"
330
    sys.exit()
331
else:
332
    # test PC speed to find sutable delay for linux driver
333
    # to get 250 us 
334
    mytime = time.clock()
335
    n = 0
336
    while (n < 100000):
337
        n += 1;
338
    k10Time = time.clock() - mytime   # time per 10000 while cycles
339
    wait = k10Time/100000.0     # time per while cycle
340
    wait = (0.00025/wait) * 1.20   # count for 250us + safe margin
341
 
342
    # ok done
343
    don = Dongle(mode.portname,115200,100)
344
    print wait
345
    don.tty.wait = wait
346
    don.write_command(0x0050) # 0x0098
347
    don.write_command(0x00C5)            #send dongle check internal command
348
    buf=don.getReturn(2)  # two bytes expected to this command
349
    if ord(buf[1])==0x32 and  ord(buf[0])==0x10:
350
        print "Dongle OK"
351
    else:
352
        print 'Dongle returned on open: %02x %02x '%(ord(buf[1]), ord(buf[0]))
353
 
354
 
355
if mode.q == 1:   # perform a query from dongle
356
    don.write_command(0x0050) # 0x0098
357
    don.write_command(0x0098) # 0x0098
358
    buf=don.read_data(3,0x000010)  # word count and word address
359
    if ord(buf[0])==0x51 and  ord(buf[2])==0x52 and  ord(buf[4])==0x59:
360
        buf=don.read_data(2,0x000000)  # word count and word address
361
        print 'Query  OK, Factory: 0x%02x device: 0x%02x '%(ord(buf[0]),ord(buf[2]))
362
        buf=don.read_data(2,0x000002)
363
        print 'lock bit is 0x%02x 0x%02x'%(ord(buf[0]),ord(buf[1]))
364
    else:
365
        print "Got bad query data:"
366
        print 'Query address 0x10 = 0x%02x%02x '%(ord(buf[1]),ord(buf[0]))
367
        print 'Query address 0x10 = 0x%02x%02x '%(ord(buf[3]),ord(buf[2]))
368
        print 'Query address 0x10 = 0x%02x%02x '%(ord(buf[5]),ord(buf[4]))
369
        print "Read byte count:",len(buf)
370
 
371
    don.write_command(0x00FF) # 0x0098
372
    buf=don.read_data(4,0xff57c0>>1)  # word count and word address     
373
    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]) )
374
 
375
 
376
 
377
if mode.filename!="" and mode.address!=-1:
378
    #Calculate number of blocks and start of blocks
379
    size = 0
380
    mode.address = mode.address>>1  #make word address
381
    try:
382
        f=open(mode.filename,"rb")
383
        f.seek(0,2) #seek to end
384
        size = f.tell()
385
        f.seek(0) #seek to start
386
        print 'File size %iK '%(size/1024)
387
        f.close()
388
    except IOError:
389
         print "IO Error on file open"
390
         sys.exit()
391
    #clear blockLock bits
392
    don.write_command(0x0060) # 0x0098
393
    don.write_command(0x00D0) # 0x0098
394
    don.wait_on_busy()
395
    don.parse_status()
396
    wordSize = (size+ (size&1))>> 1    # round byte count up and make word address
397
    endBlock = don.get_block_no(mode.address+wordSize - 1)
398
    startBlock = don.get_block_no(mode.address)
399
    i=startBlock
400
    while i <= endBlock:
401
        print 'Erasing block %i '%(i)
402
        don.erase_block(i)
403
        don.wait_on_busy()
404
        don.parse_status()   #do this after programming all but uneaven ending
405
        i=i+1
406
    #don.write_command(0x00FF) # 0x0098
407
    #buf=don.read_data(4,0x000000)  # word count and word address     
408
    #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]) )
409
 
410
    f=open(mode.filename,"rb")
411
    f.seek(0) #seek to start
412
    address= mode.address
413
    #don.set_address(address)
414
    while 1:
415
        if address/(1024*16) != (address-16)/(1024*16):  # get bytes from words if 512
416
            print 'Progress: %iK of %iK at 0x%06x'%((address-mode.address)/512,size/1024,address)
417
        buf = f.read(32)  #16 words is maximum write here bytes are read
418
        if len(buf)==32:
419
            don.buffer_write(16,address,buf)
420
            address = address + 16
421
        elif len(buf)>0:
422
            don.parse_status()   #do this after programming all but uneaven ending
423
            print "Doing an unaligned write..."
424
            length = len(buf)
425
            length = (length + (length&1))>> 1   #round up to get even word count
426
            buf = buf+"\xff"   #pad just in case rounding took place
427
            don.buffer_write(len,address,buf)
428
            address = address + 16     #inc word address
429
            break
430
        else:
431
            break
432
    print "Write DONE!"
433
    don.parse_status()   #do this after programming all but uneaven ending
434
    f.close()
435
 
436
if mode.r == 1:   # perform a readback
437
    if mode.offset!=-1 and mode.length!=-1 and mode.filename!="":
438
        mode.offset=mode.offset>>1    #make word offset
439
        mode.length= mode.length>>1   #make word length
440
        try:
441
            f=open(mode.filename,"wb")
442
            don.write_command(0x00FF) #  put flash to data read mode
443
            address = mode.offset    # set word address
444
            while 1:
445
                if address/(1024*32) != (address-128)/(1024*32):  # get K bytes from words if 512
446
                    print 'Progress: %iK of %iK'%((address-mode.offset)/512,mode.length/512)
447
                buf=don.read_data(128,address)  # word count and byte address read 64 words to speed up
448
                f.write(buf)
449
                #print "from address:",address<<1," ", len(buf)
450
                if address+128 >= (mode.offset + mode.length):  # 2+64 estimates the end to end in right place
451
                    break
452
                address = address + 128    #this is word address
453
            f.close()
454
            print "Readback done!"
455
        except IOError:
456
            print "IO Error on file open"
457
            sys.exit()
458
    else:
459
       print "Some of readback parameters missing..."
460
       print mode.offset,mode.length, mode.filename
461
       sys.exit()
462 8 nuubik
 
463
if mode.t == 1:   # perform dongle test
464
        print "Dongle TEST"
465
        if mode.e == 1:
466
            #Erase Dongle
467
            don.write_command(0x0060) # 0x0098
468
            don.write_command(0x00D0) # 0x0098
469
            don.wait_on_busy()
470
            don.parse_status()
471
            endBlock = 31
472
            startBlock = 0
473
            i=startBlock
474
            while i <= endBlock:
475
                print 'Erasing block %i '%(i)
476
                don.erase_block(i)
477
                don.wait_on_busy()
478
                don.parse_status()   #do this after programming all but uneaven ending
479
                i=i+1
480
        #Do marching one test on data and address
481
        mode.length= 0   #make word length
482
        try:
483
            #Marching one test
484
            #---------------------------------------------------------------------------
485
            address = 0x100000    # set word address
486
            data = 0x100000
487
            while mode.length<20: # last address to test 0x20 0000  
488
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
489
                don.buffer_write(2,address,buf1)
490
                don.parse_status()   #do this after programming all but uneaven ending
491
                don.write_command(0x00FF) #  put flash to data read mode   
492
                buf2=don.read_data(2,address)  # word count and byte address read 64 words to speed up
493
                if buf1 != buf2:
494
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
495
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
496
                    print "Test FAIL!!!!!"
497
                    sys.exit()
498
                address = address >> 1
499
                if address == 0x2:
500
                    address = address >> 1  # 0x2 is written and will return zero on read as write new write will fail
501
                data = data >> 1
502
                mode.length =  mode.length + 1
503
                buf2=don.read_data(1,0)  #read first byte
504
                if ord(buf2[0]) != 0xFF:
505
                    print "Test FAIL (At least one address line const. 0)!!!!!"
506
            #-----------------------------------------------------------------------
507
            #Marching zero test
508
            address = 0xFFEFFFFF    # set word address
509
            data = 0x100000
510
            while mode.length<18: # last address to test 0x20 0000  
511
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
512
                don.buffer_write(2,address,buf1)
513
                don.parse_status()   #do this after programming all but uneaven ending
514
                don.write_command(0x00FF) #  put flash to data read mode   
515
                buf2=don.read_data(2,address&0x1FFFFF)  # word count and byte address read 64 words to speed up
516
                if buf1 != buf2:
517
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
518
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
519
                    print "Test FAIL!!!!!"
520
                    sys.exit()
521
                address = (address >> 1)|0xFF000000
522
                data = data >> 1
523
                mode.length =  mode.length + 1
524
                buf2=don.read_data(1,0x1FFFFF)  #read first byte
525
                if ord(buf2[0]) != 0xFF:
526
                    print "Test FAIL (At least two address lines bonded)!!!!!"
527
 
528
            if mode.b == 1:
529
                #Erase Dongle
530
                don.write_command(0x0060) # 0x0098
531
                don.write_command(0x00D0) # 0x0098
532
                don.wait_on_busy()
533
                don.parse_status()
534
                endBlock = 31
535
                startBlock = 0
536
                i=startBlock
537
                while i <= endBlock:
538
                    print 'Blanking block %i '%(i)
539
                    don.erase_block(i)
540
                    don.wait_on_busy()
541
                    don.parse_status()   #do this after programming all but uneaven ending
542
                    i=i+1
543
            print "Test SUCCESSFUL!"
544
        except IOError:
545
            print "IO Error on file open"
546
            sys.exit()
547
 
548
 
549 2 nuubik
##########################################################

powered by: WebSVN 2.1.0

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