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 53

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 52 nuubik
#            14 Nov. 2007  Moved dongle specific code to class Dongle from USPP
38 17 nuubik
#                          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 46 nuubik
 
46
#            24 Apr. 2008  Mac OS X support by Stefan Reinauer <stepan@coresystems.de>
47 52 nuubik
#            09 Oct. 2008  Added Dongle ver 86 20 support. Support for mode setting
48
#                          PCB ver read and PSRAM read write support. (PSRAM is on Dongle II boards)
49
#            03 Nov. 2008  Added Dongle II board changes to PSRAM write so that the bytes are not swapped
50
#                          by dongle.py but in hardware pipeline
51 2 nuubik
#-------------------------------------------------------------------------
52
 
53
import os
54
import sys
55
import string
56
import time
57 23 nuubik
import struct
58 2 nuubik
from sets import *
59
from struct import *
60
 
61 52 nuubik
#### inline of artec FTDI specific Uspp code ###################################################
62 23 nuubik
 
63
##########################################################################
64
# USPP Library (Universal Serial Port Python Library)
65
#
66
# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
67
# 
68
# This library is free software; you can redistribute it and/or
69
# modify it under the terms of the GNU Lesser General Public
70
# License as published by the Free Software Foundation; either
71
# version 2.1 of the License, or (at your option) any later version.
72
# 
73
# This library is distributed in the hope that it will be useful,
74
# but WITHOUT ANY WARRANTY; without even the implied warranty of
75
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
76
# Lesser General Public License for more details.
77
 
78
# You should have received a copy of the GNU Lesser General Public
79
# License along with this library; if not, write to the Free Software
80
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
81
##########################################################################
82
 
83
#-------------------------------------------------------------------------
84
# Project:   USPP Library (Universal Serial Port Python Library)
85
# Name:      uspp.py
86
# Purpose:   Main module. Imports the correct module for the platform
87
#            in which it is running.
88
#
89
# Author:    Isaac Barona Martinez <ibarona@gmail.com>
90
# Contributors:
91
#            Damien Géranton <dgeranton@voila.fr>
92
#            Douglas Jones <dfj23@drexel.edu>
93
#            J.Grauheding <juergen.grauheding@a-city.de>
94
#            J.Toomessoo jyrit@artecdesign.ee
95
#
96
# Copyright: (c) 2006 by Isaac Barona Martinez
97
# Licence:   LGPL
98
#
99
# Created:   26 June 2001
100
# History:
101
#            05/08/2001: Release version 0.1.
102
#            24/02/2006: Final version 1.0.
103
#            10/11/2007: Added open retry code to dongle
104
#                        by Jyri Toomessoo jyrit@artecdesign.ee
105 52 nuubik
#            14/11/2007: Moved dongle specific code to class Dongle from USPP
106 23 nuubik
#                        USPP is allmost standard now (standard USPP would work)
107
#                        Artec USPP has serial open retry
108
#                        by Jyri Toomessoo jyrit@artecdesign.ee
109
#            10/03/2008: Forced code to hw flow control settings made linux 1 byte read to 2 bytes
110
#                        as dongle never reads 1 byte at the time
111
#                        by Jyri Toomessoo jyrit@artecdesign.ee
112
#            10/03/2008: Copose single infile bundle for FTDI USB serial 1.2
113
#                        this is nonuniversal modification of the code to suite the need of Artec Design Dongle
114
#                        by Jyri Toomessoo jyrit@artecdesign.ee
115
#-------------------------------------------------------------------------
116
 
117
 
118
drv_ok = 0
119
if sys.platform=='win32':
120
    print "Windows platform detected:"
121
    if drv_ok == 0:
122
        try:
123
            from win32file import *
124
            from win32event import *
125
            import win32con
126
            import exceptions
127
 
128
            print "Using VCP FTDI driver"
129
        except ImportError,SerialPortException:
130
            print "Python for winiows extensions for COM not found"
131
            print "(see https://sourceforge.net/projects/pywin32/)"
132
            print "Could not find any usable support for FTDI chip in python"
133
            print "Try installing python support from one of the links."
134
            sys.exit()
135
elif sys.platform=='linux2':
136
    from termios import *
137
    import fcntl
138
    import exceptions
139
    import array
140
    print "Linux platform detected:"
141 46 nuubik
elif sys.platform=='darwin':
142
    from termios import *
143
    import fcntl
144
    import exceptions
145
    import array
146
    print "Mac OS X platform detected:"
147 23 nuubik
else:
148
    sys.exit('Sorry, no implementation for this platform yet')
149
 
150
 
151
 
152
class SerialPortException(exceptions.Exception):
153
    """Exception raise in the SerialPort methods"""
154
    def __init__(self, args=None):
155
        self.args=args
156
    def __str__(self):
157
        return repr(self.args)
158
 
159
 
160
if sys.platform=='win32':
161
  class SerialPortWin:
162
    BaudRatesDic={110: CBR_110,
163
                  300: CBR_300,
164
                  600: CBR_600,
165
                  1200: CBR_1200,
166
                  2400: CBR_2400,
167
                  4800: CBR_4800,
168
                  9600: CBR_9600,
169
                  19200: CBR_19200,
170
                  38400: CBR_38400,
171
                  57600: CBR_57600,
172
                  115200: CBR_115200,
173
                  128000: CBR_128000,
174
                  256000: CBR_256000
175
                  }
176
 
177
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
178
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
179
        self.__mode=mode
180
        self.__params=params
181
        self.__speed = 0
182
        self.__reopen = 0
183
        while 1:
184
            try:
185
                self.__handle=CreateFile (dev,
186
                win32con.GENERIC_READ|win32con.GENERIC_WRITE,
187
                0, # exclusive access
188
                None, # no security
189
                win32con.OPEN_EXISTING,
190
                win32con.FILE_ATTRIBUTE_NORMAL,
191
                None)
192
                break
193
 
194
            except:
195
                n=0
196
                while (n < 2000000):
197
                    n += 1;
198
                self.__reopen = self.__reopen + 1
199
            if self.__reopen > 32:
200 52 nuubik
                print "Port does not exist... retries exhausted..."
201 23 nuubik
                raise SerialPortException('Port does not exist...')
202
                break
203
                #sys.exit()
204
        self.__configure()
205
 
206
    def __del__(self):
207
        if self.__speed:
208
            try:
209
                CloseHandle(self.__handle)
210
            except:
211
                raise SerialPortException('Unable to close port')
212
 
213
 
214
 
215
 
216
    def __configure(self):
217
        if not self.__speed:
218
            self.__speed=115200
219
        # Tell the port we want a notification on each char
220
        SetCommMask(self.__handle, EV_RXCHAR)
221
        # Setup a 4k buffer
222
        SetupComm(self.__handle, 4096, 4096)
223
        # Remove anything that was there
224
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
225
                  PURGE_RXCLEAR)
226
        if self.__timeout==None:
227
            timeouts= 0, 0, 0, 0, 0
228
        elif self.__timeout==0:
229
            timeouts = win32con.MAXDWORD, 0, 0, 0, 1000
230
        else:
231
            timeouts= self.__timeout, 0, self.__timeout, 0 , 1000
232
        SetCommTimeouts(self.__handle, timeouts)
233
 
234
        # Setup the connection info
235
        dcb=GetCommState(self.__handle)
236
        dcb.BaudRate=SerialPortWin.BaudRatesDic[self.__speed]
237
        if not self.__params:
238
            dcb.ByteSize=8
239
            dcb.Parity=NOPARITY
240
            dcb.StopBits=ONESTOPBIT
241
            dcb.fRtsControl=RTS_CONTROL_ENABLE
242
            dcb.fOutxCtsFlow=1
243
        else:
244
            dcb.ByteSize, dcb.Parity, dcb.StopBits=self.__params
245
        SetCommState(self.__handle, dcb)
246
 
247
 
248
    def fileno(self):
249
        return self.__handle
250
 
251
 
252
    def read(self, num=1):
253
        (Br, buff) = ReadFile(self.__handle, num)
254
        if len(buff)<>num and self.__timeout!=0: # Time-out  
255
            print 'Expected %i bytes but got %i before timeout'%(num,len(buff))
256
            raise SerialPortException('Timeout')
257
        else:
258
            return buff
259
 
260
 
261
    def readline(self):
262
        s = ''
263
        while not '\n' in s:
264
            s = s+SerialPortWin.read(self,1)
265
 
266
        return s
267
 
268
 
269
    def write(self, s):
270
        """Write the string s to the serial port"""
271
        errCode = 0
272
        overlapped=OVERLAPPED()
273
        overlapped.hEvent=CreateEvent(None, 0,0, None)
274
        (errCode, bytesWritten) = WriteFile(self.__handle, s,overlapped)
275
        # Wait for the write to complete
276
        WaitForSingleObject(overlapped.hEvent, INFINITE)
277
        return bytesWritten
278
 
279
    def inWaiting(self):
280
        """Returns the number of bytes waiting to be read"""
281
        flags, comstat = ClearCommError(self.__handle)
282
        return comstat.cbInQue
283
 
284
    def flush(self):
285
        """Discards all bytes from the output or input buffer"""
286
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
287
                  PURGE_RXCLEAR)
288
 
289
 
290
 
291 46 nuubik
if sys.platform=='linux2':
292 23 nuubik
  class SerialPortLin:
293
    """Encapsulate methods for accesing to a serial port."""
294
 
295
    BaudRatesDic={
296
        110: B110,
297
        300: B300,
298
        600: B600,
299
        1200: B1200,
300
        2400: B2400,
301
        4800: B4800,
302
        9600: B9600,
303
        19200: B19200,
304
        38400: B38400,
305
        57600: B57600,
306
        115200: B115200,
307
        230400: B230400
308
        }
309
    buf = array.array('h', '\000'*4)
310
 
311
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
312
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
313
        self.__mode=mode
314
        self.__params=params
315
        self.__speed = 0
316
        self.__reopen = 0
317
        while 1:
318
            try:
319
                self.__handle=os.open(dev, os.O_RDWR)
320
                break
321
 
322
            except:
323
                n=0
324
                while (n < 2000000):
325
                    n += 1;
326
                self.__reopen = self.__reopen + 1
327
            if self.__reopen > 32:
328
                print "Port does not exist..."
329
                raise SerialPortException('Port does not exist...')
330
                break
331
 
332
        self.__configure()
333
 
334
    def __del__(self):
335
        if self.__speed:
336
            #tcsetattr(self.__handle, TCSANOW, self.__oldmode)
337
            pass
338
            try:
339
                pass
340
                os.close(self.__handle)
341
            except IOError:
342
                raise SerialPortException('Unable to close port')
343
 
344
 
345
    def __configure(self):
346
        if not self.__speed:
347
            self.__speed=115200
348
 
349
        # Save the initial port configuration
350
        self.__oldmode=tcgetattr(self.__handle)
351
        if not self.__params:
352
            # print "Create linux params for serialport..."
353
            # self.__params is a list of attributes of the file descriptor
354
            # self.__handle as follows:
355
            # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
356
            # where cc is a list of the tty special characters.
357
            self.__params=[]
358
            # c_iflag
359
            self.__params.append(IGNPAR)
360
            # c_oflag
361
            self.__params.append(0)
362
            # c_cflag
363
            self.__params.append(CS8|CREAD|CRTSCTS)
364
            # c_lflag
365
            self.__params.append(0)
366
            # c_ispeed
367
            self.__params.append(SerialPortLin.BaudRatesDic[self.__speed])
368
            # c_ospeed
369
            self.__params.append(SerialPortLin.BaudRatesDic[self.__speed])
370
            cc=[0]*NCCS
371
        if self.__timeout==None:
372
            # A reading is only complete when VMIN characters have
373
            # been received (blocking reading)
374
            cc[VMIN]=1
375
            cc[VTIME]=0
376
        elif self.__timeout==0:
377
            cc[VMIN]=0
378
            cc[VTIME]=0
379
        else:
380
            cc[VMIN]=0
381
            cc[VTIME]=self.__timeout #/100
382
        self.__params.append(cc)               # c_cc
383
 
384
        tcsetattr(self.__handle, TCSANOW, self.__params)
385
 
386
 
387
    def fileno(self):
388
        return self.__handle
389
 
390
 
391
    def __read1(self):
392
        tryCnt = 0
393
        byte = ""
394
        while(len(byte)==0 and tryCnt<10):
395
            tryCnt+=1
396
            byte = os.read(self.__handle, 2)
397
        if len(byte)==0 and self.__timeout!=0: # Time-out
398
            print 'Time out cnt was %i'%(tryCnt)
399
            print 'Expected 1 byte but got %i before timeout'%(len(byte))
400
            sys.stdout.flush()
401
            raise SerialPortException('Timeout')
402
        else:
403
            return byte
404
 
405
 
406
    def read(self, num=1):
407
        s=''
408
        for i in range(num/2):
409
            s=s+SerialPortLin.__read1(self)
410
        return s
411
 
412
 
413
    def readline(self):
414
 
415
        s = ''
416
        while not '\n' in s:
417
            s = s+SerialPortLin.__read1(self)
418
 
419
        return s
420
 
421
 
422
    def write(self, s):
423
        """Write the string s to the serial port"""
424
        return os.write(self.__handle, s)
425
 
426
    def inWaiting(self):
427
        """Returns the number of bytes waiting to be read"""
428
        data = struct.pack("L", 0)
429
        data=fcntl.ioctl(self.__handle, TIOCINQ, data)
430
        return struct.unpack("L", data)[0]
431
 
432
    def outWaiting(self):
433
        """Returns the number of bytes waiting to be write
434
        mod. by J.Grauheding
435
        result needs some finetunning
436
        """
437
        rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)
438
        return rbuf
439
 
440
 
441
    def flush(self):
442
        """Discards all bytes from the output or input buffer"""
443
        tcflush(self.__handle, TCIOFLUSH)
444
 
445
 
446 46 nuubik
if sys.platform=='darwin':
447
  class SerialPortOSX:
448
    """Encapsulate methods for accesing to a serial port."""
449 23 nuubik
 
450 46 nuubik
    BaudRatesDic={
451
        110: B110,
452
        300: B300,
453
        600: B600,
454
        1200: B1200,
455
        2400: B2400,
456
        4800: B4800,
457
        9600: B9600,
458
        19200: B19200,
459
        38400: B38400,
460
        57600: B57600,
461
        115200: B115200,
462
        230400: B230400
463
        }
464
    buf = array.array('h', '\000'*4)
465
 
466
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
467
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
468
        self.__mode=mode
469
        self.__params=params
470
        self.__speed = 0
471
        self.__reopen = 0
472
        while 1:
473
            try:
474
                self.__handle=os.open(dev, os.O_RDWR)
475
                break
476
 
477
            except:
478
                n=0
479
                while (n < 2000000):
480
                    n += 1;
481
                self.__reopen = self.__reopen + 1
482
            if self.__reopen > 32:
483
                print "Port does not exist..."
484
                raise SerialPortException('Port does not exist...')
485
                break
486
 
487
        self.__configure()
488
 
489
    def __del__(self):
490
        if self.__speed:
491
            #tcsetattr(self.__handle, TCSANOW, self.__oldmode)
492
            pass
493
            try:
494
                pass
495
                #os.close(self.__handle)
496
            except IOError:
497
                raise SerialPortException('Unable to close port')
498
 
499
 
500
    def __configure(self):
501
        if not self.__speed:
502
            self.__speed=115200
503
 
504
        # Save the initial port configuration
505
        self.__oldmode=tcgetattr(self.__handle)
506
        if not self.__params:
507
            # print "Create MacOSX params for serialport..."
508
            # self.__params is a list of attributes of the file descriptor
509
            # self.__handle as follows:
510
            # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
511
            # where cc is a list of the tty special characters.
512
            self.__params=[]
513
            # c_iflag
514
            self.__params.append(IGNPAR)
515
            # c_oflag
516
            self.__params.append(0)
517
            # c_cflag
518
            self.__params.append(CS8|CREAD|CRTSCTS)
519
            # c_lflag
520
            self.__params.append(0)
521
            # c_ispeed
522
            self.__params.append(SerialPortOSX.BaudRatesDic[self.__speed])
523
            # c_ospeed
524
            self.__params.append(SerialPortOSX.BaudRatesDic[self.__speed])
525
            cc=[0]*NCCS
526
        if self.__timeout==None:
527
            # A reading is only complete when VMIN characters have
528
            # been received (blocking reading)
529
            cc[VMIN]=1
530
            cc[VTIME]=0
531
        elif self.__timeout==0:
532
            cc[VMIN]=0
533
            cc[VTIME]=0
534
        else:
535
            cc[VMIN]=0
536
            cc[VTIME]=self.__timeout #/100
537
        self.__params.append(cc)               # c_cc
538
 
539
        tcsetattr(self.__handle, TCSANOW, self.__params)
540
 
541
 
542
    def fileno(self):
543
        return self.__handle
544
 
545
 
546
    def __read1(self):
547
        tryCnt = 0
548
        byte = ""
549
        while(len(byte)==0 and tryCnt<10):
550
            tryCnt+=1
551
            byte = os.read(self.__handle, 2)
552
        if len(byte)==0 and self.__timeout!=0: # Time-out
553
            print 'Time out cnt was %i'%(tryCnt)
554
            print 'Expected 1 byte but got %i before timeout'%(len(byte))
555
            sys.stdout.flush()
556
            raise SerialPortException('Timeout')
557
        else:
558
            return byte
559
 
560
 
561
    def read(self, num=1):
562
        s=''
563
        for i in range(num/2):
564
            s=s+SerialPortOSX.__read1(self)
565
        return s
566
 
567
 
568
    def readline(self):
569
 
570
        s = ''
571
        while not '\n' in s:
572
            s = s+SerialPortOSX.__read1(self)
573
 
574
        return s
575
 
576
 
577
    def write(self, s):
578
        """Write the string s to the serial port"""
579
        return os.write(self.__handle, s)
580
 
581
    def inWaiting(self):
582
        """Returns the number of bytes waiting to be read"""
583
        data = struct.pack("L", 0)
584
        data=fcntl.ioctl(self.__handle, FIONREAD, data)
585
        return struct.unpack("L", data)[0]
586
 
587
    def outWaiting(self):
588
        """Returns the number of bytes waiting to be write
589
        mod. by J.Grauheding
590
        result needs some finetunning
591
        """
592
        rbuf=fcntl.ioctl(self.__handle, FIONWRITE, self.buf)
593
        return rbuf
594
 
595
 
596
    def flush(self):
597
        """Discards all bytes from the output or input buffer"""
598
        tcflush(self.__handle, TCIOFLUSH)
599
 
600
 
601
 
602 52 nuubik
#### end inline of artec FTDI specific Uspp code ###############################################
603 23 nuubik
 
604
 
605
#### Dongle code starts here  ##################################################################
606
 
607
 
608 2 nuubik
#### global funcs ####
609
def usage(s):
610 52 nuubik
    print "Artec USB Dongle programming utility ver. 2.7 prerelease"
611 17 nuubik
    print "Usage:"
612
    print "Write file      : ",s," [-vq] -c <name> <file> <offset>"
613
    print "Readback file   : ",s," [-vq] -c <name> [-vq] -r <offset> <length> <file>"
614 2 nuubik
    print "Options:"
615 17 nuubik
    print " <file> <offset> When file and offset are given file will be written to dongle"
616
    print "        file:    File name to be written to dongle"
617
    print "        offset:  Specifies data writing starting point in bytes to 4M window"
618
    print "                 For ThinCan boot code the offset = 4M - filesize. To write"
619 52 nuubik
    print "                 256K file the offset must be 3840K or EOF"
620
    print "                 EOF marker will cause the dongle.py to calculate suitable offset"
621
    print "                 and also cause files with odd byte count to be front padded"
622 17 nuubik
    print " "
623
    print " -c <name>       Indicate port name where the USB Serial Device is"
624
    print "        name:    COM port name in Windows or Linux Examples: COM3,/dev/ttyS3"
625
    print "                 See Device Manager in windows for USB Serial Port number"
626
    print " "
627
    print " -v              Enable verbose mode. Displays more progress information"
628
    print " "
629
    print " -q              Perform flash query to see if dongle flash is responding"
630
    print " "
631
    print " -r <offset> <length> <file>  Readback data. Available window size is 4MB"
632 23 nuubik
    print "        offset:  Offset byte addres inside 4MB window. Example: 1M"
633
    print "                 use M for MegaBytes, K for KiloBytes, none for bytes"
634
    print "                 use 0x prefix to indicate hexademical number format"
635 17 nuubik
    print "        length:  Amount in bytes to read starting from offset. Example: 1M"
636
    print "                 use M for MegaBytes, K for KiloBytes, none for bytes"
637
    print "        file:    Filename where data will be written"
638
    print " "
639
    print " -e              Erase device. Erases Full 4 MegaBytes"
640 8 nuubik
    print "Board test options: "
641 17 nuubik
    print " -t              Marching one and zero test. Device must be empty"
642
    print "                 To test dongle erase the flash with command -e"
643
    print "                 Enables dongle memory tests to be executed by user"
644
    print " "
645 29 nuubik
    print " -b              Leave flash blank after test. Used with option -t"
646 23 nuubik
    print " -l              Fast poll loop test. Does poll loop 1024 times"
647
    print "                 used to stress test connection"
648 52 nuubik
    print " -p and -P       Used to change ldev_present_n signal on Dongle II LPC interface"
649
    print "                 -p will cause the signal to go low and -P to go high"
650
    print "                 from reset and when dongle FPGA is not configured the signal is low."
651
    print "                 The state is not held when power is disconnected"
652 8 nuubik
    print ""
653 2 nuubik
    print "Examples:"
654
    print ""
655 17 nuubik
    print " ",s," -c COM3 loader.bin 0                       "
656
    print " ",s," -c /dev/ttyS3 boot.bin 3840K"
657
    print " ",s," -c COM3 -r 0x3C0000 256K flashcontent.bin"
658 46 nuubik
    print " ",s," -c /dev/cu.usbserial-003011FD -v (Mac OS X)"
659 2 nuubik
######################
660
 
661
 
662
class DongleMode:
663
    def __init__(self):
664
        self.v = 0
665
        self.f = 0
666
        self.d = 0
667
        self.q = 0
668
        self.r = 0
669 8 nuubik
        self.t = 0
670
        self.e = 0
671 23 nuubik
        self.b = 0
672
        self.l = 0
673 52 nuubik
        self.p = 0
674
        self.u = 0
675 2 nuubik
        self.filename=""
676
        self.portname=""
677
        self.address=-1
678 52 nuubik
        self.eof=-1
679
        self.oddSize=0
680
        self.oddAddr=0
681 2 nuubik
        self.offset=-1
682
        self.length=-1
683 23 nuubik
        self.version=4
684 52 nuubik
        self.region=-1
685 2 nuubik
 
686
    def convParamStr(self,param):
687
        mult = 1
688
        value = 0
689
        str = param
690
        if str.find("K")>-1:
691
            mult = 1024
692
            str=str.strip("K")
693
        if str.find("M")>-1:
694
            mult = 1024*1024
695
            str=str.strip("M")
696
        try:
697
            if str.find("x")>-1:
698
                value = int(str,0)*mult  #conver hex string to int
699
            else:
700
                value = int(str)*mult  #conver demical string to int
701
        except ValueError:
702
            print "Bad parameter format given for: ",param
703
 
704
        return value
705
 
706
 
707
 
708
 
709
class Dongle:
710
    def __init__(self,name, baud, timeout):  #time out in millis 1000 = 1s baud like 9600, 57600
711 23 nuubik
        self.mode = 0
712 2 nuubik
        try:
713 23 nuubik
            if sys.platform=='win32':
714
                self.tty = SerialPortWin(name,timeout, baud)
715 46 nuubik
            elif sys.platform=='linux2':
716 23 nuubik
                self.tty = SerialPortLin(name,timeout, baud)
717 46 nuubik
            elif sys.platform=='darwin':
718
                self.tty = SerialPortOSX(name,timeout, baud)
719 23 nuubik
 
720 17 nuubik
        except SerialPortException , e:
721
            print "Unable to open port " + name
722 2 nuubik
            sys.exit();
723 9 nuubik
 
724
    def testReturn(self,byteCount):
725
        i=0
726
        while don.tty.inWaiting()<byteCount:
727
            i=i+1
728
            if i==10000*byteCount:
729
                break
730
        if i==10000*byteCount:
731
            return 0
732 23 nuubik
        j=don.tty.inWaiting()
733
        #print "Tested in waiting %i needed %i"%(j,byteCount)
734
        return j  ## ret two bytes            
735 9 nuubik
 
736 2 nuubik
    def getReturn(self,byteCount):
737
        i=0
738 23 nuubik
        #while don.tty.inWaiting()<byteCount:
739
        #    i=i+1
740
        #    time.sleep(0.1)
741
        #    if i==100*byteCount:
742
        #        print "Dongle not communicating"
743
        #        #print "Read in waiting %i needed %i was %i"%(i,byteCount,don.tty.inWaiting())
744
        #        sys.exit()
745
        #        break
746
 
747
        #i=don.tty.inWaiting()
748
        #print "Read in waiting %i needed %i was %i"%(i,byteCount,don.tty.inWaiting())
749
        buf = don.tty.read(byteCount)
750
        #print "Got bytes =%i "%(len(buf))
751
        return buf  ## ret two bytes
752 9 nuubik
 
753 2 nuubik
 
754
    def write_command(self,command):
755
        lsb = command&0xff
756
        msb = (command>>8)&0xff
757 17 nuubik
        self.write_2bytes(msb,lsb)
758
 
759
    def write_2bytes(self, msb,lsb):
760
        """Write one word MSB,LSB to the serial port MSB first"""
761 52 nuubik
        #print "---------->  CMD %02x %02x"%(msb,lsb)
762 17 nuubik
        s = pack('BB', msb, lsb)
763 23 nuubik
        ret = self.tty.write(s)
764
        if(ret<len(s)):
765
            print 'write_2byte: Wrote less then needed %i bytes from %i'%(ret,length(s))
766 17 nuubik
        # Wait for the write to complete
767
        #WaitForSingleObject(overlapped.hEvent, INFINITE)               
768 2 nuubik
 
769
    def get_address_buf(self,address):  #set word address
770
        lsbyte = address&0xff
771
        byte = (address>>8)&0xff
772
        msbyte = (address>>16)&0xff
773
        buffer = ""
774
        buffer += chr(lsbyte)
775
        buffer += chr(0xA0)
776
        buffer +=  chr(byte)
777
        buffer +=  chr(0xA1)
778
        buffer +=  chr(msbyte)
779
        buffer +=  chr(0xA2)
780
        evaluate = (address>>24)
781
        if evaluate != 0:
782
            print "Addressign fault. Too large address passed"
783
            sys.exit()
784
        return buffer
785
 
786
 
787
    def set_address(self,address):  #set word address
788
        lsbyte = address&0xff
789
        byte = (address>>8)&0xff
790
        msbyte = (address>>16)&0xff
791
        evaluate = (address>>24)
792
        if evaluate != 0:
793 52 nuubik
            print "Addressing fault. Too large address passed"
794 2 nuubik
            sys.exit()
795 17 nuubik
        self.write_2bytes(lsbyte,0xA0)            #set internal address to dongle
796
        self.write_2bytes(byte,0xA1)            #set internal address to dongle
797
        self.write_2bytes(msbyte,0xA2)            #send query command
798 2 nuubik
 
799
    def read_data(self,wordCount,address):
800
        command = 0
801
        byteCount = wordCount<<1  #calc byte count
802
        if wordCount>0 :
803 52 nuubik
            command = (command|wordCount)<<8
804 2 nuubik
            command = command|0xCD
805
            self.set_address(address)    # send read address
806
            self.write_command(command)  # send get data command
807
            return self.getReturn(byteCount)
808
        else:
809
            print "Word count can't be under 1"
810
            sys.exit()
811 23 nuubik
 
812 2 nuubik
 
813 23 nuubik
    def issue_blk_read(self):
814
        command = 0
815
        wordCount = 0
816
        byteCount = wordCount<<1  #calc byte count
817 52 nuubik
        command = (command|wordCount)<<8
818 23 nuubik
        command = command|0xCD
819
        self.write_command(command)  # send get data command
820
 
821
 
822
 
823
 
824 2 nuubik
    def read_status(self):
825
        don.write_command(0x0070) # 0x0098 //clear status
826
        command = 0
827
        wordCount= 1  #calc byte count
828
        byteCount = wordCount<<1
829 52 nuubik
        command = (command|wordCount)<<8
830 2 nuubik
        command = command|0xCD
831
        self.write_command(command)  # send get data command
832
        return self.getReturn(byteCount)
833
 
834
 
835
    def get_block_no(self,address):
836
        return address >> 16 # 16 bit mode block is 64Kwords
837
 
838
    def wait_on_busy(self):
839
        exit=0
840
        while exit==0:
841
            buf=self.read_status()
842
            statReg = ord(buf[0])  #8 bit reg
843
            if statReg>>7 == 1:
844
                exit=1
845
 
846
    def parse_status(self):  # use only after wait on busy commad to get result of the operation
847
        exit = 0
848
        buf=self.read_status()
849
        statReg = ord(buf[0])  #8 bit reg
850
        if (statReg>>5)&1 == 1:
851
            print "Block erase suspended"
852
            exit = 1
853
        if (statReg>>4)&3 == 3:
854
            print "Error in command order"  #if bits 4 and 5 are set then 
855
            exit = 1
856
        if (statReg>>4)&3 == 1:
857
            print "Error in setting lock bit"
858
            exit = 1
859
        if (statReg>>3)&1 == 1:
860
            print "Low Programming Voltage Detected, Operation Aborted"
861
            exit = 1
862
        if (statReg>>2)&1 == 1:
863
            print "Programming suspended"
864
            exit = 1
865
        if (statReg>>1)&1 == 1:
866
            print "Block lock bit detected"
867
            exit = 1
868
        if exit == 1:
869
            sys.exit()
870
 
871
    def erase_block(self,blockNo):
872
        blockAddress = blockNo << 16
873
        command = 0x0020
874
        self.set_address(blockAddress)
875
        self.write_command(command)  #issue block erase
876
        command = 0x00D0
877
        self.write_command(command)  #issue block erase confirm
878 23 nuubik
        #self.wait_on_busy()
879
        #self.parse_status()
880 2 nuubik
 
881 52 nuubik
    def buffer_write_ram(self,startAddress,word_buf):
882
        wordsWritten = 0
883
        length = len(word_buf)  # get the byte count
884
        #print "block write request for word cnt= %i"%(length//2)
885
        if length == 65536*2:
886
            #print "block write word cnt = 65536"
887
            adrBuf = self.get_address_buf(startAddress+wordsWritten)   #6 bytes total         
888
            cmd_e8=""  #8 bytes total
889
            cmd_e8+= chr(0)   #write word count 0 is 64K words
890
            cmd_e8+= chr(0xE9)
891
            buffer = adrBuf+cmd_e8 #prepare command
892
            #i=0
893
            #while i<65536*2:
894
            #    buffer = buffer + word_buf[wordsWritten*2+i+1]+word_buf[wordsWritten*2+i]
895
            #    i=i+2
896
            #print "block write buffer size = %i"%(len(word_buf[:wordsWritten*2+65536*2]))
897
            buffer = buffer + word_buf[0:wordsWritten*2+65536*2]
898
            self.tty.write(buffer)
899
            wordsWritten = wordsWritten + 65536 - 2  #two last words are written brokenly bu large block write
900
            length = length - 65536*2 + 4 # this amout has been written (two last words are written brokenly bu large block write)
901
        if length >= 32:  # can't write in one go so we must loop the code
902
            while length>=32:  #if we have atleast 32 bytes
903
                cmd_e8=""  #8 bytes total
904
                adrBuf = self.get_address_buf(startAddress+wordsWritten)   #6 bytes total
905
                #print "block write word cnt = 16"
906
                cmd_e8+= chr(16)   #write word count 16 is 32 bytes
907
                cmd_e8+= chr(0xE9)
908
                buffer = adrBuf + cmd_e8 #prepare command
909
                #i=0
910
                #while i<32:
911
                #    #print "Adding to write buffer %02x%02x"%(ord(word_buf[i+1]),ord(word_buf[i]))
912
                #    buffer = buffer + word_buf[wordsWritten*2+i+1]+word_buf[wordsWritten*2+i]
913
                #    i=i+2
914
                #print "block write buffer size = %i"%(len(word_buf[wordsWritten*2:wordsWritten*2+32]))
915
                buffer = buffer + word_buf[wordsWritten*2:wordsWritten*2+32]
916
                self.tty.write(buffer) #ok buffer is filled
917
                wordsWritten = wordsWritten + 16
918
                length = length - 32 # this amout has been written
919
        #and finally deal with smaller writes than 64K or 16 word blocks
920
        if length%2==1:  #uneven byte count given we must add one byte of padding
921
            print "uneaven write byte count, length = %i padding the end with extra byte 0xff "%(length)
922
            word_buf=word_buf+chr(0xFF)
923
        if length > 0:
924
            #print "block write tail word cnt= %i"%(length//2+length%2)
925
            adrBuf = self.get_address_buf(startAddress+wordsWritten)   #6 bytes total
926
            cmd_e8=""  #8 bytes total
927
            cmd_e8+= chr(length//2+length%2)   #write word count 0 is 64K words
928
            cmd_e8+= chr(0xE9)
929
            buffer = adrBuf + cmd_e8
930
            #i=0
931
            #while i<length+length%2:
932
            #    buffer = buffer + word_buf[wordsWritten*2+i+1]+word_buf[wordsWritten*2+i]
933
            #    i=i+2
934
            #print "block write buffer size = %i"%(len(word_buf[wordsWritten*2:wordsWritten*2+length+length%2]))
935
            buffer = buffer + word_buf[wordsWritten*2:wordsWritten*2+length+length%2]
936
            self.tty.write(buffer)
937
 
938
 
939
 
940 2 nuubik
    def buffer_write(self,wordCount,startAddress,buffer):
941
        # to speed up buffer writing compose all commands into one buffer
942
        # instead of multiple single writes this is needed as the FTDI chip
943
        # round lag is amazingly large with VCOM drivers
944
        #u = len(buffer)
945
        if len(buffer)<32:            #don't ever make unaligned writes
946
            i=len(buffer)
947
            while len(buffer)<32:
948
                buffer += "\xff"
949
        adrBuf = self.get_address_buf(startAddress)   #6 bytes total
950
        cmd_e8=""  #8 bytes total
951
        cmd_e8+= chr(16)   #make it always 16 wordCount
952
        cmd_e8+= chr(0xE8)
953
        cmd_wcnt=""  #10 bytes total
954
        cmd_wcnt+= chr(0x00)
955
        cmd_wcnt+= chr(16-1)
956
        cmd_buf=""  #12 bytes total
957
        cmd_buf+= chr(0x00)
958
        cmd_buf+= chr(0xD0)
959
        wr_buffer_cmd = adrBuf + cmd_e8 + cmd_wcnt + buffer + cmd_buf   #44 bytes total
960 17 nuubik
        self.write_buf_cmd(wr_buffer_cmd)
961 23 nuubik
 
962
        if self.mode.version <5:
963
            n = 0
964
            if sys.platform=='win32':
965
                while (n < 1024):
966
                    n += 1;
967 46 nuubik
            elif sys.platform=='linux2' or sys.platform=='darwin':
968 23 nuubik
                #Linux FTDI VCP driver is way faster and needs longer grace time than windows driver
969
                while (n < 1024*8):
970
                    n += 1;
971 17 nuubik
 
972
    def write_buf_cmd(self, buffer):
973
        """Write one word MSB,LSB to the serial port MSB first"""
974
        a=0
975
        s=""
976
        if (len(buffer) < 44):  # if buffer is shorter than expected then pad with read array mode commands
977
            i=0
978
            while i<len(buffer):
979
                print '0x%02x'%(ord(buffer[i]))
980
                i+=1
981
            while(a < len(buffer)):
982
                if a < 10:
983
                    s= pack('2c', buffer[a], buffer[a+1])
984
                    self.tty.write(s)
985
                elif a < len(buffer)-2:
986
                    s= pack('2c', buffer[a+1], buffer[a])
987
                    self.tty.write(s)
988
                elif  len(buffer)==2:
989
                    s=pack('2c', buffer[a], buffer[a+1])
990
                    self.tty.write(s)
991
                else:
992
                     s=pack('2c', buffer[a], chr(0xFF))
993
                     self.tty.write(s)
994
                a+=2
995
        else:
996
            #first 10 bytes are in correct order + 32 data bytes are in wrong order and + 2 confirm bytes are in correct order
997
            s=pack('44c',
998
            buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7],
999
            buffer[8], buffer[9], buffer[11], buffer[10], buffer[13], buffer[12], buffer[15], buffer[14],
1000
            buffer[17], buffer[16], buffer[19], buffer[18], buffer[21], buffer[20], buffer[23], buffer[22],
1001
            buffer[25], buffer[24], buffer[27], buffer[26], buffer[29], buffer[28], buffer[31], buffer[30],
1002
            buffer[33], buffer[32], buffer[35], buffer[34], buffer[37], buffer[36], buffer[39], buffer[38],
1003
            buffer[41], buffer[40], buffer[42], buffer[43]
1004
            )
1005 23 nuubik
            ret = self.tty.write(s)
1006
 
1007 2 nuubik
 
1008 52 nuubik
############# Main program functions #################### 
1009 2 nuubik
 
1010 52 nuubik
def flash_write(mode,don):
1011 2 nuubik
    #Calculate number of blocks and start of blocks
1012
    size = 0
1013 52 nuubik
    if mode.address&1 == 1:
1014
        mode.oddAddr=1
1015 2 nuubik
    mode.address = mode.address>>1  #make word address
1016
    try:
1017
        f=open(mode.filename,"rb")
1018
        f.seek(0,2) #seek to end
1019
        size = f.tell()
1020
        f.seek(0) #seek to start
1021
        print 'File size %iK '%(size/1024)
1022
        f.close()
1023
    except IOError:
1024 42 nuubik
         print "IO Error on file open. File missing or no premission to open."
1025 52 nuubik
         don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1026
         don.write_command(0xC6C5)   #clear lock bit
1027
         ret_buf=don.getReturn(2)    #two bytes expected to this command         
1028 2 nuubik
         sys.exit()
1029 52 nuubik
 
1030
    if mode.eof==1:
1031
        if (size&1==1):
1032
            mode.oddSize = 1
1033
        region_size_w = 0x200000     # 4M region word count
1034
        #print "Given region size = %i bytes"%(region_size_w*2)
1035
        file_size_w = (size+ (size&1))>> 1
1036
        #print "Given file size = %i bytes"%(file_size_w*2)
1037
        mode.address = region_size_w - file_size_w
1038
        print "Offset will be 0x%x"%(mode.address*2)
1039
 
1040
 
1041 2 nuubik
    #clear blockLock bits
1042
    don.write_command(0x0060) # 0x0098
1043
    don.write_command(0x00D0) # 0x0098
1044 23 nuubik
    if mode.version < 5:
1045
        don.wait_on_busy()
1046
        don.parse_status()
1047 52 nuubik
    wordSize = (size+ (size&1))>> 1    # round byte count up and make word address    
1048 2 nuubik
    endBlock = don.get_block_no(mode.address+wordSize - 1)
1049
    startBlock = don.get_block_no(mode.address)
1050 44 nuubik
    if endBlock >= 32:
1051 42 nuubik
        print "Given file does not fit into remaining space. File size is %i KB"%(size/1024)
1052
        print "Space left from given offset is %i KB"%((4*1024*1024-mode.address*2)/1024)
1053 52 nuubik
        don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1054
        don.write_command(0xC6C5)   #clear lock bit
1055
        ret_buf=don.getReturn(2)    #two bytes expected to this command                 
1056 42 nuubik
        sys.exit()
1057 2 nuubik
    i=startBlock
1058 9 nuubik
    print 'Erasing from block %i to %i '%(i,endBlock)
1059 2 nuubik
    while i <= endBlock:
1060 9 nuubik
        if mode.v == 1:
1061
            print 'Erasing block %i '%(i)
1062
        else:
1063
            sys.stdout.write(".")
1064
            sys.stdout.flush()
1065 2 nuubik
        don.erase_block(i)
1066 23 nuubik
        if mode.version < 5:
1067
            don.wait_on_busy()
1068
            don.parse_status()   #do this after programming all but uneaven ending
1069 2 nuubik
        i=i+1
1070 9 nuubik
    if mode.v == 0:
1071
        print " "
1072 2 nuubik
    f=open(mode.filename,"rb")
1073
    f.seek(0) #seek to start
1074
    address= mode.address
1075
    #don.set_address(address)
1076 9 nuubik
    print 'Writing %iK'%(size/1024)
1077 2 nuubik
    while 1:
1078 9 nuubik
        if (address/(1024*64) != (address-16)/(1024*64)) and address != mode.address:  # get bytes from words if 512
1079
            if mode.v == 1:
1080
                print 'Progress: %iK of %iK at 0x%06x'%((address-mode.address)/512,size/1024,address)
1081
            else:
1082
                sys.stdout.write(".")
1083
                sys.stdout.flush()
1084 52 nuubik
        if mode.oddSize==1 or mode.oddAddr==1:
1085
            mode.oddSize = 0   # odd file size when writing BIOS to the end of region should be also front padded
1086
            mode.oddAddr = 0   # as odd address is shifted right padding should be added in front of data
1087
            buf = "\xFF"+f.read(31)  #16 words is maximum write here bytes are read
1088
        else:
1089
            buf = f.read(32)  #16 words is maximum write here bytes are read
1090
 
1091 2 nuubik
        if len(buf)==32:
1092
            don.buffer_write(16,address,buf)
1093
            address = address + 16
1094
        elif len(buf)>0:
1095
            don.parse_status()   #do this after programming all but uneaven ending
1096
            print "Doing an unaligned write..."
1097
            length = len(buf)
1098
            length = (length + (length&1))>> 1   #round up to get even word count
1099
            buf = buf+"\xff"   #pad just in case rounding took place
1100
            don.buffer_write(len,address,buf)
1101
            address = address + 16     #inc word address
1102
            break
1103
        else:
1104
            break
1105 9 nuubik
    if mode.v == 0:
1106
        print " "
1107 23 nuubik
    if mode.version >= 5:
1108
        print "Waiting for buffers to empty"
1109
        don.wait_on_busy()
1110
        don.parse_status()   #do this after programming all but uneaven ending        
1111 2 nuubik
    print "Write DONE!"
1112
    don.parse_status()   #do this after programming all but uneaven ending
1113 52 nuubik
    f.close()
1114
    don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1115 2 nuubik
 
1116 52 nuubik
 
1117
 
1118
def psram_write(mode,don):
1119
    #Calculate number of blocks and start of blocks
1120
    size = 0
1121
    if mode.address&1 == 1:
1122
        mode.oddAddr=1
1123
    mode.address = mode.address>>1  #make word address
1124
    #check that file exists
1125
    try:
1126
        f=open(mode.filename,"rb")
1127
        f.seek(0,2) #seek to end
1128
        size = f.tell()
1129
        f.seek(0) #seek to start
1130
        print 'File size %iK '%(size/1024)
1131
        f.close()
1132
    except IOError:
1133
         print "IO Error on file open. File missing or no premission to open."
1134
         don.write_command(0xC6C5)   #clear lock bit
1135
         ret_buf=don.getReturn(2)    #two bytes expected to this command                  
1136
         sys.exit()
1137
 
1138
    if mode.eof==1:
1139
        if (size&1==1):
1140
            mode.oddSize = 1   # deal with odd file sizes        
1141
        region_size_w = 0x200000     # 4M region word count
1142
        #print "Given region size = %i bytes"%(region_size_w*2)
1143
        file_size_w = (size+ (size&1))>> 1
1144
        #print "Given file size = %i bytes"%(file_size_w*2)
1145
        mode.address = region_size_w - file_size_w
1146
        print "Offset will be 0x%x"%(mode.address*2)
1147
 
1148
 
1149
    #check that file size fits to remaining space given     
1150
    wordSize = (size+ (size&1))>> 1    # round byte count up and make word address
1151
    endBlock = don.get_block_no(mode.address+wordSize - 1)
1152
    startBlock = don.get_block_no(mode.address)
1153
    if endBlock >= 32:
1154
        print "Given file does not fit into remaining space. File size is %i KB"%(size/1024)
1155
        print "Space left from given offset is %i KB"%((4*1024*1024-mode.address*2)/1024)
1156
        don.write_command(0xC6C5)   #clear lock bit
1157
        ret_buf=don.getReturn(2)    #two bytes expected to this command                 
1158
        sys.exit()
1159
    i=startBlock
1160
    #Start writing the file content to dongle PSRAM
1161
    f=open(mode.filename,"rb")
1162
    f.seek(0) #seek to start
1163
    address= mode.address
1164
    #don.set_address(address)
1165
    print 'Writing %iK'%(size/1024)
1166
    while 1:
1167
        if (address/(1024*64) != (address-16)/(1024*64)) and address != mode.address:  # get bytes from words if 512
1168
            if mode.v == 1:
1169
                print 'Progress: %iK of %iK at 0x%06x'%((address-mode.address)/512,size/1024,address)
1170
            else:
1171
                sys.stdout.write(".")
1172
                sys.stdout.flush()
1173
        if mode.oddSize==1 or mode.oddAddr==1:
1174
            mode.oddSize = 0
1175
            mode.oddAddr = 0
1176
            buf = "\xFF"+f.read(65536*2-1)  #65536 words is maximum write here bytes are read (*2 is byte count)
1177
        else:
1178
            buf = f.read(65536*2)  #65536 words is maximum write here bytes are read (*2 is byte count)
1179
 
1180
        if len(buf)==65536*2:
1181
            don.buffer_write_ram(address,buf)
1182
            address = address + 65536  # add word count
1183
        elif len(buf)>0:
1184
            print "Doing an unaligned write..."
1185
            length = len(buf)
1186
            don.buffer_write_ram(address,buf)
1187
            address = address + length//2     #inc word address
1188
            break
1189
        else:
1190
            break
1191
    if mode.v == 0:
1192
        print " "
1193
    print "Write DONE!"
1194
    f.close()
1195
 
1196
 
1197
def flash_read(mode,don):
1198 2 nuubik
    if mode.offset!=-1 and mode.length!=-1 and mode.filename!="":
1199 23 nuubik
        if mode.version >= 5:
1200
            ##################### from hw ver 5 readback code ##################################################
1201
            blockCount = (mode.length>>17)+1 #read this many 64K word blocks
1202
            mode.offset=mode.offset>>1    #make word offset
1203
            lastLength = mode.length&0x0001FFFF
1204
            mode.length= mode.length>>1   #make word length
1205
            if mode.length < 512:
1206
                print 'Reading %i bytes in single block '%(lastLength)
1207
            else:
1208 52 nuubik
                print 'Reading %iK '%(mode.length/512)
1209 2 nuubik
            don.write_command(0x00FF) #  put flash to data read mode
1210 23 nuubik
            try:
1211
                f=open(mode.filename,"wb")  #if this fails no point in reading as there is nowhere to write
1212
                address = mode.offset    # set word address
1213
                don.set_address(address)
1214
                i=0
1215
                while (i<blockCount):
1216
                    don.issue_blk_read()  # request 64K words from current address
1217
                    buf=don.getReturn(65536*2) #Read all words
1218
                    if (i==blockCount-1):  #last block
1219
                        f.write(buf[:lastLength])
1220
                    else:
1221
                        f.write(buf) ## must tuncate the buffer
1222 9 nuubik
                    if mode.v == 1:
1223 23 nuubik
                        print 'Got block %i'%(i+1)
1224 9 nuubik
                    else:
1225
                        sys.stdout.write(".")
1226
                        sys.stdout.flush()
1227 23 nuubik
                    i+=1
1228
                f.close()
1229
            except IOError:
1230
                print "IO Error on file open"
1231 52 nuubik
                don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1232
                don.write_command(0xC6C5)   #clear lock bit
1233
                ret_buf=don.getReturn(2)    #two bytes expected to this command                         
1234 23 nuubik
                sys.exit()
1235
            ##################### end from hw ver 5 readback code  ############################################ 
1236
        else:
1237
            ##################### before hw ver 5 readback code ###############################################
1238
            mode.offset=mode.offset>>1    #make word offset
1239
            mode.length= mode.length>>1   #make word length
1240
            print 'Reading %iK'%(mode.length/512)
1241
            try:
1242
                f=open(mode.filename,"wb")
1243
                don.write_command(0x00FF) #  put flash to data read mode
1244
                address = mode.offset    # set word address
1245
                while 1:
1246
                    if address/(1024*32) != (address-128)/(1024*32):  # get K bytes from words if 512
1247
                        if mode.v == 1:
1248
                            print 'Progress: %iK of %iK'%((address-mode.offset)/512,mode.length/512)
1249
                        else:
1250
                            sys.stdout.write(".")
1251
                            sys.stdout.flush()
1252
                    buf=don.read_data(128,address)  # word count and byte address read 64 words to speed up
1253
                    f.write(buf)
1254
                    #print "from address:",address<<1," ", len(buf)
1255
                    if address+128 >= (mode.offset + mode.length):  # 2+64 estimates the end to end in right place
1256
                        break
1257
                    address = address + 128    #this is word address
1258
                f.close()
1259
                if mode.v == 0:
1260
                    print " "
1261
                print "Readback done!"
1262
            except IOError:
1263
                print "IO Error on file open"
1264 52 nuubik
                don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1265
                don.write_command(0xC6C5)   #clear lock bit
1266
                ret_buf=don.getReturn(2)    #two bytes expected to this command                         
1267 23 nuubik
                sys.exit()
1268
       ##################### end before hw ver 5 readback code  ################################################ 
1269 2 nuubik
    else:
1270
       print "Some of readback parameters missing..."
1271
       print mode.offset,mode.length, mode.filename
1272 52 nuubik
       don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1273
       don.write_command(0xC6C5)   #clear lock bit
1274
       ret_buf=don.getReturn(2)    #two bytes expected to this command                
1275
       sys.exit()
1276
    don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1277
 
1278
 
1279
def psram_read(mode,don):
1280
    if mode.offset!=-1 and mode.length!=-1 and mode.filename!="":
1281
        if mode.version > 5:  #should never be smaller here
1282
            blockCount = (mode.length>>17)+1 #read this many 64K word blocks
1283
            mode.offset=mode.offset>>1    #make word offset
1284
            lastLength = mode.length&0x0001FFFF
1285
            mode.length= mode.length>>1   #make word length
1286
            if mode.length < 512:
1287
                print 'Reading %i bytes in single block '%(lastLength)
1288
                sys.stdout.flush()
1289
            else:
1290
                print 'Reading %iK'%(mode.length/512)
1291
                sys.stdout.flush()
1292
            try:
1293
                f=open(mode.filename,"wb")  #if this fails no point in reading as there is nowhere to write
1294
                address = mode.offset    # set word address
1295
                don.set_address(address)
1296
                i=0
1297
                while (i<blockCount):
1298
                    try:
1299
                        don.issue_blk_read()  # request 64K words from current address
1300
                        buf=don.getReturn(65536*2) #Read all words
1301
                    except SerialPortException:
1302
                        if sys.platform=='win32':
1303
                            print("\nExit due to driver error...")
1304
                            print("Please disconnect dongle and try again... \n")
1305
                            sys.exit()
1306
                        else:
1307
                            print("\nPlease send email to jyrit@artecdesign.ee stating your dongle version")
1308
                            print("disconnect the dongle and try again")
1309
                    if (i==blockCount-1):  #last block
1310
                        f.write(buf[:lastLength])
1311
                    else:
1312
                        f.write(buf) ## must tuncate the buffer
1313
                    if mode.v == 1:
1314
                        print 'Got block %i'%(i+1)
1315
                    else:
1316
                        sys.stdout.write(".")
1317
                        sys.stdout.flush()
1318
                    i+=1
1319
                f.close()
1320
            except IOError:
1321
                print "IO Error on file open"
1322
                don.write_command(0xC6C5)   #clear lock bit
1323
                ret_buf=don.getReturn(2)    #two bytes expected to this command                         
1324
                sys.exit()
1325
        else:
1326
            print "Dongle PSRAM region supported since hw version 8606 on Dongle II boards"
1327
 
1328
       ##################### end before hw ver 5 readback code  ################################################ 
1329
    else:
1330
       print "Some of readback parameters missing..."
1331
       print mode.offset,mode.length, mode.filename
1332
       don.write_command(0xC6C5)   #clear lock bit
1333
       ret_buf=don.getReturn(2)    #two bytes expected to this command                
1334 2 nuubik
       sys.exit()
1335 52 nuubik
 
1336
 
1337
def flash_qry(mode,don):
1338
    buf=don.read_data(4,0x0)  # word count and word address
1339
    don.write_command(0x0050)  #FLASH command clear status register   
1340
    don.write_command(0x0098)  #FLASH command read QRY
1341
    buf=don.read_data(3,0x000010)  # word count and word address
1342
    if ord(buf[0])==0x51 and  ord(buf[2])==0x52 and  ord(buf[4])==0x59:
1343
        buf=don.read_data(2,0x000000)  # word count and word address
1344
        print 'Query  OK, Flash Factory Code is: 0x%02x device: 0x%02x '%(ord(buf[0]),ord(buf[2]))
1345
        buf=don.read_data(2,0x000002)
1346
        print 'lock bit is 0x%02x 0x%02x'%(ord(buf[0]),ord(buf[1]))
1347
    else:
1348
        print "Got bad Flash query data:"
1349
        print 'Query address 0x10 = 0x%02x%02x '%(ord(buf[1]),ord(buf[0]))
1350
        print 'Query address 0x12 = 0x%02x%02x '%(ord(buf[3]),ord(buf[2]))
1351
        print 'Query address 0x14 = 0x%02x%02x '%(ord(buf[5]),ord(buf[4]))
1352
        print "Read byte count:",len(buf)
1353
 
1354
    don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1355
    buf=don.read_data(4,0xff57c0>>1)  # word count and word address
1356 8 nuubik
 
1357 52 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]) )
1358
 
1359
 
1360
def flash_test(mode,don):
1361
        print "FLASH TEST"
1362
        test_status = 1
1363 8 nuubik
        if mode.e == 1:
1364
            #Erase Dongle
1365 9 nuubik
            print "Erasing"
1366 8 nuubik
            don.write_command(0x0060) # 0x0098
1367
            don.write_command(0x00D0) # 0x0098
1368
            don.wait_on_busy()
1369
            don.parse_status()
1370
            endBlock = 31
1371
            startBlock = 0
1372
            i=startBlock
1373
            while i <= endBlock:
1374 9 nuubik
                if mode.v == 1:
1375
                    print 'Erasing block %i '%(i)
1376
                else:
1377
                     sys.stdout.write(".")
1378
                     sys.stdout.flush()
1379 8 nuubik
                don.erase_block(i)
1380
                don.wait_on_busy()
1381
                don.parse_status()   #do this after programming all but uneaven ending
1382 9 nuubik
                i=i+1
1383
            if mode.v == 0: # add CRTL return to dots
1384
                print ""
1385 8 nuubik
        #Do marching one test on data and address
1386
        mode.length= 0   #make word length
1387 52 nuubik
        don.write_command(0x00FF) #  put flash to data read mode
1388
        buf2=don.read_data(1,0)  #read first byte
1389
        if ord(buf2[0]) != 0xFF:
1390
            print "Can't run FLASH TEST on unerased flash first byte is 0x%02x"%(ord(buf2[0]))
1391
            don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1392
            don.write_command(0xC6C5)   #clear lock bit
1393
            ret_buf=don.getReturn(2)    #two bytes expected to this command                     
1394
            sys.exit()
1395 8 nuubik
        try:
1396
            #Marching one test
1397 52 nuubik
            print "Single bit high test on addr and data"
1398 8 nuubik
            #---------------------------------------------------------------------------
1399
            address = 0x100000    # set word address
1400
            data = 0x100000
1401
            while mode.length<20: # last address to test 0x20 0000  
1402
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1403
                don.buffer_write(2,address,buf1)
1404
                don.parse_status()   #do this after programming all but uneaven ending
1405
                don.write_command(0x00FF) #  put flash to data read mode   
1406
                buf2=don.read_data(2,address)  # word count and byte address read 64 words to speed up
1407
                if buf1 != buf2:
1408
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1409
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1410 52 nuubik
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1411
                    print "Data written = 0x%08x"%(data&0xFFFF)
1412
                    print "Test FAIL!!!!!"
1413
                    test_status = 0
1414
                buf2=don.read_data(1,0)  #read first byte
1415
                if ord(buf2[0]) != 0xFF:
1416
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1417
                    print "Test FAIL (Used address line probably const. 0)!"
1418
                    test_status = 0
1419
                    don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1420
                    don.write_command(0xC6C5)   #clear lock bit
1421
                    ret_buf=don.getReturn(2)    #two bytes expected to this command                             
1422
                    sys.exit()
1423 8 nuubik
                address = address >> 1
1424
                if address == 0x2:
1425
                    address = address >> 1  # 0x2 is written and will return zero on read as write new write will fail
1426
                data = data >> 1
1427
                mode.length =  mode.length + 1
1428 52 nuubik
 
1429 8 nuubik
            #-----------------------------------------------------------------------
1430
            #Marching zero test
1431 52 nuubik
            print "Single bit low test on addr and data"
1432 8 nuubik
            address = 0xFFEFFFFF    # set word address
1433 52 nuubik
            data = 0xFFEFFFFF
1434 8 nuubik
            while mode.length<18: # last address to test 0x20 0000  
1435
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1436
                don.buffer_write(2,address,buf1)
1437
                don.parse_status()   #do this after programming all but uneaven ending
1438
                don.write_command(0x00FF) #  put flash to data read mode   
1439
                buf2=don.read_data(2,address&0x1FFFFF)  # word count and byte address read 64 words to speed up
1440
                if buf1 != buf2:
1441
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1442
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1443 52 nuubik
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1444
                    print "Data written = 0x%08x"%(data&0xFFFF)
1445
                    print "Test FAIL!!!!!"
1446 8 nuubik
                    print "Test FAIL!!!!!"
1447 52 nuubik
                    test_status = 0
1448
                buf2=don.read_data(1,0x1FFFFF)  #read first byte
1449
                if ord(buf2[0]) != 0xFF:
1450
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1451
                    print "Test FAIL (At used address line const. 1 or lines bonded)!"
1452
                    test_status = 0
1453
                    don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1454
                    don.write_command(0xC6C5)   #clear lock bit
1455
                    ret_buf=don.getReturn(2)    #two bytes expected to this command                             
1456
                    sys.exit()
1457 8 nuubik
                address = (address >> 1)|0xFF000000
1458
                data = data >> 1
1459
                mode.length =  mode.length + 1
1460
            if mode.b == 1:
1461
                #Erase Dongle
1462 9 nuubik
                print "Erasing"
1463 8 nuubik
                don.write_command(0x0060) # 0x0098
1464
                don.write_command(0x00D0) # 0x0098
1465
                don.wait_on_busy()
1466
                don.parse_status()
1467
                endBlock = 31
1468
                startBlock = 0
1469
                i=startBlock
1470
                while i <= endBlock:
1471 9 nuubik
                    if mode.v == 1:
1472
                        print 'Blanking block %i '%(i)
1473
                    else:
1474
                        sys.stdout.write(".")
1475
                        sys.stdout.flush()
1476 8 nuubik
                    don.erase_block(i)
1477 23 nuubik
                    if mode.version < 5:
1478
                        don.wait_on_busy()
1479
                        don.parse_status()   #do this after programming all but uneaven ending
1480 9 nuubik
                    i=i+1
1481
                if mode.v == 0:
1482
                    print " "
1483 52 nuubik
            if  test_status == 1:
1484
                print "Test SUCCESSFUL!"
1485
            don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1486
            don.write_command(0xC6C5)   #clear lock bit
1487
            ret_buf=don.getReturn(2)    #two bytes expected to this command                     
1488 9 nuubik
            sys.exit()
1489 8 nuubik
        except IOError:
1490
            print "IO Error on file open"
1491 52 nuubik
            don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1492
            don.write_command(0xC6C5)   #clear lock bit
1493
            ret_buf=don.getReturn(2)    #two bytes expected to this command                     
1494 8 nuubik
            sys.exit()
1495 52 nuubik
        don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1496
 
1497
def psram_test(mode,don):
1498
        print "PSRAM TEST"
1499
        test_status = 1
1500
        #Do marching one test on data and address
1501
        mode.length= 0   #make word length
1502
        try:
1503
            print "Single bit high test on addr and data"
1504
            #---------------------------------------------------------------------------
1505
            address = 0x100000    # set word address
1506
            data = 0x100000
1507
            don.buffer_write_ram(0,"\xFF\xFF")  #init PSRAM
1508
            while mode.length<20: # last address to test 0x20 0000  
1509
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1510
                don.buffer_write_ram(address,buf1)
1511
                buf2=don.read_data(2,address)  # word count and byte address read 64 words to speed up
1512
                if buf1 != buf2:
1513
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1514
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1515
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1516
                    print "Data written = 0x%08x"%(data&0xFFFF)
1517
                    print "Test due to data FAIL!!!!!"
1518
                    test_status=0
1519
                buf2=don.read_data(1,0)  #read first byte
1520
                if ord(buf2[0]) != 0xFF:
1521
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1522
                    print "Test FAIL (At least one address line const. 0)!!!!!"
1523
                    test_status=0
1524
                    don.write_command(0xC6C5)   #clear lock bit
1525
                    ret_buf=don.getReturn(2)    #two bytes expected to this command                             
1526
                    sys.exit()
1527
                address = address >> 1
1528
                if address == 0x2:
1529
                    address = address >> 1  # 0x2 is written and will return zero on read as write new write will fail
1530
                data = data >> 1
1531
                mode.length =  mode.length + 1
1532 8 nuubik
 
1533 52 nuubik
            #-----------------------------------------------------------------------
1534
            #Marching zero test
1535
            print "Single bit low test on addr and data"
1536
            address = 0xFFEFFFFF    # set word address
1537
            data = 0xFFEFFFFF
1538
            while mode.length<18: # last address to test 0x20 0000  
1539
                buf1=pack('BBBB', (0x000000FF&data),(0x0000FF00&data)>>8 ,(0x00FF0000&data)>>16 ,(0xFF0000&data)>>24 )
1540
                don.buffer_write_ram(address&0x1FFFFF,buf1)
1541
                buf2=don.read_data(2,address&0x1FFFFF)  # word count and byte address read 64 words to speed up
1542
                if buf1 != buf2:
1543
                    print 'IN  %02x %02x %02x %02x '%(ord(buf1[3]), ord(buf1[2]),ord(buf1[1]), ord(buf1[0]))
1544
                    print 'OUT %02x %02x %02x %02x '%(ord(buf2[3]), ord(buf2[2]),ord(buf2[1]), ord(buf2[0]))
1545
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1546
                    print "Data written = 0x%08x"%(data&0xFFFF)
1547
                    print "Test FAIL!!!!!"
1548
                    test_status=0
1549
                buf2=don.read_data(1,0x1FFFFF)  #read first byte
1550
                if ord(buf2[0]) != 0xFF:
1551
                    print "Address used = 0x%08x"%(address&0x1FFFFF)
1552
                    print "Test FAIL (At used address least two address lines bonded or const. 1)!"
1553
                    test_status=0
1554
                    don.write_command(0xC6C5)   #clear lock bit
1555
                    ret_buf=don.getReturn(2)    #two bytes expected to this command                             
1556
                    sys.exit()
1557
                address = (address >> 1)|0xFF000000
1558
                data = data >> 1
1559
                mode.length =  mode.length + 1
1560
            if test_status==1:
1561
                print "Test SUCCESSFUL!"
1562
            don.write_command(0xC6C5)   #clear lock bit
1563
            ret_buf=don.getReturn(2)    #two bytes expected to this command                         
1564
            sys.exit()
1565
        except IOError:
1566
            print "IO Error on file open"
1567
            don.write_command(0xC6C5)   #clear lock bit
1568
            ret_buf=don.getReturn(2)    #two bytes expected to this command                     
1569
            sys.exit()
1570
 
1571
def flash_erase(mode,don):
1572 9 nuubik
            #Erase Dongle
1573
            print "Erasing all"
1574
            don.write_command(0x0060) # 0x0098
1575
            don.write_command(0x00D0) # 0x0098
1576 23 nuubik
            if mode.version < 5:
1577
                don.wait_on_busy()
1578
                don.parse_status()
1579 9 nuubik
            endBlock = 31
1580
            startBlock = 0
1581
            i=startBlock
1582
            while i <= endBlock:
1583
                if mode.v == 1:
1584
                    print 'Erasing block %i '%(i)
1585
                else:
1586
                     sys.stdout.write(".")
1587
                     sys.stdout.flush()
1588
                don.erase_block(i)
1589 23 nuubik
                if mode.version < 5:
1590
                    don.wait_on_busy()
1591
                    don.parse_status()   #do this after programming all but uneaven ending
1592 9 nuubik
                i=i+1
1593
            if mode.v == 0: # add CRTL return to dots
1594
                print ""
1595 23 nuubik
            if mode.version >= 5:
1596
                print "Waiting for buffers to empty"
1597
                don.wait_on_busy()
1598
                don.parse_status()   #do this after programming all but uneaven ending
1599 52 nuubik
            print "Erase done."
1600
            don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1601
def flash_looptest(mode,don):
1602 23 nuubik
            print "Status Loop test"
1603
            i=1024
1604
            startTime = time.clock()
1605
            while i > 0:
1606 52 nuubik
                if i%128==0:
1607
                    sys.stdout.write(".")
1608
                    sys.stdout.flush()
1609 23 nuubik
                don.wait_on_busy()
1610
                don.parse_status()   #do this after programming all but uneaven ending
1611
                i=i-1
1612 52 nuubik
            #if sys.platform=='win32':
1613
            endTime = (time.clock()-startTime)/1024.0
1614
            print "\nSystem round delay is %4f ms"%(endTime*1000.0)
1615
            sys.stdout.flush()
1616
            don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1617
 
1618
################## Main program #########################
1619
 
1620
 
1621
last_ops = 0
1622
mode = DongleMode()
1623
# PARSE ARGUMENTS 
1624
for arg in sys.argv:
1625
    if len(sys.argv) == 1: # if no arguments display help
1626
       #usage(sys.argv[0])
1627
       usage("dongle.py")
1628
       sys.exit()
1629
    if arg in ("-h","--help","/help","/h"):
1630
        #usage(sys.argv[0])
1631
        usage("dongle.py")
1632
        sys.exit()
1633
    if arg in ("-c"):
1634
        last_ops = sys.argv.index(arg) + 1  #if remains last set of options from here start ordered strings
1635
        i = sys.argv.index(arg)
1636
        print "Opening port: "+sys.argv[i+1]
1637
        mode.portname = sys.argv[i+1]   # next element after -c open port for usage
1638
    if arg[0]=="-" and arg[1]!="c": # if other opptions
1639
        # parse all options in this
1640
        last_ops = sys.argv.index(arg)  #if remains last set of options from here start ordered strings
1641
        ops = arg[1:]# get all besides the - sign
1642
        for op in ops:
1643
            if op=="q":
1644
                mode.q = 1
1645
            if op=="v":
1646
                mode.v = 1
1647
            if op=="f":
1648
                mode.f = 1
1649
            if op=="d":
1650
                mode.d = 1
1651
            if op=="r":
1652
                mode.r = 1
1653
            if op=="t":
1654
                mode.t = 1
1655
            if op=="e":
1656
                mode.e = 1
1657
            if op=="b":
1658
                mode.b = 1
1659
            if op=="l":
1660
                mode.l = 1
1661
            if op=="p":
1662
                mode.p = 0
1663
            if op=="P":
1664
                mode.p = 1
1665
            if op=="u":
1666
                mode.u = 1
1667
    else:
1668
        i = sys.argv.index(arg)
1669
        if i ==  last_ops + 1:
1670
            if mode.r==1:
1671
                mode.offset=mode.convParamStr(arg)
1672
            else:
1673
                mode.filename=arg
1674
        if i ==  last_ops + 2:
1675
            if mode.r==1:
1676
                mode.length=mode.convParamStr(arg)
1677
            else:
1678
                if arg.find("EOF")>-1:
1679
                    print "Found EOF marker"
1680
                    mode.eof = 1    #the file is to be written to the end of 4M area
1681
                    mode.address = 0
1682
                else:
1683
                    mode.address=mode.convParamStr(arg)
1684
 
1685
        if i ==  last_ops + 3:
1686
            if mode.r==1:
1687
                mode.filename=arg
1688
            else:
1689
                print "Too many parameters provided"
1690
                sys.exit()
1691
        if i >  last_ops + 3:
1692
             print "Too many parameters provided"
1693
             sys.exit()
1694
 
1695
# END PARSE ARGUMENTS             
1696
 
1697
if mode.portname=="":
1698
    print "No port name given see -h for help"
1699
    sys.exit()
1700
else:
1701
    # test PC speed to find sutable delay for linux driver
1702
    # to get 250 us 
1703
    mytime = time.clock()
1704
    n = 0
1705
    while (n < 100000):
1706
        n += 1;
1707
    k10Time = time.clock() - mytime   # time per 10000 while cycles
1708
    wait = k10Time/100000.0     # time per while cycle
1709
    wait = (0.00025/wait) * 1.20   # count for 250us + safe margin
1710
    # ok done
1711
    reopened = 0
1712
 
1713
 
1714
    if sys.platform=='win32':
1715
        don  = Dongle(mode.portname,256000,6000)
1716
    elif sys.platform=='linux2':
1717
        don  = Dongle(mode.portname,230400,6000)
1718
        #don.tty.cts()
1719
    elif sys.platform=='darwin':
1720
        don  = Dongle(mode.portname,230400,6000)
1721
        #don.tty.cts()
1722
    else:
1723
        sys.exit('Sorry, no implementation for this platform yet')
1724
 
1725
 
1726
    don.tty.wait = wait
1727
    while 1:
1728
        #don.write_command(0x0050)    #FLASH command clear status register  
1729
        don.write_command(0x00C5)            #send dongle check internal command
1730
        don_ret=don.testReturn(2)
1731
        if don_ret==2:
1732
            break
1733
        if reopened == 3:
1734
             print 'Dongle connected, but does not communicate'
1735
             sys.exit()
1736
        reopened = reopened + 1
1737
        # reopen and do new cycle
1738
        if sys.platform=='win32':
1739
            don  = Dongle(mode.portname,256000,6000)
1740
        elif sys.platform=='linux2':
1741
            don  = Dongle(mode.portname,230400,6000)
1742
            #self.tty.cts()
1743
        elif sys.platform=='darwin':
1744
            don  = Dongle(mode.portname,230400,6000)
1745
            #self.tty.cts()
1746
        else:
1747
            sys.exit('Sorry, no implementation for this platform yet')
1748
        don.tty.wait = wait
1749
 
1750
    buf=don.getReturn(2)  # two bytes expected to this command
1751
    if ord(buf[1])==0x32 and  ord(buf[0])==0x10:
1752
        print "Dongle OK"
1753
    else:
1754
        print 'Dongle returned on open: %02x %02x '%(ord(buf[1]), ord(buf[0]))
1755
    don.write_command(0x01C5)            #try getting dongle HW ver (works since 05 before that returns 0x3210)
1756
    buf=don.getReturn(2)  # two bytes expected to this command
1757
    if ord(buf[1])==0x86 and  ord(buf[0])>0x04:
1758
        mode.version = ord(buf[0])
1759
        don.mode = mode
1760
        print 'Dongle HW version code is  %02x %02x'%(ord(buf[1]), ord(buf[0]))
1761
 
1762
        print 'Dongle version is  %x'%(mode.version)
1763
    else:
1764
        don.mode = mode
1765
        print 'Dongle HW version code is smaller than 05 some features have been improved on'
1766
        print 'HW code and Quartus FPGA binary file are available at:'
1767
        print 'http://www.opencores.org/projects.cgi/web/usb_dongle_fpga/overview'
1768
        print 'Programming is possible with Altera Quartus WE and BYTEBLASTER II cable or'
1769
        print 'compatible clone like X-Blaster http://www.customcircuitsolutions.com/cable.html'
1770
 
1771
    if mode.version>0x19:   # Dongle II versions
1772
        print 'Other status info:'
1773
        if mode.p == 0:
1774
            don.write_command(0xC3C5)  # ldev_present_n set to 0   (is active low for thincan)       
1775
            buf_dc = don.getReturn(2)  # two bytes expected to this command    
1776
        else:
1777
            don.write_command(0xC4C5)  # ldev_present_n set to 1 (is active low for thincan) 
1778
            buf_dc = don.getReturn(2)  # two bytes expected to this command                
1779
        if mode.u == 1:
1780
            don.write_command(0xC2C5)  # force USB prog mode signals to conf memory  
1781
            #buf_dc = don.getReturn(2)  # two bytes expected to this command                
1782
            sys.exit()
1783
        don.write_command(0x02C5)  #try getting PCB ver (works since 06 before that returns 0x3210)
1784
        buf=don.getReturn(2)  # two bytes expected to this command
1785
        i_temp = 0
1786
        i_temp = (ord(buf[1])<<8)|ord(buf[0])
1787
        print 'Dongle PCB version code is AD 67075%05i'%( i_temp )
1788
        don.write_command(0x03C5)            #try getting mode switch setting (works since 06 before that returns 0x3210)
1789
        buf=don.getReturn(2)  # two bytes expected to this command
1790
        mode_reg = ord(buf[0])
1791
        print 'Dongle memory region  %02x'%(mode_reg)
1792
        if ord(buf[1])==0x00:
1793
            if ord(buf[0]) > 3:
1794
                print 'PSRAM region selected'
1795
            else:
1796
                print 'FLASH region selected'
1797
            mode.region = mode_reg  #set the region for PSRAM support                            
1798
    if mode.region>3:
1799
        pass
1800
        #print 'Initialize psram on region %i'%(mode.region)
1801
        #PSRAM mode init
1802
    else:
1803
        #print 'Initialize flash on region %i'%(mode.region)
1804
        don.write_command(0x0050)    #FLASH command clear status register
1805
        don.write_command(0x00FF) # 0x0098  --set flash to read array mode
1806
        #Flash mode init
1807
 
1808
#Lock LPC out from memory interface        
1809
don.write_command(0xC5C5)   #set lock bit up
1810
ret_buf=don.getReturn(2)    #two bytes expected to this command
1811
 
1812
if mode.q == 1:   # perform a query from dongle  
1813
    if mode.region<4:
1814
        flash_qry(mode,don)
1815
    else:
1816
        print "Query only supported on flash regions (to change region turn the Mode switch):"
1817
        print "FLASH regions are regions from 0 to 3"
1818
 
1819
 
1820
if mode.filename!="" and mode.address!=-1:   #Dongle write command given
1821
    if mode.region<4:
1822
        print "Flash write called"
1823
        flash_write(mode,don)
1824
    else:
1825
        print "PSRAM write called"
1826
        psram_write(mode,don)
1827
 
1828
if mode.r == 1:   # perform a readback
1829
    if mode.region<4:
1830
        print "Flash read called"
1831
        flash_read(mode,don)
1832
    else:
1833
        print "PSRAM read called"
1834
        psram_read(mode,don)
1835
 
1836
if mode.t == 1:   # perform dongle test
1837
    if mode.region<4:
1838
        flash_test(mode,don)
1839
    else:
1840
        psram_test(mode,don)
1841
if mode.e == 1:   # perform dongle erase
1842
    if mode.region<4:
1843
        flash_erase(mode,don)
1844
    else:
1845
        print "Erase is supported on flash regions (to change region turn the Mode switch):"
1846
        print "FLASH regions are regions from 0 to 3"
1847
 
1848
if mode.l == 1:   # perform dongle test  
1849
    if mode.region<4:
1850
        flash_looptest(mode,don)
1851
    else:
1852
        print "Looptest is supported on flash regions (to change region turn the Mode switch):"
1853
        print "FLASH regions are regions from 0 to 3"
1854
 
1855 2 nuubik
##########################################################
1856 52 nuubik
 
1857
#Unlock memory interface        
1858
don.write_command(0xC6C5)   #clear lock bit
1859
ret_buf=don.getReturn(2)    #two bytes expected to this command
1860
sys.exit()
1861
 
1862
 

powered by: WebSVN 2.1.0

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