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