Added a buggy but minimally functional FTDI emulator.
[goodfet] / client / goodfet.bsl
1 #!/usr/bin/env python
2 # Serial Bootstrap Loader software for the MSP430 embedded proccessor.
3 #
4 # (C) 2001-2003 Chris Liechti <cliechti@gmx.net>
5 # this is distributed under a free software license, see license-bsl.txt
6 #
7 # fixes from Colin Domoney
8 #
9 # based on the application note slas96b.pdf from Texas Instruments, Inc.,
10 # Volker Rzehak
11 # additional infos from slaa089a.pdf
12
13 # Forked by Travis Goodspeed <travis at tnbelt.com> for use with the GoodFET
14 # JTAG programmer.
15
16 import sys, time, string, cStringIO, struct
17 sys.path.append("/usr/lib/tinyos")
18 import serial, os, glob
19
20 #forked from TinyOS Telos version.
21 VERSION = string.split("Revision: 1.39-goodfet-8 ")[1] 
22
23 DEBUG = 0                                       #disable debug messages by default
24
25 #copy of the patch file provided by TI
26 #this part is (C) by Texas Instruments
27 PATCH = """@0220
28 31 40 1A 02 09 43 B0 12 2A 0E B0 12 BA 0D 55 42
29 0B 02 75 90 12 00 1F 24 B0 12 BA 02 55 42 0B 02
30 75 90 16 00 16 24 75 90 14 00 11 24 B0 12 84 0E
31 06 3C B0 12 94 0E 03 3C 21 53 B0 12 8C 0E B2 40
32 10 A5 2C 01 B2 40 00 A5 28 01 30 40 42 0C 30 40
33 76 0D 30 40 AC 0C 16 42 0E 02 17 42 10 02 E2 B2
34 08 02 14 24 B0 12 10 0F 36 90 00 10 06 28 B2 40
35 00 A5 2C 01 B2 40 40 A5 28 01 D6 42 06 02 00 00
36 16 53 17 83 EF 23 B0 12 BA 02 D3 3F B0 12 10 0F
37 17 83 FC 23 B0 12 BA 02 D0 3F 18 42 12 02 B0 12
38 10 0F D2 42 06 02 12 02 B0 12 10 0F D2 42 06 02
39 13 02 38 E3 18 92 12 02 BF 23 E2 B3 08 02 BC 23
40 30 41
41 q
42 """
43
44 #These BSL's are (C) by TI. They come with the application note slaa089a
45 F1X_BSL = """@0220
46 24 02 2E 02 31 40 20 02 2B D2 C0 43 EA FF 32 C2
47 F2 C0 32 00 00 00 B2 40 80 5A 20 01 F2 40 85 00
48 57 00 F2 40 80 00 56 00 E2 D3 21 00 E2 D3 22 00
49 E2 C3 26 00 E2 C2 2A 00 E2 C2 2E 00 B2 40 10 A5
50 2C 01 B2 40 00 A5 28 01 3B C0 3A 00 B0 12 D6 04
51 82 43 12 02 09 43 36 40 0A 02 37 42 B0 12 AC 05
52 C6 4C 00 00 16 53 17 83 F9 23 D2 92 0C 02 0D 02
53 28 20 55 42 0B 02 75 90 12 00 80 24 75 90 10 00
54 6D 24 B0 12 9C 04 55 42 0B 02 75 90 18 00 31 24
55 75 90 1E 00 B8 24 75 90 20 00 17 24 2B B2 11 24
56 75 90 16 00 22 24 75 90 14 00 B3 24 75 90 1A 00
57 18 24 75 90 1C 00 45 24 04 3C B0 12 36 05 BE 3F
58 21 53 B0 12 3C 05 BA 3F 03 43 B0 12 36 05 D2 42
59 0E 02 56 00 D2 42 0F 02 57 00 D2 42 10 02 16 02
60 AD 3F B0 12 36 05 10 42 0E 02 16 42 0E 02 15 43
61 07 3C 36 40 FE FF B2 40 06 A5 10 02 35 40 0C 00
62 B2 40 00 A5 2C 01 92 42 10 02 28 01 B6 43 00 00
63 92 B3 2C 01 FD 23 15 83 F3 23 36 90 FE FF CD 27
64 37 40 80 00 36 F0 80 FF 36 90 00 11 0E 28 07 57
65 36 F0 00 FF 36 90 00 12 08 28 07 57 36 F0 00 FE
66 04 3C 16 42 0E 02 17 42 10 02 35 43 75 96 03 20
67 17 83 FC 23 B2 3F 82 46 00 02 B3 3F 36 40 E0 FF
68 37 40 20 00 B0 12 AC 05 7C 96 01 24 2B D3 17 83
69 F9 23 2B C2 B0 12 9C 04 2B D2 9F 3F 16 42 0E 02
70 17 42 10 02 2B B2 38 24 3B D0 10 00 B0 12 AC 05
71 36 90 00 10 06 2C 36 90 00 01 09 2C C6 4C 00 00
72 25 3C B2 40 00 A5 2C 01 B2 40 40 A5 28 01 16 B3
73 03 20 C2 4C 14 02 1A 3C C2 4C 15 02 86 9A FD FF
74 08 24 2B D3 3B B0 20 00 04 20 3B D0 20 00 82 46
75 00 02 36 90 01 02 04 28 3B D2 3B B0 10 00 02 24
76 3B C0 32 00 1A 42 14 02 86 4A FF FF 16 53 17 83
77 CD 23 B0 12 9C 04 61 3F B0 12 AC 05 17 83 FC 23
78 B0 12 9C 04 5E 3F B2 40 F0 0F 0E 02 B2 40 10 00
79 10 02 B2 40 80 00 0A 02 D2 42 10 02 0C 02 D2 42
80 10 02 0D 02 82 43 12 02 09 43 36 40 0A 02 27 42
81 7C 46 B0 12 40 05 17 83 FB 23 16 42 0E 02 17 42
82 10 02 36 90 00 01 0A 28 B2 46 14 02 5C 42 14 02
83 B0 12 40 05 17 83 5C 42 15 02 01 3C 7C 46 B0 12
84 40 05 17 83 EE 23 B2 E3 12 02 5C 42 12 02 B0 12
85 40 05 5C 42 13 02 B0 12 40 05 E0 3E 18 42 12 02
86 B0 12 AC 05 C2 4C 12 02 B0 12 AC 05 C2 4C 13 02
87 38 E3 3B B2 0A 24 86 9A FE FF 07 24 3B B0 20 00
88 04 20 16 53 82 46 00 02 2B D3 18 92 12 02 08 23
89 2B B3 06 23 30 41 E2 B2 28 00 FD 27 E2 B2 28 00
90 FD 23 B2 40 24 02 60 01 E2 B2 28 00 FD 27 15 42
91 70 01 05 11 05 11 05 11 82 45 02 02 05 11 82 45
92 04 02 B2 80 1E 00 04 02 57 42 16 02 37 80 03 00
93 05 11 05 11 17 53 FD 23 35 50 40 A5 82 45 2A 01
94 35 42 B2 40 24 02 60 01 92 92 70 01 02 02 FC 2F
95 15 83 F7 23 09 43 7C 40 90 00 02 3C 7C 40 A0 00
96 C2 43 07 02 C9 EC 12 02 19 E3 1B C3 55 42 07 02
97 55 45 56 05 00 55 0C 2E 2E 2E 2E 2E 2E 2E 2E 1A
98 34 34 92 42 70 01 72 01 B2 50 0C 00 72 01 07 3C
99 1B B3 0B 20 82 43 62 01 92 B3 62 01 FD 27 E2 C3
100 21 00 0A 3C 4C 11 F6 2B 1B E3 82 43 62 01 92 B3
101 62 01 FD 27 E2 D3 21 00 92 52 02 02 72 01 D2 53
102 07 02 F0 90 0C 00 61 FC D1 23 30 41 C2 43 09 02
103 1B C3 55 42 09 02 55 45 BC 05 00 55 0C 56 56 56
104 56 56 56 56 56 36 76 00 E2 B2 28 00 FD 23 92 42
105 70 01 72 01 92 52 04 02 72 01 82 43 62 01 92 B3
106 62 01 FD 27 E2 B2 28 00 1E 28 2B D3 1C 3C 4C 10
107 1A 3C 82 43 62 01 92 B3 62 01 FD 27 E2 B2 28 00
108 01 28 1B E3 1B B3 01 24 2B D3 C9 EC 12 02 19 E3
109 0A 3C 82 43 62 01 92 B3 62 01 FD 27 E2 B2 28 00
110 E6 2B 4C 10 1B E3 92 52 02 02 72 01 D2 53 09 02
111 C0 3F 82 43 62 01 92 B3 62 01 FD 27 E2 B2 28 00
112 01 2C 2B D3 30 41
113 q
114 """
115
116 F4X_BSL = """@0220
117 24 02 2E 02 31 40 20 02 2B D2 C0 43 EA FF 32 C2
118 F2 C0 32 00 00 00 B2 40 80 5A 20 01 32 D0 40 00
119 C2 43 50 00 F2 40 98 00 51 00 F2 C0 80 00 52 00
120 D2 D3 21 00 D2 D3 22 00 D2 C3 26 00 E2 C3 22 00
121 E2 C3 26 00 B2 40 10 A5 2C 01 B2 40 00 A5 28 01
122 3B C0 3A 00 B0 12 DE 04 82 43 12 02 09 43 36 40
123 0A 02 37 42 B0 12 B4 05 C6 4C 00 00 16 53 17 83
124 F9 23 D2 92 0C 02 0D 02 28 20 55 42 0B 02 75 90
125 12 00 80 24 75 90 10 00 6D 24 B0 12 A4 04 55 42
126 0B 02 75 90 18 00 31 24 75 90 1E 00 B8 24 75 90
127 20 00 17 24 2B B2 11 24 75 90 16 00 22 24 75 90
128 14 00 B3 24 75 90 1A 00 18 24 75 90 1C 00 45 24
129 04 3C B0 12 3E 05 BE 3F 21 53 B0 12 44 05 BA 3F
130 03 43 B0 12 3E 05 D2 42 0E 02 50 00 D2 42 0F 02
131 51 00 D2 42 10 02 16 02 AD 3F B0 12 3E 05 10 42
132 0E 02 16 42 0E 02 15 43 07 3C 36 40 FE FF B2 40
133 06 A5 10 02 35 40 0C 00 B2 40 00 A5 2C 01 92 42
134 10 02 28 01 B6 43 00 00 92 B3 2C 01 FD 23 15 83
135 F3 23 36 90 FE FF CD 27 37 40 80 00 36 F0 80 FF
136 36 90 00 11 0E 28 07 57 36 F0 00 FF 36 90 00 12
137 08 28 07 57 36 F0 00 FE 04 3C 16 42 0E 02 17 42
138 10 02 35 43 75 96 03 20 17 83 FC 23 B2 3F 82 46
139 00 02 B3 3F 36 40 E0 FF 37 40 20 00 B0 12 B4 05
140 7C 96 01 24 2B D3 17 83 F9 23 2B C2 B0 12 A4 04
141 2B D2 9F 3F 16 42 0E 02 17 42 10 02 2B B2 38 24
142 3B D0 10 00 B0 12 B4 05 36 90 00 10 06 2C 36 90
143 00 01 09 2C C6 4C 00 00 25 3C B2 40 00 A5 2C 01
144 B2 40 40 A5 28 01 16 B3 03 20 C2 4C 14 02 1A 3C
145 C2 4C 15 02 86 9A FD FF 08 24 2B D3 3B B0 20 00
146 04 20 3B D0 20 00 82 46 00 02 36 90 01 02 04 28
147 3B D2 3B B0 10 00 02 24 3B C0 32 00 1A 42 14 02
148 86 4A FF FF 16 53 17 83 CD 23 B0 12 A4 04 61 3F
149 B0 12 B4 05 17 83 FC 23 B0 12 A4 04 5E 3F B2 40
150 F0 0F 0E 02 B2 40 10 00 10 02 B2 40 80 00 0A 02
151 D2 42 10 02 0C 02 D2 42 10 02 0D 02 82 43 12 02
152 09 43 36 40 0A 02 27 42 7C 46 B0 12 48 05 17 83
153 FB 23 16 42 0E 02 17 42 10 02 36 90 00 01 0A 28
154 B2 46 14 02 5C 42 14 02 B0 12 48 05 17 83 5C 42
155 15 02 01 3C 7C 46 B0 12 48 05 17 83 EE 23 B2 E3
156 12 02 5C 42 12 02 B0 12 48 05 5C 42 13 02 B0 12
157 48 05 E0 3E 18 42 12 02 B0 12 B4 05 C2 4C 12 02
158 B0 12 B4 05 C2 4C 13 02 38 E3 3B B2 0A 24 86 9A
159 FE FF 07 24 3B B0 20 00 04 20 16 53 82 46 00 02
160 2B D3 18 92 12 02 08 23 2B B3 06 23 30 41 E2 B3
161 20 00 FD 27 E2 B3 20 00 FD 23 B2 40 24 02 60 01
162 E2 B3 20 00 FD 27 15 42 70 01 05 11 05 11 05 11
163 82 45 02 02 05 11 82 45 04 02 B2 80 1E 00 04 02
164 57 42 16 02 37 80 03 00 05 11 05 11 17 53 FD 23
165 35 50 40 A5 82 45 2A 01 35 42 B2 40 24 02 60 01
166 92 92 70 01 02 02 FC 2F 15 83 F7 23 09 43 7C 40
167 90 00 02 3C 7C 40 A0 00 C2 43 07 02 C9 EC 12 02
168 19 E3 1B C3 55 42 07 02 55 45 5E 05 00 55 0C 2E
169 2E 2E 2E 2E 2E 2E 2E 1A 34 34 92 42 70 01 72 01
170 B2 50 0C 00 72 01 07 3C 1B B3 0B 20 82 43 62 01
171 92 B3 62 01 FD 27 D2 C3 21 00 0A 3C 4C 11 F6 2B
172 1B E3 82 43 62 01 92 B3 62 01 FD 27 D2 D3 21 00
173 92 52 02 02 72 01 D2 53 07 02 F0 90 0C 00 59 FC
174 D1 23 30 41 C2 43 09 02 1B C3 55 42 09 02 55 45
175 C4 05 00 55 0C 56 56 56 56 56 56 56 56 36 76 00
176 E2 B3 20 00 FD 23 92 42 70 01 72 01 92 52 04 02
177 72 01 82 43 62 01 92 B3 62 01 FD 27 E2 B3 20 00
178 1E 28 2B D3 1C 3C 4C 10 1A 3C 82 43 62 01 92 B3
179 62 01 FD 27 E2 B3 20 00 01 28 1B E3 1B B3 01 24
180 2B D3 C9 EC 12 02 19 E3 0A 3C 82 43 62 01 92 B3
181 62 01 FD 27 E2 B3 20 00 E6 2B 4C 10 1B E3 92 52
182 02 02 72 01 D2 53 09 02 C0 3F 82 43 62 01 92 B3
183 62 01 FD 27 E2 B3 20 00 01 2C 2B D3 30 41
184 q
185 """
186
187 #cpu types for "change baudrate"
188 #use strings as ID so that they can be used in outputs too
189 F1x                     = "F1x family"
190 F2x                     = "F2x family"
191 F4x                     = "F4x family"
192
193 #known device list
194 deviceids = {
195     0xf149: F1x,
196     0xf16c: F1x, #for GoodFET10 to '20
197     0xf112: F1x,
198     0xf413: F4x,
199     0xf123: F1x,
200     0xf449: F4x,
201     0x1232: F1x,
202     0xf26f: F2x, #for GoodFET20
203     0xf227: F2x, #for GoodFET30
204 }
205
206 #GoodFET firmware
207 firmware = {
208     0xf16c: "http://goodfet.sourceforge.net/dist/msp430x1612.hex",
209     0xf26f: "http://goodfet.sourceforge.net/dist/msp430x2618.hex",
210     0xf227: "http://goodfet.sourceforge.net/dist/msp430x2274.hex"
211 }
212
213 class BSLException(Exception):
214     pass
215
216 class LowLevel:
217     "lowlevel communication"
218     #Constants
219     MODE_SSP                = 0
220     MODE_BSL                = 1
221
222     BSL_SYNC                = 0x80
223     BSL_TXPWORD             = 0x10
224     BSL_TXBLK               = 0x12 #Transmit block to boot loader
225     BSL_RXBLK               = 0x14 #Receive  block from boot loader
226     BSL_ERASE               = 0x16 #Erase one segment
227     BSL_MERAS               = 0x18 #Erase complete FLASH memory
228     BSL_CHANGEBAUD          = 0x20 #Change baudrate
229     BSL_LOADPC              = 0x1A #Load PC and start execution
230     BSL_TXVERSION           = 0x1E #Get BSL version
231
232     #Upper limit of address range that might be modified by
233     #"BSL checksum bug".
234     BSL_CRITICAL_ADDR       = 0x0A00
235
236     #Header Definitions
237     CMD_FAILED              = 0x70
238     DATA_FRAME              = 0x80
239     DATA_ACK                = 0x90
240     DATA_NAK                = 0xA0
241
242     QUERY_POLL              = 0xB0
243     QUERY_RESPONSE          = 0x50
244
245     OPEN_CONNECTION         = 0xC0
246     ACK_CONNECTION          = 0x40
247
248     DEFAULT_TIMEOUT         =   1
249     DEFAULT_PROLONG         =  10
250     MAX_FRAME_SIZE          = 256
251     MAX_DATA_BYTES          = 250
252     MAX_DATA_WORDS          = 125
253
254     MAX_FRAME_COUNT         = 16
255
256     #Error messages
257     ERR_COM                 = "Unspecific error"
258     ERR_RX_NAK              = "NAK received (wrong password?)"
259     #ERR_CMD_NOT_COMPLETED   = "Command did not send ACK: indicates that it didn't complete correctly"
260     ERR_CMD_FAILED          = "Command failed, is not defined or is not allowed"
261     ERR_BSL_SYNC            = "Bootstrap loader synchronization error"
262     ERR_FRAME_NUMBER        = "Frame sequence number error."
263     
264     z1 = 0;
265     
266     def calcChecksum(self, data, length):
267         """Calculates a checksum of "data"."""
268         checksum = 0
269
270         for i in range(length/2):
271             checksum = checksum ^ (ord(data[i*2]) | (ord(data[i*2+1]) << 8))    #xor-ing
272         return 0xffff & (checksum ^ 0xffff)         #inverting
273
274     def __init__(self, aTimeout = None, aProlongFactor = None):
275         """init bsl object, don't connect yet"""
276         if aTimeout is None:
277             self.timeout = self.DEFAULT_TIMEOUT
278         else:
279             self.timeout = aTimeout
280         if aProlongFactor is None:
281             self.prolongFactor = self.DEFAULT_PROLONG
282         else:
283             self.prolongFactor = aProlongFactor
284
285         #flags for inverted use of control pins
286         #used for some hardware
287         self.invertRST = 0
288         self.invertTEST = 0
289         self.swapRSTTEST = 0
290         self.telosLatch = 0
291         self.telosI2C = 0
292         
293         self.protocolMode = self.MODE_BSL
294         self.BSLMemAccessWarning = 0                #Default: no warning.
295         self.slowmode = 0
296
297     def comInit(self, port):
298         """Tries to open the serial port given and
299         initialises the port and variables.
300         The timeout and the number of allowed errors is multiplied by
301         'aProlongFactor' after transmission of a command to give
302         plenty of time to the micro controller to finish the command.
303         Returns zero if the function is successful."""
304         if DEBUG > 1: sys.stderr.write("* comInit()\n")
305         self.seqNo = 0
306         self.reqNo = 0
307         self.rxPtr = 0
308         self.txPtr = 0
309         # Startup-Baudrate: 9600,8,E,1, 1s timeout
310         self.serialport = serial.Serial(
311             port,
312             9600,
313             parity = serial.PARITY_EVEN,
314             timeout = self.timeout
315         )
316         if DEBUG: sys.stderr.write("using serial port %r\n" % self.serialport.portstr)
317         
318         if not self.z1:
319             self.SetRSTpin()                        #enable power
320             self.SetTESTpin()                       #enable power
321         self.serialport.flushInput()
322         self.serialport.flushOutput()
323
324     def comDone(self):
325         """Closes the used serial port.
326         This function must be called at the end of a program,
327         otherwise the serial port might not be released and can not be
328         used in other programs.
329         Returns zero if the function is successful."""
330         if DEBUG > 1: sys.stderr.write("* comDone()")
331         self.SetRSTpin(1)                       #disable power
332         self.SetTESTpin(0)                      #disable power
333         self.serialport.close()
334
335     def comRxHeader(self):
336         """receive header and split data"""
337         if DEBUG > 1: sys.stderr.write("* comRxHeader()\n")
338
339         hdr = self.serialport.read(1)
340         if not hdr: raise BSLException("Timeout")
341         rxHeader = ord(hdr) & 0xf0;
342         rxNum    = ord(hdr) & 0x0f;
343
344         if self.protocolMode == self.MODE_BSL:
345             self.reqNo = 0
346             self.seqNo = 0
347             rxNum = 0
348         if DEBUG > 1: sys.stderr.write("* comRxHeader() OK\n")
349         return rxHeader, rxNum
350
351     def comRxFrame(self, rxNum):
352         if DEBUG > 1: sys.stderr.write("* comRxFrame()\n")
353         rxFrame = chr(self.DATA_FRAME | rxNum)
354
355         if DEBUG > 2: sys.stderr.write("  comRxFrame() header...\n")
356         rxFramedata = self.serialport.read(3)
357         if len(rxFramedata) != 3: raise BSLException("Timeout")
358         rxFrame = rxFrame + rxFramedata
359
360         if DEBUG > 3: sys.stderr.write("  comRxFrame() check header...\n")
361         if rxFrame[1] == chr(0) and rxFrame[2] == rxFrame[3]:   #Add. header info. correct?
362             rxLengthCRC = ord(rxFrame[2]) + 2       #Add CRC-Bytes to length
363             if DEBUG > 2: sys.stderr.write("  comRxFrame() receiving data, size: %s\n" % rxLengthCRC)
364
365             rxFramedata = self.serialport.read(rxLengthCRC)
366             if len(rxFramedata) != rxLengthCRC: raise BSLException("Timeout")
367             rxFrame = rxFrame + rxFramedata
368             #Check received frame:
369             if DEBUG > 3: sys.stderr.write("  comRxFrame() crc check\n")
370             #rxLength+4: Length with header but w/o CRC:
371             checksum = self.calcChecksum(rxFrame, ord(rxFrame[2]) + 4)
372             if rxFrame[ord(rxFrame[2])+4] == chr(0xff & checksum) and \
373                rxFrame[ord(rxFrame[2])+5] == chr(0xff & (checksum >> 8)): #Checksum correct?
374                 #Frame received correctly (=> send next frame)
375                 if DEBUG > 2: sys.stderr.write("* comRxFrame() OK\n")
376                 return rxFrame
377             else:
378                 if DEBUG: sys.stderr.write("  comRxFrame() Checksum wrong\n")
379         else:
380             if DEBUG: sys.stderr.write("  comRxFrame() Header corrupt %r" % rxFrame)
381         raise BSLException(self.ERR_COM)            #Frame has errors!
382
383     def comTxHeader(self, txHeader):
384         """send header"""
385         if DEBUG > 1: sys.stderr.write("* txHeader()\n")
386         self.serialport.write(txHeader)
387
388     def comTxRx(self, cmd, dataOut, length):
389         """Sends the command cmd with the data given in dataOut to the
390         microcontroller and expects either an acknowledge or a frame
391         with result from the microcontroller.  The results are stored
392         in dataIn (if not a NULL pointer is passed).
393         In this routine all the necessary protocol stuff is handled.
394         Returns zero if the function was successful."""
395         if DEBUG > 1: sys.stderr.write("* comTxRx()\n")
396         txFrame     = []
397         rxHeader    = 0
398         rxNum       = 0
399
400         dataOut = list(dataOut)     #convert to a list for simpler data fill in
401         #Transmitting part ----------------------------------------
402         #Prepare data for transmit
403         if (length % 2) != 0:
404             #/* Fill with one byte to have even number of bytes to send */
405             if self.protocolMode == self.MODE_BSL:
406                 dataOut.append(0xFF)  #fill with 0xFF
407             else:
408                 dataOut.append(0)     #fill with zero
409
410         txFrame = "%c%c%c%c" % (self.DATA_FRAME | self.seqNo, cmd, len(dataOut), len(dataOut))
411
412         self.reqNo = (self.seqNo + 1) % self.MAX_FRAME_COUNT
413
414         txFrame = txFrame + string.join(dataOut,'')
415         checksum = self.calcChecksum(txFrame, length + 4)
416         txFrame = txFrame + chr(checksum & 0xff)
417         txFrame = txFrame + chr((checksum >> 8) & 0xff)
418
419         accessAddr = (0x0212 + (checksum^0xffff)) & 0xfffe  #0x0212: Address of wCHKSUM
420         if self.BSLMemAccessWarning and accessAddr < self.BSL_CRITICAL_ADDR:
421             sys.stderr.write("WARNING: This command might change data at address %04x or %04x!\n" % (accessAddr, accessAddr + 1))
422
423         self.serialport.flushInput()                #clear receiving queue
424         #TODO: Check after each transmitted character,
425         #TODO: if microcontroller did send a character (probably a NAK!).
426         for c in txFrame:
427             self.serialport.write(c)
428             if DEBUG > 3: sys.stderr.write("\ttx %02x" % ord(c))
429             #if self.serialport.inWaiting(): break  #abort when BSL replies, probably NAK
430         else:
431             if DEBUG > 1: sys.stderr.write( "  comTxRx() transmit OK\n")
432
433         #Receiving part -------------------------------------------
434         rxHeader, rxNum = self.comRxHeader()        #receive header
435         if DEBUG > 1: sys.stderr.write("  comTxRx() rxHeader=0x%02x, rxNum=%d, seqNo=%d, reqNo=%s\n" % (rxHeader, rxNum, self.seqNo, self.reqNo))
436         if rxHeader == self.DATA_ACK:               #acknowledge/OK
437             if DEBUG > 2: sys.stderr.write("  comTxRx() DATA_ACK\n")
438             if rxNum == self.reqNo:
439                 self.seqNo = self.reqNo
440                 if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_ACK OK\n")
441                 return          #Acknowledge received correctly => next frame
442             raise BSLException(self.ERR_FRAME_NUMBER)
443         elif rxHeader == self.DATA_NAK:             #not acknowledge/error
444             if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_NAK\n")
445             raise BSLException(self.ERR_RX_NAK)
446         elif rxHeader == self.DATA_FRAME:           #receive data
447             if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_FRAME\n")
448             if rxNum == self.reqNo:
449                 rxFrame = self.comRxFrame(rxNum)
450                 return rxFrame
451             raise BSLException(self.ERR_FRAME_NUMBER)
452         elif rxHeader == self.CMD_FAILED:           #Frame ok, but command failed.
453             if DEBUG > 2: sys.stderr.write("*  comTxRx() CMD_FAILED\n")
454             raise BSLException(self.ERR_CMD_FAILED)
455
456         raise BSLException("Unknown header 0x%02x\nAre you downloading to RAM into an old device that requires the patch? Try option -U" % rxHeader)
457
458     def SetDTR(self, level, invert):
459         """Controls DTR pin (0: GND; 1: VCC; unless inverted flag is set)"""
460         if invert:
461             self.serialport.setDTR(not level)
462         else:
463             self.serialport.setDTR(level)
464         if self.slowmode:
465             time.sleep(0.040)
466
467     def SetRTS(self, level, invert):
468         """Controls RTS pin (0: GND; 1: VCC; unless inverted flag is set)"""
469         if invert:
470             self.serialport.setRTS(not level)
471         else:
472             self.serialport.setRTS(level)
473         if self.slowmode:
474             time.sleep(0.040)
475
476     def SetRSTpin(self, level=1):
477         """Controls RST/NMI pin (0: GND; 1: VCC; unless inverted flag is set)"""
478         if self.swapRSTTEST:
479             self.SetRTS(level, self.invertRST)
480         else:
481             self.SetDTR(level, self.invertRST)
482
483     def SetTESTpin(self, level=1):
484         """Controls TEST pin (inverted on board: 0: VCC; 1: GND; unless inverted flag is set)"""
485         if self.swapRSTTEST:
486             self.SetDTR(level, self.invertTEST)
487         else:
488             self.SetRTS(level, self.invertTEST)
489
490     def telosSetSCL(self, level):
491         self.serialport.setRTS(not level)
492
493     def telosSetSDA(self, level):
494         self.serialport.setDTR(not level)
495
496     def telosI2CStart(self):
497         self.telosSetSDA(1)
498         self.telosSetSCL(1)
499         self.telosSetSDA(0)
500
501     def telosI2CStop(self):
502         self.telosSetSDA(0)
503         self.telosSetSCL(1)
504         self.telosSetSDA(1)
505
506     def telosI2CWriteBit(self, bit):
507         self.telosSetSCL(0)
508         self.telosSetSDA(bit)
509         time.sleep(2e-6)
510         self.telosSetSCL(1)
511         time.sleep(1e-6)
512         self.telosSetSCL(0)
513
514     def telosI2CWriteByte(self, byte):
515         self.telosI2CWriteBit( byte & 0x80 );
516         self.telosI2CWriteBit( byte & 0x40 );
517         self.telosI2CWriteBit( byte & 0x20 );
518         self.telosI2CWriteBit( byte & 0x10 );
519         self.telosI2CWriteBit( byte & 0x08 );
520         self.telosI2CWriteBit( byte & 0x04 );
521         self.telosI2CWriteBit( byte & 0x02 );
522         self.telosI2CWriteBit( byte & 0x01 );
523         self.telosI2CWriteBit( 0 );  # "acknowledge"
524
525     def telosI2CWriteCmd(self, addr, cmdbyte):
526         self.telosI2CStart()
527         self.telosI2CWriteByte( 0x90 | (addr << 1) )
528         self.telosI2CWriteByte( cmdbyte )
529         self.telosI2CStop()
530     def writepicROM(self, address, data):
531         ''' Writes data to @address'''
532         for i in range(7,-1,-1):
533             self.picROMclock((address >> i) & 0x01)
534         self.picROMclock(0)
535         recbuf = 0
536         for i in range(7,-1,-1):
537             s = ((data >> i) & 0x01)
538             #print s
539             if i < 1:
540                 r = not self.picROMclock(s, True)
541             else:
542                 r = not self.picROMclock(s)
543             recbuf = (recbuf << 1) + r
544
545         self.picROMclock(0, True)
546         #k = 1
547         #while not self.serial.getCTS():
548         #    pass 
549         #time.sleep(0.1)
550         return recbuf
551
552     def readpicROM(self, address):
553         ''' reads a byte from @address'''
554         for i in range(7,-1,-1):
555             self.picROMclock((address >> i) & 0x01)
556         self.picROMclock(1)
557         recbuf = 0
558         r = 0
559         for i in range(7,-1,-1):
560             r = self.picROMclock(0)
561             recbuf = (recbuf << 1) + r
562         self.picROMclock(r)
563         #time.sleep(0.1)
564         return recbuf
565         
566     def picROMclock(self, masterout, slow = False):
567         #print "setting masterout to "+str(masterout)
568         self.serialport.setRTS(masterout)
569         self.serialport.setDTR(1)
570         #time.sleep(0.02)
571         self.serialport.setDTR(0)
572         if slow:
573             time.sleep(0.02)
574         return self.serialport.getCTS()
575
576     def picROMfastclock(self, masterout):
577         #print "setting masterout to "+str(masterout)
578         self.serialport.setRTS(masterout)
579         self.serialport.setDTR(1)
580         self.serialport.setDTR(0)
581         time.sleep(0.02)
582         return self.serialport.getCTS()
583
584     def bslResetZ1(self, invokeBSL=0):
585         '''
586         Applies BSL entry sequence on RST/NMI and TEST/VPP pins
587         Parameters:
588             invokeBSL = 1: complete sequence
589             invokeBSL = 0: only RST/NMI pin accessed
590             
591         By now only BSL mode is accessed
592         '''
593         
594         if DEBUG > 1: sys.stderr.write("* bslReset(invokeBSL=%s)\n" % invokeBSL)
595         if invokeBSL:
596             #sys.stderr.write("in Z1 bsl reset...\n")
597             time.sleep(0.1)
598             self.writepicROM(0xFF, 0xFF)
599             time.sleep(0.1)
600             #sys.stderr.write("z1 bsl reset done...\n")
601         else:
602             #sys.stderr.write("in Z1 reset...\n")
603             time.sleep(0.1)
604             self.writepicROM(0xFF, 0xFE)
605             time.sleep(0.1)
606             #sys.stderr.write("z1 reset done...\n")
607
608     def telosBReset(self,invokeBSL=0):
609         # "BSL entry sequence at dedicated JTAG pins"
610         # rst !s0: 0 0 0 0 1 1
611         # tck !s1: 1 0 1 0 0 1
612         #   s0|s1: 1 3 1 3 2 0
613
614         # "BSL entry sequence at shared JTAG pins"
615         # rst !s0: 0 0 0 0 1 1
616         # tck !s1: 0 1 0 1 1 0
617         #   s0|s1: 3 1 3 1 0 2
618
619         if invokeBSL:
620             self.telosI2CWriteCmd(0,1)
621             self.telosI2CWriteCmd(0,3)
622             self.telosI2CWriteCmd(0,1)
623             self.telosI2CWriteCmd(0,3)
624             self.telosI2CWriteCmd(0,2)
625             self.telosI2CWriteCmd(0,0)
626         else:
627             self.telosI2CWriteCmd(0,3)
628             self.telosI2CWriteCmd(0,2)
629
630         # This line was not defined inside the else: block, not sure where it
631         # should be however
632         self.telosI2CWriteCmd(0,0)
633         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
634         self.serialport.flushInput()  #clear buffers
635
636     def bslReset(self, invokeBSL=0):
637         """Applies BSL entry sequence on RST/NMI and TEST/VPP pins
638         Parameters:
639             invokeBSL = 1: complete sequence
640             invokeBSL = 0: only RST/NMI pin accessed
641
642         RST is inverted twice on boot loader hardware
643         TEST is inverted (only once)
644         Need positive voltage on DTR, RTS for power-supply of hardware"""
645         if self.telosI2C:
646             self.telosBReset(invokeBSL)
647             return
648         
649         if self.z1:
650             if DEBUG > 1: sys.stderr.write("* entering bsl with z1\n")
651             self.bslResetZ1(invokeBSL)
652             return
653     
654
655         if DEBUG > 1: sys.stderr.write("* bslReset(invokeBSL=%s)\n" % invokeBSL)
656         self.SetRSTpin(1)       #power suply
657         self.SetTESTpin(1)      #power suply
658         time.sleep(0.250)       #charge capacitor on boot loader hardware
659
660         if self.telosLatch:
661             self.SetTESTpin(0)
662             self.SetRSTpin(0)
663             self.SetTESTpin(1)
664         self.SetRSTpin(0)       #RST  pin: GND
665
666         if invokeBSL:
667             self.SetTESTpin(1)  #TEST pin: GND
668             self.SetTESTpin(0)  #TEST pin: Vcc
669             self.SetTESTpin(1)  #TEST pin: GND
670             self.SetTESTpin(0)  #TEST pin: Vcc
671             self.SetRSTpin (1)  #RST  pin: Vcc
672             self.SetTESTpin(1)  #TEST pin: GND
673         else:
674             self.SetRSTpin(1)   #RST  pin: Vcc
675         time.sleep(0.250)       #give MSP430's oscillator time to stabilize
676
677         self.serialport.flushInput()    #clear buffers
678
679     def bslSync(self,wait=0):
680         """Transmits Synchronization character and expects to receive Acknowledge character
681         if wait is 0 it must work the first time. otherwise if wait is 1
682         it is retried (forever).
683         """
684         loopcnt = 5                                 #Max. tries to get synchronization
685
686         if DEBUG > 1: sys.stderr.write("* bslSync(wait=%d)\n" % wait)
687         while wait or loopcnt:
688             loopcnt = loopcnt - 1                   #count down tries
689             self.serialport.flushInput()            #clear input, in case a prog is running
690
691             self.serialport.write(chr(self.BSL_SYNC))   #Send synchronization byte
692             c = self.serialport.read(1)             #read answer
693             if c == chr(self.DATA_ACK):             #ACk
694                 if DEBUG > 1: sys.stderr.write("  bslSync() OK\n")
695                 return                              #Sync. successful
696             elif not c:                             #timeout
697                     if loopcnt > 4:
698                         if DEBUG > 1:
699                             sys.stderr.write("  bslSync() timeout, retry ...\n")
700                     elif loopcnt == 4:
701                         #nmi may have caused the first reset to be ignored, try again
702                         self.bslReset(0) 
703                         self.bslReset(1)
704                     elif loopcnt > 0:
705                         if DEBUG > 1:
706                             sys.stderr.write("  bslSync() timeout, retry ...\n")
707                     else :
708                         if DEBUG > 1:
709                             sys.stderr.write("  bslSync() timeout\n")
710             else:                                   #garbage
711                 if DEBUG > 1: sys.stderr.write("  bslSync() failed (0x%02x), retry ...\n" % ord(c))
712                 
713                 raise BSLException(self.ERR_BSL_SYNC)       #Sync. failed
714
715     def bslTxRx(self, cmd, addr, length = 0, blkout = None, wait=0):
716         """Transmits a command (cmd) with its parameters:
717         start-address (addr), length (len) and additional
718         data (blkout) to boot loader.
719         wait specified if the bsl sync should be tried once or
720         repeated, forever
721         Parameters return by boot loader are passed via blkin.
722         """
723         if DEBUG > 1: sys.stderr.write("* bslTxRx()\n")
724
725         if cmd == self.BSL_TXBLK:
726             #Align to even start address
727             if (addr % 2) != 0:
728                 addr = addr - 1                     #Decrement address and
729                 blkout = chr(0xFF) + blkOut         #fill first byte of blkout with 0xFF
730                 length = length + 1
731             #Make sure that len is even
732             if (length % 2) != 0:
733                 blkout = blkout + chr(0xFF)         #Inc. len and fill last byte of blkout with 0xFF
734                 length = length + 1
735
736         elif cmd == self.BSL_RXBLK:
737             #Align to even start address
738             if (addr % 2) != 0:
739                 addr = addr - 1                     #Decrement address but
740                 length = length + 1                 #request an additional byte
741             #Make sure that len is even
742             if (length % 2) != 0:
743                 length = length + 1
744
745         #if cmd == self.BSL_TXBLK or cmd == self.BSL_TXPWORD:
746         #    length = len + 4
747
748         #Add necessary information data to frame
749         dataOut =  struct.pack("<HH", addr, length)
750
751         if blkout: #Copy data out of blkout into frame
752             dataOut = dataOut + blkout
753
754         self.bslSync(wait)                          #synchronize BSL
755         rxFrame = self.comTxRx(cmd, dataOut, len(dataOut))  #Send frame
756         if rxFrame:                                 #test answer
757             return rxFrame[4:] #return only data w/o [hdr,null,len,len]
758         else:
759             return rxFrame
760
761
762 class Segment:
763     """store a string with memory contents along with its startaddress"""
764     def __init__(self, startaddress = 0, data=None):
765         if data is None:
766             self.data = ''
767         else:
768             self.data = data
769         self.startaddress = startaddress
770
771     def __getitem__(self, index):
772         return self.data[index]
773
774     def __len__(self):
775         return len(self.data)
776
777     def __repr__(self):
778         return "Segment(startaddress = 0x%04x, data=%r)" % (self.startaddress, self.data)
779
780 class Memory:
781     """represent memory contents. with functions to load files"""
782     def __init__(self, filename=None):
783         self.segments = []
784         if filename:
785             self.filename = filename
786             self.loadFile(filename)
787
788     def append(self, seg):
789         self.segments.append(seg)
790
791     def __getitem__(self, index):
792         return self.segments[index]
793
794     def __len__(self):
795         return len(self.segments)
796
797     def loadIHex(self, file):
798         """load data from a (opened) file in Intel-HEX format"""
799         segmentdata = []
800         currentAddr = 0
801         startAddr   = 0
802         lines = file.readlines()
803         for l in lines:
804             if l[0] != ':': raise BSLException("File Format Error\n")
805             l = l.strip()       #fix CR-LF issues...
806             length  = int(l[1:3],16)
807             address = int(l[3:7],16)
808             type    = int(l[7:9],16)
809             check   = int(l[-2:],16)
810             if type == 0x00:
811                 if currentAddr != address:
812                     if segmentdata:
813                         self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
814                     startAddr = currentAddr = address
815                     segmentdata = []
816                 for i in range(length):
817                     segmentdata.append( chr(int(l[9+2*i:11+2*i],16)) )
818                 currentAddr = length + currentAddr
819             elif type in (0x01, 0x02, 0x03, 0x04, 0x05):
820                 pass
821             else:
822                 sys.stderr.write("Ignored unknown field (type 0x%02x) in ihex file.\n" % type)
823         if segmentdata:
824             self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
825
826     def loadTIText(self, file):
827         """load data from a (opened) file in TI-Text format"""
828         next        = 1
829         startAddr   = 0
830         segmentdata = []
831         #Convert data for MSP430, TXT-File is parsed line by line
832         while next >= 1:
833             #Read one line
834             l = file.readline()
835             if not l: break #EOF
836             l = l.strip()
837             if l[0] == 'q': break
838             elif l[0] == '@':        #if @ => new address => send frame and set new addr.
839                 #create a new segment
840                 if segmentdata:
841                     self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
842                 startAddr = int(l[1:],16)
843                 segmentdata = []
844             else:
845                 for i in string.split(l):
846                     segmentdata.append(chr(int(i,16)))
847         if segmentdata:
848             self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
849
850     def loadELF(self, file):
851         """load data from a (opened) file in ELF object format.
852         File must be seekable"""
853         import elf
854         obj = elf.ELFObject()
855         obj.fromFile(file)
856         if obj.e_type != elf.ELFObject.ET_EXEC:
857             raise Exception("No executable")
858         for section in obj.getSections():
859             if DEBUG:
860                 sys.stderr.write("ELF section %s at 0x%04x %d bytes\n" % (section.name, section.lma, len(section.data)))
861             if len(section.data):
862                 self.segments.append( Segment(section.lma, section.data) )
863         
864     def loadFile(self, filename):
865         """fill memory with the contents of a file. file type is determined from extension"""
866         #TODO: do a contents based detection
867         if filename[-4:].lower() == '.txt':
868             self.loadTIText(open(filename, "rb"))
869         elif filename[-4:].lower() in ('.a43', '.hex'):
870             self.loadIHex(open(filename, "rb"))
871         else:
872             self.loadELF(open(filename, "rb"))
873
874     def getMemrange(self, fromadr, toadr):
875         """get a range of bytes from the memory. unavailable values are filled with 0xff."""
876         res = ''
877         toadr = toadr + 1   #python indxes are excluding end, so include it
878         while fromadr < toadr:
879             #print "fromto: %04x %04x" % (fromadr, toadr)
880             for seg in self.segments:
881                 #print seg
882                 segend = seg.startaddress + len(seg.data)
883                 if seg.startaddress <= fromadr and fromadr < segend:
884                     #print "startok 0x%04x %d" % (seg.startaddress, len(seg.data))
885                     #print ("0x%04x "*3) % (segend, fromadr, toadr)
886                     if toadr > segend:   #not all data in segment
887                         #print "out of segment"
888                         catchlength = segend-fromadr
889                     else:
890                         catchlength = toadr-fromadr
891                     #print toadr-fromadr
892                     #print catchlength
893                     res = res + seg.data[fromadr-seg.startaddress : fromadr-seg.startaddress+catchlength]
894                     fromadr = fromadr + catchlength    #adjust start
895                     if len(res) >= toadr-fromadr:
896                         break#return res
897             else:
898                     res = res + chr(255)
899                     fromadr = fromadr + 1 #adjust start
900                     #print "fill FF"
901         #print "res: %r" % res
902         return res
903
904
905 class BootStrapLoader(LowLevel):
906     """higher level Bootstrap Loader functions."""
907
908     ERR_VERIFY_FAILED       = "Error: verification failed"
909     ERR_ERASE_CHECK_FAILED  = "Error: erase check failed"
910
911     ACTION_PROGRAM          = 0x01 #Mask: program data
912     ACTION_VERIFY           = 0x02 #Mask: verify data
913     ACTION_ERASE_CHECK      = 0x04 #Mask: erase check
914
915     #Max. bytes sent within one frame if parsing a TI TXT file.
916     #( >= 16 and == n*16 and <= MAX_DATA_BYTES!)
917     MAXDATA                 = 240-16
918
919
920     def __init__(self, *args, **kargs):
921         LowLevel.__init__(self, *args, **kargs)
922         self.byteCtr        = 0
923         self.meraseCycles   = 1
924         self.patchRequired  = 0
925         self.patchLoaded    = 0
926         self.bslVer         = 0
927         self.passwd         = None
928         self.data           = None
929         self.maxData        = self.MAXDATA
930         self.cpu            = None
931
932
933     def preparePatch(self):
934         """prepare to download patch"""
935         if DEBUG > 1: sys.stderr.write("* preparePatch()\n")
936
937         if self.patchLoaded:
938             #Load PC with 0x0220.
939             #This will invoke the patched bootstrap loader subroutines.
940             self.bslTxRx(self.BSL_LOADPC,           #Command: Load PC
941                            0x0220)                  #Address to load into PC
942             self.BSLMemAccessWarning = 0 #Error is removed within workaround code
943         return
944
945     def postPatch(self):
946         """setup after the patch is loaded"""
947         if DEBUG > 1: sys.stderr.write("* postPatch()\n")
948         if self.patchLoaded:
949             self.BSLMemAccessWarning = 1                #Turn warning back on.
950
951     
952     def verifyBlk(self, addr, blkout, action):
953         """verify memory against data or 0xff"""
954         if DEBUG > 1: sys.stderr.write("* verifyBlk()\n")
955
956         if action & self.ACTION_VERIFY or action & self.ACTION_ERASE_CHECK:
957             if DEBUG: sys.stderr.write("  Check starting at 0x%04x, %d bytes ... \n" % (addr, len(blkout)))
958
959             self.preparePatch()
960             blkin = self.bslTxRx(self.BSL_RXBLK, addr, len(blkout))
961             self.postPatch()
962
963             for i in range(len(blkout)):
964                 if action & self.ACTION_VERIFY:
965                     #Compare data in blkout and blkin
966                     if blkin[i] != blkout[i]:
967                         sys.stderr.write("Verification failed at 0x%04x (0x%02x, 0x%02x)\n" % (addr+i, ord(blkin[i]), ord(blkout[i])))
968                         sys.stderr.flush()
969                         raise BSLException(self.ERR_VERIFY_FAILED)      #Verify failed!
970                     continue
971                 elif action & self.ACTION_ERASE_CHECK:
972                     #Compare data in blkin with erase pattern
973                     if blkin[i] != chr(0xff):
974                         sys.stderr.write("Erase Check failed at 0x%04x (0x%02x)\n" % (addr+i, ord(blkin[i])))
975                         sys.stderr.flush()
976                         raise BSLException(self.ERR_ERASE_CHECK_FAILED) #Erase Check failed!
977                     continue
978     def readBlk(self,adr,len):
979         """Read a block of memory."""
980         blkin = self.bslTxRx(self.BSL_RXBLK, addr, len(blkout))
981         
982     def programBlk(self, addr, blkout, action):
983         """program a memory block"""
984         if DEBUG > 1: sys.stderr.write("* programBlk()\n")
985
986         #Check, if specified range is erased
987         self.verifyBlk(addr, blkout, action & self.ACTION_ERASE_CHECK)
988
989         if action & self.ACTION_PROGRAM:
990             if DEBUG: sys.stderr.write("  Program starting at 0x%04x, %i bytes ...\n" % (addr, len(blkout)))
991             self.preparePatch()
992             #Program block
993             self.bslTxRx(self.BSL_TXBLK, addr, len(blkout), blkout)
994             self.postPatch()
995
996         #Verify block
997         self.verifyBlk(addr, blkout, action & self.ACTION_VERIFY)
998
999     #segments:
1000     #list of tuples or lists:
1001     #segements = [ (addr1, [d0,d1,d2,...]), (addr2, [e0,e1,e2,...])]
1002     def programData(self, segments, action):
1003         """programm or verify data"""
1004         if DEBUG > 1: sys.stderr.write("* programData()\n")
1005         for seg in segments:
1006             currentAddr = seg.startaddress
1007             pstart = 0
1008             while pstart<len(seg.data):
1009                 length = self.MAXDATA
1010                 if pstart+length > len(seg.data):
1011                     length = len(seg.data) - pstart
1012                 self.programBlk(currentAddr, seg.data[pstart:pstart+length], action)
1013                 pstart = pstart + length
1014                 currentAddr = currentAddr + length
1015                 self.byteCtr = self.byteCtr + length #total sum
1016     
1017     def uploadData(self, startaddress, size, wait=0):
1018         """upload a datablock"""
1019         if DEBUG > 1: sys.stderr.write("* uploadData()\n")
1020         data = ''
1021         pstart = 0
1022         while pstart<size:
1023             length = self.maxData
1024             if pstart+length > size:
1025                 length = size - pstart
1026             data = data + self.bslTxRx(self.BSL_RXBLK,
1027                                        pstart+startaddress,
1028                                        length,
1029                                        wait=wait)[:-2] #cut away checksum
1030             pstart = pstart + length
1031         return data
1032
1033     def txPasswd(self, passwd=None, wait=0):
1034         """transmit password, default if None is given."""
1035         if DEBUG > 1: sys.stderr.write("* txPassword(%r)\n" % passwd)
1036         if passwd is None:
1037             #Send "standard" password to get access to protected functions.
1038             sys.stderr.write("Transmit default password ...\n")
1039             sys.stderr.flush()
1040             #Flash is completely erased, the contents of all Flash cells is 0xff
1041             passwd = chr(0xff)*32
1042         else:
1043             #sanity check of password
1044             if len(passwd) != 32:
1045                 raise ValueError, "password has wrong length (%d)\n" % len(passwd)
1046             sys.stderr.write('Transmit password ...\n')
1047             sys.stderr.flush()
1048         #send the password
1049         self.bslTxRx(self.BSL_TXPWORD,      #Command: Transmit Password
1050                        0xffe0,              #Address of interupt vectors
1051                        0x0020,              #Number of bytes
1052                        passwd,              #password
1053                        wait=wait)           #if wait is 1, try to sync forever
1054
1055
1056     #-----------------------------------------------------------------
1057
1058     def actionMassErase(self):
1059         """Erase the flash memory completely (with mass erase command)"""
1060         sys.stderr.write("Mass Erase...\n")
1061         sys.stderr.flush()
1062         self.bslReset(1)                            #Invoke the boot loader.
1063         for i in range(self.meraseCycles):
1064             if i == 1: sys.stderr.write("Additional Mass Erase Cycles...\n")
1065             self.bslTxRx(self.BSL_MERAS,            #Command: Mass Erase
1066                                 0xff00,             #Any address within flash memory.
1067                                 0xa506)             #Required setting for mass erase!
1068         self.passwd = None                          #No password file required!
1069         #print "Mass Erase complete"
1070         #Transmit password to get access to protected BSL functions.
1071         self.txPasswd()
1072
1073     def actionStartBSL(self, usepatch=1, adjsp=1, replacementBSL=None, forceBSL=0, mayuseBSL=0, speed=None, bslreset=1):
1074         """start BSL, download patch if desired and needed, adjust SP if desired"""
1075         sys.stderr.write("Invoking BSL...\n")
1076         sys.stderr.flush()
1077         
1078         #for '30, invertTEST=0, else =1
1079         if bslreset:
1080             self.bslReset(1)                        #Invoke the boot loader.
1081         
1082         
1083         self.txPasswd(self.passwd)                  #transmit password
1084
1085         #Read actual bootstrap loader version.
1086         #sys.stderr.write("Reading BSL version ...\n")
1087         blkin = self.bslTxRx(self.BSL_RXBLK,        #Command: Read/Receive Block
1088                           0x0ff0,                   #Start address
1089                           16)                       #No. of bytes to read
1090         dev_id, bslVerHi, bslVerLo = struct.unpack(">H8xBB4x", blkin[:-2]) #cut away checksum and extract data
1091         self.dev_id=dev_id;
1092         
1093         
1094         if self.cpu is None:                        #cpy type forced?
1095             if deviceids.has_key(dev_id):
1096                 self.cpu = deviceids[dev_id]        #try to autodectect CPU type
1097                 
1098                 if DEBUG:
1099                     sys.stderr.write("Autodetect successful: %04x -> %s\n" % (dev_id, self.cpu))
1100             else:
1101                 sys.stderr.write("Autodetect failed! Unkown ID: %04x. Trying to continue anyway.\n" % dev_id)
1102                 self.cpu = F1x                      #assume something and try anyway..
1103
1104         sys.stderr.write("Current bootstrap loader version: %x.%x (Device ID: %04x)\n" % (bslVerHi, bslVerLo, dev_id))
1105         sys.stderr.flush()
1106         self.bslVer = (bslVerHi << 8) | bslVerLo
1107
1108         if self.bslVer <= 0x0110:                   #check if patch is needed
1109             self.BSLMemAccessWarning = 1
1110         else:
1111             self.BSLMemAccessWarning = 0 #Fixed in newer versions of BSL.
1112
1113         if self.bslVer <= 0x0130 and adjsp:
1114             #only do this on BSL where it's needed to prevent
1115             #malfunction with F4xx devices/ newer ROM-BSLs
1116             
1117             #Execute function within bootstrap loader
1118             #to prepare stack pointer for the following patch.
1119             #This function will lock the protected functions again.
1120             sys.stderr.write("Adjust SP. Load PC with 0x0C22 ...\n")
1121             self.bslTxRx(self.BSL_LOADPC,           #Command: Load PC
1122                                 0x0C22)             #Address to load into PC
1123             #Re-send password to re-gain access to protected functions.
1124             self.txPasswd(self.passwd)
1125
1126         #get internal BSL replacement if needed or forced by the user
1127         #required if speed is set but an old BSL is in the device
1128         #if a BSL is given by the user, that one is used and not the internal one
1129         if ((mayuseBSL and speed and self.bslVer < 0x0150) or forceBSL) and replacementBSL is None:
1130             replacementBSL = Memory() #File to program
1131             if self.cpu == F4x:
1132                 if DEBUG:
1133                     sys.stderr.write("Using built in BSL replacement for F4x devices\n")
1134                     sys.stderr.flush()
1135                 replacementBSL.loadTIText(cStringIO.StringIO(F4X_BSL))  #parse embedded BSL
1136             else:
1137                 if DEBUG:
1138                     sys.stderr.write("Using built in BSL replacement for F1x devices\n")
1139                     sys.stderr.flush()
1140                 replacementBSL.loadTIText(cStringIO.StringIO(F1X_BSL))  #parse embedded BSL
1141     
1142         #now download the new BSL, if allowed and needed (version lower than the
1143         #the replacement) or forced
1144         if replacementBSL is not None:
1145             self.actionDownloadBSL(replacementBSL)
1146
1147         #debug message with the real BSL version in use (may have changed after replacement BSL)
1148         if DEBUG:
1149             sys.stderr.write("Current bootstrap loader version: 0x%04x\n" % (self.bslVer,))
1150             sys.stderr.flush()
1151
1152         #now apply workarounds or patches if BSL in use requires that
1153         if self.bslVer <= 0x0110:                   #check if patch is needed
1154             if usepatch:                            #test if patch is desired
1155                 sys.stderr.write("Patch for flash programming required!\n")
1156                 self.patchRequired = 1
1157
1158                 sys.stderr.write("Load and verify patch ...\n")
1159                 sys.stderr.flush()
1160                 #Programming and verification is done in one pass.
1161                 #The patch file is only read and parsed once.
1162                 segments = Memory()                     #data to program
1163                 segments.loadTIText(cStringIO.StringIO(PATCH))  #parse embedded patch
1164                 #program patch
1165                 self.programData(segments, self.ACTION_PROGRAM | self.ACTION_VERIFY)
1166                 self.patchLoaded = 1
1167             else:
1168                 if DEBUG:
1169                     sys.stderr.write("Device needs patch, but not applied (usepatch is false).\n")    #message if not patched
1170
1171         #should the baudrate be changed?
1172         if speed is not None:
1173             self.actionChangeBaudrate(speed)            #change baudrate
1174
1175     def actionDownloadBSL(self, bslsegments):
1176         sys.stderr.write("Load new BSL into RAM...\n")
1177         sys.stderr.flush()
1178         self.programData(bslsegments, self.ACTION_PROGRAM)
1179         sys.stderr.write("Verify new BSL...\n")
1180         sys.stderr.flush()
1181         self.programData(bslsegments, self.ACTION_VERIFY) #File to verify
1182
1183         #Read startvector of bootstrap loader
1184         #blkin = self.bslTxRx(self.BSL_RXBLK, 0x0300, 2)
1185         #blkin = self.bslTxRx(self.BSL_RXBLK, 0x0220, 2)
1186         blkin = self.bslTxRx(self.BSL_RXBLK, bslsegments[0].startaddress, 2)
1187         startaddr = struct.unpack("<H", blkin[:2])[0]
1188
1189         sys.stderr.write("Starting new BSL at 0x%04x...\n" % startaddr)
1190         sys.stderr.flush()
1191         self.bslTxRx(self.BSL_LOADPC,  #Command: Load PC
1192                      startaddr)        #Address to load into PC
1193
1194         #BSL-Bugs should be fixed within "new" BSL
1195         self.BSLMemAccessWarning = 0
1196         self.patchRequired = 0
1197         self.patchLoaded   = 0
1198
1199         #Re-send password to re-gain access to protected functions.
1200         self.txPasswd(self.passwd)
1201
1202         #update version info
1203         #verison only valid for the internal ones, but it also makes sure 
1204         #that the patches are not applied if the user d/ls one
1205         self.bslVer = 0x0150
1206
1207     def actionEraseCheck(self):
1208         """check the erasure of required flash cells."""
1209         sys.stderr.write("Erase Check by file ...\n")
1210         sys.stderr.flush()
1211         if self.data is not None:
1212             self.programData(self.data, self.ACTION_ERASE_CHECK)
1213         else:
1214             raise BSLException, "cannot do erase check against data with not knowing the actual data"
1215
1216     def actionProgram(self):
1217         """program data into flash memory."""
1218         if self.data is not None:
1219             sys.stderr.write("Program ...\n")
1220             sys.stderr.flush()
1221             self.programData(self.data, self.ACTION_PROGRAM)
1222             sys.stderr.write("%i bytes programmed.\n" % self.byteCtr)
1223             sys.stderr.flush()
1224         else:
1225             raise BSLException, "programming without data not possible"
1226     def actionFromweb(self):
1227         """Grab GoodFET firmware from the web, then flash it."""
1228         print "Grabbing %x firmware." % self.dev_id;
1229         print "%s" % firmware[self.dev_id];
1230         fn="/tmp/.goodfet.hex"
1231         os.system("curl %s >%s" % (firmware[self.dev_id],fn))
1232         
1233         fw=Memory(fn);
1234         #fw.loadIhex(open(fn,"rb"));
1235         
1236         sys.stderr.write("Program ...\n")
1237         sys.stderr.flush()
1238         self.programData(fw, self.ACTION_PROGRAM | self.ACTION_VERIFY)
1239         sys.stderr.write("%i bytes programmed.\n" % self.byteCtr)
1240         sys.stderr.flush()
1241         
1242     def actionVerify(self):
1243         """Verify programmed data"""
1244         if self.data is not None:
1245             sys.stderr.write("Verify ...\n")
1246             sys.stderr.flush()
1247             self.programData(self.data, self.ACTION_VERIFY)
1248         else:
1249             raise BSLException, "verify without data not possible"
1250
1251     def actionReset(self):
1252         """perform a reset, start user programm"""
1253         sys.stderr.write("Reset device ...\n")
1254         sys.stderr.flush()
1255         self.bslReset(0) #only reset
1256
1257     def actionRun(self, address=0x220):
1258         """start program at specified address"""
1259         sys.stderr.write("Load PC with 0x%04x ...\n" % address)
1260         sys.stderr.flush()
1261         self.bslTxRx(self.BSL_LOADPC, #Command: Load PC
1262                             address)  #Address to load into PC
1263
1264     #table with values from slaa089a.pdf
1265     bauratetable = {
1266         F1x: {
1267              9600:[0x8580, 0x0000],
1268             19200:[0x86e0, 0x0001],
1269             38400:[0x87e0, 0x0002],
1270         },
1271         F2x: {
1272              9600:[0x8580, 0x0000],
1273             19200:[0x8B00, 0x0001],
1274             38400:[0x8C80, 0x0002],
1275         },
1276         F4x: {
1277              9600:[0x9800, 0x0000],
1278             19200:[0xb000, 0x0001],
1279             38400:[0xc800, 0x0002],
1280         },
1281     }
1282     def actionChangeBaudrate(self, baudrate=9600):
1283         """change baudrate. first the command is sent, then the comm
1284         port is reprogrammed. only possible with newer MSP430-BSL versions.
1285         (ROM >=1.6, downloadable >=1.5)"""
1286         try:
1287             baudconfigs = self.bauratetable[self.cpu]
1288         except KeyError:
1289             raise ValueError, "unknown CPU type %s, can't switch baudrate" % self.cpu
1290         try:
1291             a,l = baudconfigs[baudrate]
1292         except KeyError:
1293             raise ValueError, "baudrate not valid. valid values are %r" % baudconfigs.keys()
1294         
1295         sys.stderr.write("Changing baudrate to %d ...\n" % baudrate)
1296         sys.stderr.flush()
1297         self.bslTxRx(self.BSL_CHANGEBAUD,   #Command: change baudrate
1298                     a, l)                   #args are coded in adr and len
1299         time.sleep(0.010)                   #recomended delay
1300         self.serialport.setBaudrate(baudrate)
1301
1302     def actionReadBSLVersion(self):
1303         """informational output of BSL version number.
1304         (newer MSP430-BSLs only)"""
1305         ans = self.bslTxRx(self.BSL_TXVERSION, 0) #Command: receive version info
1306         #the following values are in big endian style!!!
1307         family_type, bsl_version = struct.unpack(">H8xH4x", ans[:-2]) #cut away checksum and extract data
1308         print "Device Type: 0x%04x\nBSL version: 0x%04x\n" % (family_type, bsl_version)
1309
1310
1311 def usage():
1312     """print some help message"""
1313     sys.stderr.write("""
1314 USAGE: %s [options] [file]
1315 Version: %s
1316
1317 If "-" is specified as file the data is read from the stdinput.
1318 A file ending with ".txt" is considered to be in TIText format,
1319 '.a43' and '.hex' as IntelHex and all other filenames are
1320 considered as ELF files.
1321
1322 General options:
1323   -h, --help            Show this help screen.
1324   -c, --comport=port    Specify the communication port to be used.
1325                         (Default is 0)
1326                                 0->COM1 / ttyS0
1327                                 1->COM2 / ttyS1
1328                                 etc.
1329   -P, --password=file   Specify a file with the interrupt vectors that
1330                         are used as password. This can be any file that
1331                         has previously been used to program the device.
1332                         (e.g. -P INT_VECT.TXT).
1333   -f, --framesize=num   Max. number of data bytes within one transmitted
1334                         frame (16 to 240 in steps of 16) (e.g. -f 240).
1335   -m, --erasecycles=num Number of mass erase cycles (default is 1). Some
1336                         old F149 devices need additional erase cycles.
1337                         On newer devices it is no longer needed. (e.g. for
1338                         an old F149: -m20)
1339   -U, --unpatched       Do not download the BSL patch, even when it is
1340                         needed. This is used when a program is downloaded
1341                         into RAM and executed from there (and where flash
1342                         programming is not needed.)
1343   -D, --debug           Increase level of debug messages. This won't be
1344                         very useful for the average user...
1345   -I, --intelhex        Force fileformat to IntelHex
1346   -T, --titext          Force fileformat to be TIText
1347   -N, --notimeout       Don't use timeout on serial port (use with care)
1348   -B, --bsl=bsl.txt     Load and use new BSL from the TI Text file
1349   -S, --speed=baud      Reconfigure speed, only possible with newer
1350                         MSP403-BSL versions (>1.5, read slaa089a.pdf for
1351                         details). If the --bsl option is not used, an
1352                         internal BSL replacement will be loaded.
1353                         Needs a target with at least 2kB RAM!
1354                         Possible values are 9600, 19200, 38400
1355                         (default 9600)
1356   -1, --f1x             Specify CPU family, in case autodetect fails
1357   -2, --f2x             Specify CPU family, in case autodetect fails
1358   -4, --f4x             Specify CPU family, in case autodetect fails
1359                         --F1x and --f2x are only needed when the "change
1360                         baudrate" feature is used and the autodetect feature
1361                         fails. If the device ID that is uploaded is known, it
1362                         has precedence to the command line option.
1363   --invert-reset        Invert signal on RST pin (used for some BSL hardware)
1364   --invert-test         Invert signal on TEST/TCK pin (used for some BSL
1365                         hardware)
1366   --swap-reset-test     Swap the RST and TEST pins (used for some BSL hardware)
1367   --telos-latch         Special twiddle in BSL reset for Telos hardware
1368   --telos-i2c           DTR/RTS map via an I2C switch to TCK/RST in Telos Rev.B
1369   --telos               Implies options --invert-reset, --invert-test, 
1370                         --swap-reset-test, and --telos-latch
1371   --telosb              Implies options --swap-reset-test, --telos-i2c,
1372                         --no-BSL-download, and --speed=38400
1373   --goodfet10
1374   --goodfet20
1375   --goodfet30
1376   --tmote               Identical operation to --telosb
1377   --z1                  Bootstrap a Z1
1378   --no-BSL-download     Do not download replacement BSL (disable automatic)
1379   --force-BSL-download  Download replacement BSL even if not needed (the one
1380                         in the device would have the required features)
1381   --slow                Add delays when operating the conrol pins. Useful if
1382                         the pins/circuit has high capacitance.
1383
1384 Program Flow Specifiers:
1385   -e, --masserase       Mass Erase (clear all flash memory)
1386   -E, --erasecheck      Erase Check by file
1387   -p, --program         Program file
1388   -v, --verify          Verify by file
1389
1390 The order of the above options matters! The table is ordered by normal
1391 execution order. For the options "Epv" a file must be specified.
1392 Program flow specifiers default to "pvr" if a file is given.
1393 Don't forget to specify "e" or "eE" when programming flash!
1394
1395 Data retreiving:
1396   -u, --upload=addr     Upload a datablock (see also: -s).
1397   -s, --size=num        Size of the data block do upload. (Default is 2)
1398   -x, --hex             Show a hexadecimal display of the uploaded data.
1399                         (Default)
1400   -b, --bin             Get binary uploaded data. This can be used
1401                         to redirect the output into a file.
1402
1403 Do before exit:
1404   -g, --go=address      Start programm execution at specified address.
1405                         This implies option --wait.
1406   -r, --reset           Reset connected MSP430. Starts application.
1407                         This is a normal device reset and will start
1408                         the programm that is specified in the reset
1409                         vector. (see also -g)
1410   -w, --wait            Wait for <ENTER> before closing serial port.
1411
1412 If it says "NAK received" it's probably because you specified no or a
1413 wrong password.
1414 """ % (sys.argv[0], VERSION))
1415
1416 #add some arguments to a function, but don't call it yet, instead return
1417 #a wrapper object for later invocation
1418 class curry:
1419     """create a callable with some arguments specified in advance"""
1420     def __init__(self, fun, *args, **kwargs):
1421         self.fun = fun
1422         self.pending = args[:]
1423         self.kwargs = kwargs.copy()
1424
1425     def __call__(self, *args, **kwargs):
1426         if kwargs and self.kwargs:
1427             kw = self.kwargs.copy()
1428             kw.update(kwargs)
1429         else:
1430             kw = kwargs or self.kwargs
1431         return apply(self.fun, self.pending + args, kw)
1432
1433     def __repr__(self):
1434         #first try if it a function
1435         try:
1436             return "curry(%s, %r, %r)" % (self.fun.func_name, self.pending, self.kwargs)
1437         except AttributeError:
1438             #fallback for callable classes
1439             return "curry(%s, %r, %r)" % (self.fun, self.pending, self.kwargs)
1440
1441 def hexify(line, bytes, width=16):
1442     return  '%04x  %s%s %s' % (
1443         line,
1444         ('%02x '*len(bytes)) % tuple(bytes),
1445         '   '* (width-len(bytes)),
1446         ('%c'*len(bytes)) % tuple(map(lambda x: (x>=32 and x<127) and x or ord('.'), bytes))
1447         )
1448
1449 #Main:
1450 def main(itest=1):
1451     global DEBUG
1452     import getopt
1453     filetype    = None
1454     filename    = None
1455     comPort     = None     #Default setting.
1456     speed       = None
1457     unpatched   = 0
1458     reset       = 0
1459     wait        = 0     #wait at the end
1460     goaddr      = None
1461     bsl         = BootStrapLoader()
1462     toinit      = []
1463     todo        = []
1464     startaddr   = None
1465     size        = 2
1466     hexoutput   = 1
1467     notimeout   = 0
1468     bslrepl     = None
1469     mayuseBSL   = 1
1470     forceBSL    = 0
1471     dumpivt     = 0
1472     dumpinfo    = 0
1473     
1474     bsl.invertRST = 1
1475     bsl.invertTEST = itest
1476     
1477     if(os.environ.get("board")=='telosb' or 
1478        os.environ.get("board")=='telosbbt' or
1479        os.environ.get("platform")=='telosb'):
1480         bsl.swapRSTTEST = 1
1481         bsl.telosI2C = 1
1482         mayuseBSL = 0
1483     if(os.environ.get("board")=='z1' or 
1484        os.environ.get("board")=='zolertiaz1'):
1485         bsl.z1 = 1
1486     
1487     
1488     if comPort is None and os.environ.get("GOODFET")!=None:
1489         glob_list = glob.glob(os.environ.get("GOODFET"));
1490         if len(glob_list) > 0:
1491             comPort = glob_list[0];
1492     if comPort is None:
1493         glob_list = glob.glob("/dev/tty.usbserial*");
1494         if len(glob_list) > 0:
1495             comPort = glob_list[0];
1496     if comPort is None:
1497         glob_list = glob.glob("/dev/ttyUSB*");
1498         if len(glob_list) > 0:
1499             comPort = glob_list[0];
1500     if os.name=='nt':
1501             from scanwin32 import winScan;
1502             scan=winScan();
1503             for order,comport,desc,hwid in sorted(scan.comports()):
1504                 try:
1505                     if hwid.index('FTDI')==0:
1506                         comPort=comport;
1507                         #print "Using FTDI port %s" % port
1508                 except:
1509                     #Do nothing.
1510                     a=1;
1511     sys.stderr.write("MSP430 Bootstrap Loader Version: %s\n" % VERSION)
1512
1513     try:
1514         opts, args = getopt.getopt(sys.argv[1:],
1515             "hc:P:wf:m:eEpvrg:UDudsxbITNB:S:V14",
1516             ["help", "comport=", "password=", "wait", "framesize=",
1517              "erasecycles=", "masserase", "erasecheck", "program",
1518              "verify", "reset", "go=", "unpatched", "debug",
1519              "upload=", "download=", "size=", "hex", "bin",
1520              "intelhex", "titext", "notimeout", "bsl=", "speed=",
1521              "bslversion", "f1x", "f2x", "f4x", "invert-reset", "invert-test",
1522              "swap-reset-test", "telos-latch", "telos-i2c", "telos", "telosb",
1523              "tmote","no-BSL-download", "force-BSL-download", "slow",
1524              "dumpivt", "dumpinfo", "fromweb",
1525              "goodfet40", "goodfet30", "goodfet20", "goodfet10",
1526              "z1",
1527              "nhbadge", "nhbadgeb", "goodfet"
1528             ]
1529         )
1530     except getopt.GetoptError:
1531         # print help information and exit:
1532         usage()
1533         sys.exit(2)
1534
1535     for o, a in opts:
1536         if o in ("-h", "--help"):
1537             usage()
1538             sys.exit()
1539         elif o in ("-c", "--comport"):
1540             try:
1541                 comPort = int(a)                    #try to convert decimal
1542             except ValueError:
1543                 comPort = a                         #take the string and let serial driver decide
1544         elif o in ("-P", "--password"):
1545             #extract password from file
1546             bsl.passwd = Memory(a).getMemrange(0xffe0, 0xffff)
1547         elif o in ("-w", "--wait"):
1548             wait = 1
1549         elif o in ("--dumpivt"):
1550             dumpivt=1;
1551         elif o in ("--dumpinfo"):
1552             dumpinfo=1;
1553         elif o in ("-f", "--framesize"):
1554             try:
1555                 maxData = int(a)                    #try to convert decimal
1556             except ValueError:
1557                 sys.stderr.write("framesize must be a valid number\n")
1558                 sys.exit(2)
1559             #Make sure that conditions for maxData are met:
1560             #( >= 16 and == n*16 and <= MAX_DATA_BYTES!)
1561             if maxData > BootStrapLoader.MAX_DATA_BYTES:
1562                 maxData = BootStrapLoader.MAX_DATA_BYTES
1563             elif maxData < 16:
1564                 maxData = 16
1565             bsl.maxData = maxData - (maxData % 16)
1566             sys.stderr.write( "Max. number of data bytes within one frame set to %i.\n" % maxData)
1567         elif o in ("-m", "--erasecycles"):
1568             try:
1569                 meraseCycles = int(a)               #try to convert decimal
1570             except ValueError:
1571                 sys.stderr.write("erasecycles must be a valid number\n")
1572                 sys.exit(2)
1573             #sanity check of value
1574             if meraseCycles < 1:
1575                 sys.stderr.write("erasecycles must be a positive number\n")
1576                 sys.exit(2)
1577             if meraseCycles > 20:
1578                 sys.stderr.write("warning: erasecycles set to a large number (>20): %d\n" % meraseCycles)
1579             sys.stderr.write( "Number of mass erase cycles set to %i.\n" % meraseCycles)
1580             bsl.meraseCycles = meraseCycles
1581         elif o in ("-e", "--masserase"):
1582             toinit.append(bsl.actionMassErase)        #Erase Flash
1583         elif o in ("-E", "--erasecheck"):
1584             toinit.append(bsl.actionEraseCheck)       #Erase Check (by file)
1585         elif o in ("-p", "--program"):
1586             todo.append(bsl.actionProgram)          #Program file
1587         elif o in ("--fromweb"):
1588             toinit.append(bsl.actionMassErase)        #Erase Flash
1589             todo.append(bsl.actionFromweb)          #Program GoodFET code
1590         elif o in ("-v", "--verify"):
1591             todo.append(bsl.actionVerify)           #Verify file
1592         elif o in ("-r", "--reset"):
1593             reset = 1
1594         elif o in ("-g", "--go"):
1595             try:
1596                 goaddr = int(a)                    #try to convert decimal
1597             except ValueError:
1598                 try:
1599                     goaddr = int(a[2:],16)         #try to convert hex
1600                 except ValueError:
1601                     sys.stderr.write("go address must be a valid number\n")
1602                     sys.exit(2)
1603             wait = 1
1604         elif o in ("-U", "--unpatched"):
1605             unpatched = 1
1606         elif o in ("-D", "--debug"):
1607             DEBUG = DEBUG + 1
1608         elif o in ("-u", "--upload"):
1609             try:
1610                 startaddr = int(a)                  #try to convert decimal
1611             except ValueError:
1612                 try:
1613                     startaddr = int(a,16)           #try to convert hex
1614                 except ValueError:
1615                     sys.stderr.write("upload address must be a valid number\n")
1616                     sys.exit(2)
1617         elif o in ("-s", "--size"):
1618             try:
1619                 size = int(a)
1620             except ValueError:
1621                 try:
1622                     size = int(a,16)
1623                 except ValueError:
1624                     sys.stderr.write("size must be a valid number\n")
1625                     sys.exit(2)
1626         elif o in ("-x", "--hex"):
1627             hexoutput = 1
1628         elif o in ("-b", "--bin"):
1629             hexoutput = 0
1630         elif o in ("-I", "--intelhex"):
1631             filetype = 0
1632         elif o in ("-T", "--titext"):
1633             filetype = 1
1634         elif o in ("-N", "--notimeout"):
1635             notimeout = 1
1636         elif o in ("-B", "--bsl"):
1637             bslrepl = Memory() #File to program
1638             bslrepl.loadFile(a)
1639         elif o in ("-V", "--bslversion"):
1640             todo.append(bsl.actionReadBSLVersion) #load replacement BSL as first item
1641         elif o in ("-S", "--speed"):
1642             try:
1643                 speed = int(a)                    #try to convert decimal
1644             except ValueError:
1645                 sys.stderr.write("speed must be decimal number\n")
1646                 sys.exit(2)
1647         elif o in ("-1", "--f1x"):
1648             bsl.cpu = F1x
1649         elif o in ("-2", "--f2x"):
1650             bsl.cpu = F2x
1651         elif o in ("-4", "--f4x"):
1652             bsl.cpu = F4x
1653         elif o in ("--invert-reset", ):
1654             bsl.invertRST = 1
1655         elif o in ("--invert-test", ):
1656             bsl.invertTEST = 1
1657         elif o in ("--swap-reset-test", ):
1658             bsl.swapRSTTEST = 1
1659         elif o in ("--telos-latch", ):
1660             bsl.telosLatch = 1
1661         elif o in ("--telos-i2c", ):
1662             bsl.telosI2C = 1
1663         elif o in ("--telos", ):
1664             bsl.invertRST = 1
1665             bsl.invertTEST = 1
1666             bsl.swapRSTTEST = 1
1667             bsl.telosLatch = 1
1668         elif o in ("--goodfet10", ):
1669             bsl.invertRST = 1
1670             bsl.invertTEST = 1
1671         elif o in ("--goodfet20", ):
1672             bsl.invertRST = 1
1673             bsl.invertTEST = 1
1674         elif o in ("--goodfet30", ):
1675             bsl.invertRST = 1
1676             bsl.invertTEST = 0
1677         elif o in ("--goodfet40", ):
1678             bsl.invertRST = 1
1679             bsl.invertTEST = 1
1680         elif o in ("--goodfet", ):
1681             bsl.invertRST = 1
1682             bsl.invertTEST = 1
1683         elif o in ("--nhbadge", "--nhbadgeb" ):
1684             bsl.invertRST = 1
1685             bsl.invertTEST = 1
1686         elif o in ("--telosb", ):
1687             bsl.swapRSTTEST = 1
1688             bsl.telosI2C = 1
1689             mayuseBSL = 0
1690             speed = 38400
1691         elif o in ("--tmote", ):
1692             bsl.swapRSTTEST = 1
1693             bsl.telosI2C = 1
1694             mayuseBSL = 0
1695             speed = 38400
1696         elif o in ("--z1", ):
1697             bsl.z1 = 1
1698             speed = 38400
1699         elif o in ("--no-BSL-download", ):
1700             mayuseBSL = 0
1701         elif o in ("--force-BSL-download", ):
1702             forceBSL = 1
1703         elif o in ("--slow", ):
1704             bsl.slowmode = 1
1705
1706     if len(args) == 0:
1707         sys.stderr.write("Use -h for help\n");
1708         sys.stderr.write("Use --fromweb to upgrade a GoodFET.\n")
1709     elif len(args) == 1:                            #a filename is given
1710         if not todo:                                #if there are no actions yet
1711             todo.extend([                           #add some useful actions...
1712                 bsl.actionProgram,
1713                 bsl.actionVerify,
1714             ])
1715         filename = args[0]
1716     else:                                           #number of args is wrong
1717         usage()
1718         sys.exit(2)
1719
1720     if DEBUG:   #debug infos
1721         sys.stderr.write("Debug level set to %d\n" % DEBUG)
1722         sys.stderr.write("Python version: %s\n" % sys.version)
1723
1724     #sanity check of options
1725     if notimeout and goaddr is not None and startaddr is not None:
1726         sys.stderr.write("Option --notimeout can not be used together with both --upload and --go\n")
1727         sys.exit(1)
1728
1729     if notimeout:
1730         sys.stderr.write("Warning: option --notimeout can cause improper function in some cases!\n")
1731         bsl.timeout = 0
1732
1733     if goaddr and reset:
1734         sys.stderr.write("Warning: option --reset ignored as --go is specified!\n")
1735         reset = 0
1736
1737     if startaddr and reset:
1738         sys.stderr.write("Warning: option --reset ignored as --upload is specified!\n")
1739         reset = 0
1740
1741     sys.stderr.flush()
1742     
1743     #prepare data to download
1744     bsl.data = Memory()                             #prepare downloaded data
1745     if filetype is not None:                        #if the filetype is given...
1746         if filename is None:
1747             raise ValueError("no filename but filetype specified")
1748         if filename == '-':                         #get data from stdin
1749             file = sys.stdin
1750         else:
1751             file = open(filename, "rb")             #or from a file
1752         if filetype == 0:                           #select load function
1753             bsl.data.loadIHex(file)                 #intel hex
1754         elif filetype == 1:
1755             bsl.data.loadTIText(file)               #TI's format
1756         else:
1757             raise ValueError("illegal filetype specified")
1758     else:                                           #no filetype given...
1759         if filename == '-':                         #for stdin:
1760             bsl.data.loadIHex(sys.stdin)            #assume intel hex
1761         elif filename:
1762             bsl.data.loadFile(filename)             #autodetect otherwise
1763
1764     if DEBUG > 3: sys.stderr.write("File: %r" % filename)
1765
1766     bsl.comInit(comPort)                            #init port
1767
1768     #initialization list
1769     if toinit:  #erase and erase check
1770         if DEBUG: sys.stderr.write("Preparing device ...\n")
1771         #bsl.actionStartBSL(usepatch=0, adjsp=0)     #no workarounds needed
1772         #if speed: bsl.actionChangeBaudrate(speed)   #change baud rate as fast as possible
1773         for f in toinit: f()
1774
1775     if todo or goaddr or startaddr:
1776         if DEBUG: sys.stderr.write("Actions ...\n")
1777         #connect to the BSL
1778         bsl.actionStartBSL(
1779             usepatch=not unpatched,
1780             replacementBSL=bslrepl,
1781             forceBSL=forceBSL,
1782             mayuseBSL=mayuseBSL,
1783             speed=speed,
1784         )
1785
1786     #work list
1787     if todo:
1788         if DEBUG > 0:       #debug
1789             #show a nice list of sheduled actions
1790             sys.stderr.write("TODO list:\n")
1791             for f in todo:
1792                 try:
1793                     sys.stderr.write("   %s\n" % f.func_name)
1794                 except AttributeError:
1795                     sys.stderr.write("   %r\n" % f)
1796         for f in todo: f()                          #work through todo list
1797
1798     if reset:                                       #reset device first if desired
1799         bsl.actionReset()
1800     if dumpivt:
1801         bsl.txPasswd(); #default pass
1802         data=bsl.uploadData(0xc00,1024);
1803         hex="";
1804         for c in data:
1805             hex+=("%02x "%ord(c));
1806         print hex;
1807     if dumpinfo:
1808         bsl.txPasswd(); #default pass
1809         data=bsl.uploadData(0x1000,256);
1810         hex="@1000\n";
1811         for c in data:
1812             hex+=("%02x "%ord(c));
1813         hex+="\nq\n";
1814         print hex;
1815     
1816     if goaddr is not None:                          #start user programm at specified address
1817         bsl.actionRun(goaddr)                       #load PC and execute
1818
1819     #upload datablock and output
1820     if startaddr is not None:
1821         if goaddr:                                  #if a program was started...
1822             #don't restart BSL but wait for the device to enter it itself
1823             sys.stderr.write("Waiting for device to reconnect for upload: ")
1824             sys.stderr.flush()
1825             bsl.txPasswd(bsl.passwd, wait=1)        #synchronize, try forever...
1826             data = bsl.uploadData(startaddr, size)  #upload data
1827         else:
1828             data = bsl.uploadData(startaddr, size)  #upload data
1829         if hexoutput:                               #depending on output format
1830             m = 0
1831             while m < len(data):                    #print a hex display
1832                 print hexify(startaddr+m, map(ord,data[m:m+16]))
1833                 m = m + 16
1834         else:
1835             sys.stdout.write(data)                  #binary output w/o newline!
1836         wait = 0    #wait makes no sense as after the upload the device is still in BSL
1837
1838     if wait:                                        #wait at the end if desired
1839         sys.stderr.write("Press <ENTER> ...\n")     #display a prompt
1840         sys.stderr.flush()
1841         raw_input()                                 #wait for newline
1842
1843     bsl.comDone()           #Release serial communication port
1844
1845 if __name__ == '__main__':
1846     try:
1847         main(1)
1848     except SystemExit:
1849         raise               #let pass exit() calls
1850     except KeyboardInterrupt:
1851         if DEBUG: raise     #show full trace in debug mode
1852         sys.stderr.write("user abort.\n")   #short messy in user mode
1853         sys.exit(1)         #set errorlevel for script usage
1854     except Exception, msg:  #every Exception is caught and displayed
1855         if DEBUG: raise     #show full trace in debug mode
1856         #sys.stderr.write("\nAn error occoured:\n%s\n" % msg) #short messy in user mode
1857         #sys.exit(1)         #set errorlevel for script usage
1858         main(0);