2 # Serial Bootstrap Loader software for the MSP430 embedded proccessor.
4 # (C) 2001-2003 Chris Liechti <cliechti@gmx.net>
5 # this is distributed under a free software license, see license-bsl.txt
7 # fixes from Colin Domoney
9 # based on the application note slas96b.pdf from Texas Instruments, Inc.,
11 # additional infos from slaa089a.pdf
13 # Forked by Travis Goodspeed <travis at tnbelt.com> for use with the GoodFET
16 import sys, time, string, cStringIO, struct
17 sys.path.append("/usr/lib/tinyos")
18 import serial, os, glob
20 #forked from TinyOS Telos version.
21 VERSION = string.split("Revision: 1.39-goodfet-8 ")[1]
23 DEBUG = 0 #disable debug messages by default
25 #copy of the patch file provided by TI
26 #this part is (C) by Texas Instruments
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
44 #These BSL's are (C) by TI. They come with the application note slaa089a
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
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
187 #cpu types for "change baudrate"
188 #use strings as ID so that they can be used in outputs too
196 0xf16c: F1x, #for GoodFET10 to '20
202 0xf26f: F2x, #for GoodFET20
207 0xf16c: "http://goodfet.sourceforge.net/dist/msp430x1612.hex",
208 0xf26f: "http://goodfet.sourceforge.net/dist/msp430x2618.hex",
211 class BSLException(Exception):
215 "lowlevel communication"
222 BSL_TXBLK = 0x12 #Transmit block to boot loader
223 BSL_RXBLK = 0x14 #Receive block from boot loader
224 BSL_ERASE = 0x16 #Erase one segment
225 BSL_MERAS = 0x18 #Erase complete FLASH memory
226 BSL_CHANGEBAUD = 0x20 #Change baudrate
227 BSL_LOADPC = 0x1A #Load PC and start execution
228 BSL_TXVERSION = 0x1E #Get BSL version
230 #Upper limit of address range that might be modified by
232 BSL_CRITICAL_ADDR = 0x0A00
241 QUERY_RESPONSE = 0x50
243 OPEN_CONNECTION = 0xC0
244 ACK_CONNECTION = 0x40
255 ERR_COM = "Unspecific error"
256 ERR_RX_NAK = "NAK received (wrong password?)"
257 #ERR_CMD_NOT_COMPLETED = "Command did not send ACK: indicates that it didn't complete correctly"
258 ERR_CMD_FAILED = "Command failed, is not defined or is not allowed"
259 ERR_BSL_SYNC = "Bootstrap loader synchronization error"
260 ERR_FRAME_NUMBER = "Frame sequence number error."
262 def calcChecksum(self, data, length):
263 """Calculates a checksum of "data"."""
266 for i in range(length/2):
267 checksum = checksum ^ (ord(data[i*2]) | (ord(data[i*2+1]) << 8)) #xor-ing
268 return 0xffff & (checksum ^ 0xffff) #inverting
270 def __init__(self, aTimeout = None, aProlongFactor = None):
271 """init bsl object, don't connect yet"""
273 self.timeout = self.DEFAULT_TIMEOUT
275 self.timeout = aTimeout
276 if aProlongFactor is None:
277 self.prolongFactor = self.DEFAULT_PROLONG
279 self.prolongFactor = aProlongFactor
281 #flags for inverted use of control pins
282 #used for some hardware
289 self.protocolMode = self.MODE_BSL
290 self.BSLMemAccessWarning = 0 #Default: no warning.
293 def comInit(self, port):
294 """Tries to open the serial port given and
295 initialises the port and variables.
296 The timeout and the number of allowed errors is multiplied by
297 'aProlongFactor' after transmission of a command to give
298 plenty of time to the micro controller to finish the command.
299 Returns zero if the function is successful."""
300 if DEBUG > 1: sys.stderr.write("* comInit()\n")
305 # Startup-Baudrate: 9600,8,E,1, 1s timeout
306 self.serialport = serial.Serial(
309 parity = serial.PARITY_EVEN,
310 timeout = self.timeout
312 if DEBUG: sys.stderr.write("using serial port %r\n" % self.serialport.portstr)
313 self.SetRSTpin() #enable power
314 self.SetTESTpin() #enable power
315 self.serialport.flushInput()
316 self.serialport.flushOutput()
319 """Closes the used serial port.
320 This function must be called at the end of a program,
321 otherwise the serial port might not be released and can not be
322 used in other programs.
323 Returns zero if the function is successful."""
324 if DEBUG > 1: sys.stderr.write("* comDone()")
325 self.SetRSTpin(1) #disable power
326 self.SetTESTpin(0) #disable power
327 self.serialport.close()
329 def comRxHeader(self):
330 """receive header and split data"""
331 if DEBUG > 1: sys.stderr.write("* comRxHeader()\n")
333 hdr = self.serialport.read(1)
334 if not hdr: raise BSLException("Timeout")
335 rxHeader = ord(hdr) & 0xf0;
336 rxNum = ord(hdr) & 0x0f;
338 if self.protocolMode == self.MODE_BSL:
342 if DEBUG > 1: sys.stderr.write("* comRxHeader() OK\n")
343 return rxHeader, rxNum
345 def comRxFrame(self, rxNum):
346 if DEBUG > 1: sys.stderr.write("* comRxFrame()\n")
347 rxFrame = chr(self.DATA_FRAME | rxNum)
349 if DEBUG > 2: sys.stderr.write(" comRxFrame() header...\n")
350 rxFramedata = self.serialport.read(3)
351 if len(rxFramedata) != 3: raise BSLException("Timeout")
352 rxFrame = rxFrame + rxFramedata
354 if DEBUG > 3: sys.stderr.write(" comRxFrame() check header...\n")
355 if rxFrame[1] == chr(0) and rxFrame[2] == rxFrame[3]: #Add. header info. correct?
356 rxLengthCRC = ord(rxFrame[2]) + 2 #Add CRC-Bytes to length
357 if DEBUG > 2: sys.stderr.write(" comRxFrame() receiving data, size: %s\n" % rxLengthCRC)
359 rxFramedata = self.serialport.read(rxLengthCRC)
360 if len(rxFramedata) != rxLengthCRC: raise BSLException("Timeout")
361 rxFrame = rxFrame + rxFramedata
362 #Check received frame:
363 if DEBUG > 3: sys.stderr.write(" comRxFrame() crc check\n")
364 #rxLength+4: Length with header but w/o CRC:
365 checksum = self.calcChecksum(rxFrame, ord(rxFrame[2]) + 4)
366 if rxFrame[ord(rxFrame[2])+4] == chr(0xff & checksum) and \
367 rxFrame[ord(rxFrame[2])+5] == chr(0xff & (checksum >> 8)): #Checksum correct?
368 #Frame received correctly (=> send next frame)
369 if DEBUG > 2: sys.stderr.write("* comRxFrame() OK\n")
372 if DEBUG: sys.stderr.write(" comRxFrame() Checksum wrong\n")
374 if DEBUG: sys.stderr.write(" comRxFrame() Header corrupt %r" % rxFrame)
375 raise BSLException(self.ERR_COM) #Frame has errors!
377 def comTxHeader(self, txHeader):
379 if DEBUG > 1: sys.stderr.write("* txHeader()\n")
380 self.serialport.write(txHeader)
382 def comTxRx(self, cmd, dataOut, length):
383 """Sends the command cmd with the data given in dataOut to the
384 microcontroller and expects either an acknowledge or a frame
385 with result from the microcontroller. The results are stored
386 in dataIn (if not a NULL pointer is passed).
387 In this routine all the necessary protocol stuff is handled.
388 Returns zero if the function was successful."""
389 if DEBUG > 1: sys.stderr.write("* comTxRx()\n")
394 dataOut = list(dataOut) #convert to a list for simpler data fill in
395 #Transmitting part ----------------------------------------
396 #Prepare data for transmit
397 if (length % 2) != 0:
398 #/* Fill with one byte to have even number of bytes to send */
399 if self.protocolMode == self.MODE_BSL:
400 dataOut.append(0xFF) #fill with 0xFF
402 dataOut.append(0) #fill with zero
404 txFrame = "%c%c%c%c" % (self.DATA_FRAME | self.seqNo, cmd, len(dataOut), len(dataOut))
406 self.reqNo = (self.seqNo + 1) % self.MAX_FRAME_COUNT
408 txFrame = txFrame + string.join(dataOut,'')
409 checksum = self.calcChecksum(txFrame, length + 4)
410 txFrame = txFrame + chr(checksum & 0xff)
411 txFrame = txFrame + chr((checksum >> 8) & 0xff)
413 accessAddr = (0x0212 + (checksum^0xffff)) & 0xfffe #0x0212: Address of wCHKSUM
414 if self.BSLMemAccessWarning and accessAddr < self.BSL_CRITICAL_ADDR:
415 sys.stderr.write("WARNING: This command might change data at address %04x or %04x!\n" % (accessAddr, accessAddr + 1))
417 self.serialport.flushInput() #clear receiving queue
418 #TODO: Check after each transmitted character,
419 #TODO: if microcontroller did send a character (probably a NAK!).
421 self.serialport.write(c)
422 if DEBUG > 3: sys.stderr.write("\ttx %02x" % ord(c))
423 #if self.serialport.inWaiting(): break #abort when BSL replies, probably NAK
425 if DEBUG > 1: sys.stderr.write( " comTxRx() transmit OK\n")
427 #Receiving part -------------------------------------------
428 rxHeader, rxNum = self.comRxHeader() #receive header
429 if DEBUG > 1: sys.stderr.write(" comTxRx() rxHeader=0x%02x, rxNum=%d, seqNo=%d, reqNo=%s\n" % (rxHeader, rxNum, self.seqNo, self.reqNo))
430 if rxHeader == self.DATA_ACK: #acknowledge/OK
431 if DEBUG > 2: sys.stderr.write(" comTxRx() DATA_ACK\n")
432 if rxNum == self.reqNo:
433 self.seqNo = self.reqNo
434 if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_ACK OK\n")
435 return #Acknowledge received correctly => next frame
436 raise BSLException(self.ERR_FRAME_NUMBER)
437 elif rxHeader == self.DATA_NAK: #not acknowledge/error
438 if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_NAK\n")
439 raise BSLException(self.ERR_RX_NAK)
440 elif rxHeader == self.DATA_FRAME: #receive data
441 if DEBUG > 2: sys.stderr.write("* comTxRx() DATA_FRAME\n")
442 if rxNum == self.reqNo:
443 rxFrame = self.comRxFrame(rxNum)
445 raise BSLException(self.ERR_FRAME_NUMBER)
446 elif rxHeader == self.CMD_FAILED: #Frame ok, but command failed.
447 if DEBUG > 2: sys.stderr.write("* comTxRx() CMD_FAILED\n")
448 raise BSLException(self.ERR_CMD_FAILED)
450 raise BSLException("Unknown header 0x%02x\nAre you downloading to RAM into an old device that requires the patch? Try option -U" % rxHeader)
452 def SetDTR(self, level, invert):
453 """Controls DTR pin (0: GND; 1: VCC; unless inverted flag is set)"""
455 self.serialport.setDTR(not level)
457 self.serialport.setDTR(level)
461 def SetRTS(self, level, invert):
462 """Controls RTS pin (0: GND; 1: VCC; unless inverted flag is set)"""
464 self.serialport.setRTS(not level)
466 self.serialport.setRTS(level)
470 def SetRSTpin(self, level=1):
471 """Controls RST/NMI pin (0: GND; 1: VCC; unless inverted flag is set)"""
473 self.SetRTS(level, self.invertRST)
475 self.SetDTR(level, self.invertRST)
477 def SetTESTpin(self, level=1):
478 """Controls TEST pin (inverted on board: 0: VCC; 1: GND; unless inverted flag is set)"""
480 self.SetDTR(level, self.invertTEST)
482 self.SetRTS(level, self.invertTEST)
484 def telosSetSCL(self, level):
485 self.serialport.setRTS(not level)
487 def telosSetSDA(self, level):
488 self.serialport.setDTR(not level)
490 def telosI2CStart(self):
495 def telosI2CStop(self):
500 def telosI2CWriteBit(self, bit):
502 self.telosSetSDA(bit)
508 def telosI2CWriteByte(self, byte):
509 self.telosI2CWriteBit( byte & 0x80 );
510 self.telosI2CWriteBit( byte & 0x40 );
511 self.telosI2CWriteBit( byte & 0x20 );
512 self.telosI2CWriteBit( byte & 0x10 );
513 self.telosI2CWriteBit( byte & 0x08 );
514 self.telosI2CWriteBit( byte & 0x04 );
515 self.telosI2CWriteBit( byte & 0x02 );
516 self.telosI2CWriteBit( byte & 0x01 );
517 self.telosI2CWriteBit( 0 ); # "acknowledge"
519 def telosI2CWriteCmd(self, addr, cmdbyte):
521 self.telosI2CWriteByte( 0x90 | (addr << 1) )
522 self.telosI2CWriteByte( cmdbyte )
525 def telosBReset(self,invokeBSL=0):
527 # "BSL entry sequence at dedicated JTAG pins"
528 # rst !s0: 0 0 0 0 1 1
529 # tck !s1: 1 0 1 0 0 1
532 # "BSL entry sequence at shared JTAG pins"
533 # rst !s0: 0 0 0 0 1 1
534 # tck !s1: 0 1 0 1 1 0
538 self.telosI2CWriteCmd(0,1)
539 self.telosI2CWriteCmd(0,3)
540 self.telosI2CWriteCmd(0,1)
541 self.telosI2CWriteCmd(0,3)
542 self.telosI2CWriteCmd(0,2)
543 self.telosI2CWriteCmd(0,0)
545 self.telosI2CWriteCmd(0,3)
546 self.telosI2CWriteCmd(0,2)
547 self.telosI2CWriteCmd(0,0)
548 time.sleep(0.250) #give MSP430's oscillator time to stabilize
549 self.serialport.flushInput() #clear buffers
551 def bslReset(self, invokeBSL=0):
552 """Applies BSL entry sequence on RST/NMI and TEST/VPP pins
554 invokeBSL = 1: complete sequence
555 invokeBSL = 0: only RST/NMI pin accessed
557 RST is inverted twice on boot loader hardware
558 TEST is inverted (only once)
559 Need positive voltage on DTR, RTS for power-supply of hardware"""
561 self.telosBReset(invokeBSL)
564 if DEBUG > 1: sys.stderr.write("* bslReset(invokeBSL=%s)\n" % invokeBSL)
565 self.SetRSTpin(1) #power suply
566 self.SetTESTpin(1) #power suply
567 time.sleep(0.250) #charge capacitor on boot loader hardware
574 self.SetRSTpin(0) #RST pin: GND
576 self.SetTESTpin(1) #TEST pin: GND
577 self.SetTESTpin(0) #TEST pin: Vcc
578 self.SetTESTpin(1) #TEST pin: GND
579 self.SetTESTpin(0) #TEST pin: Vcc
580 self.SetRSTpin (1) #RST pin: Vcc
581 self.SetTESTpin(1) #TEST pin: GND
583 self.SetRSTpin(1) #RST pin: Vcc
584 time.sleep(0.250) #give MSP430's oscillator time to stabilize
586 self.serialport.flushInput() #clear buffers
588 def bslSync(self,wait=0):
589 """Transmits Synchronization character and expects to receive Acknowledge character
590 if wait is 0 it must work the first time. otherwise if wait is 1
591 it is retried (forever).
593 loopcnt = 5 #Max. tries to get synchronization
595 if DEBUG > 1: sys.stderr.write("* bslSync(wait=%d)\n" % wait)
596 while wait or loopcnt:
597 loopcnt = loopcnt - 1 #count down tries
598 self.serialport.flushInput() #clear input, in case a prog is running
600 self.serialport.write(chr(self.BSL_SYNC)) #Send synchronization byte
601 c = self.serialport.read(1) #read answer
602 if c == chr(self.DATA_ACK): #ACk
603 if DEBUG > 1: sys.stderr.write(" bslSync() OK\n")
604 return #Sync. successful
608 sys.stderr.write(" bslSync() timeout, retry ...\n")
610 #nmi may have caused the first reset to be ignored, try again
615 sys.stderr.write(" bslSync() timeout, retry ...\n")
618 sys.stderr.write(" bslSync() timeout\n")
620 if DEBUG > 1: sys.stderr.write(" bslSync() failed (0x%02x), retry ...\n" % ord(c))
622 raise BSLException(self.ERR_BSL_SYNC) #Sync. failed
624 def bslTxRx(self, cmd, addr, length = 0, blkout = None, wait=0):
625 """Transmits a command (cmd) with its parameters:
626 start-address (addr), length (len) and additional
627 data (blkout) to boot loader.
628 wait specified if the bsl sync should be tried once or
630 Parameters return by boot loader are passed via blkin.
632 if DEBUG > 1: sys.stderr.write("* bslTxRx()\n")
634 if cmd == self.BSL_TXBLK:
635 #Align to even start address
637 addr = addr - 1 #Decrement address and
638 blkout = chr(0xFF) + blkOut #fill first byte of blkout with 0xFF
640 #Make sure that len is even
641 if (length % 2) != 0:
642 blkout = blkout + chr(0xFF) #Inc. len and fill last byte of blkout with 0xFF
645 elif cmd == self.BSL_RXBLK:
646 #Align to even start address
648 addr = addr - 1 #Decrement address but
649 length = length + 1 #request an additional byte
650 #Make sure that len is even
651 if (length % 2) != 0:
654 #if cmd == self.BSL_TXBLK or cmd == self.BSL_TXPWORD:
657 #Add necessary information data to frame
658 dataOut = struct.pack("<HH", addr, length)
660 if blkout: #Copy data out of blkout into frame
661 dataOut = dataOut + blkout
663 self.bslSync(wait) #synchronize BSL
664 rxFrame = self.comTxRx(cmd, dataOut, len(dataOut)) #Send frame
665 if rxFrame: #test answer
666 return rxFrame[4:] #return only data w/o [hdr,null,len,len]
672 """store a string with memory contents along with its startaddress"""
673 def __init__(self, startaddress = 0, data=None):
678 self.startaddress = startaddress
680 def __getitem__(self, index):
681 return self.data[index]
684 return len(self.data)
687 return "Segment(startaddress = 0x%04x, data=%r)" % (self.startaddress, self.data)
690 """represent memory contents. with functions to load files"""
691 def __init__(self, filename=None):
694 self.filename = filename
695 self.loadFile(filename)
697 def append(self, seg):
698 self.segments.append(seg)
700 def __getitem__(self, index):
701 return self.segments[index]
704 return len(self.segments)
706 def loadIHex(self, file):
707 """load data from a (opened) file in Intel-HEX format"""
711 lines = file.readlines()
713 if l[0] != ':': raise BSLException("File Format Error\n")
714 l = l.strip() #fix CR-LF issues...
715 length = int(l[1:3],16)
716 address = int(l[3:7],16)
717 type = int(l[7:9],16)
718 check = int(l[-2:],16)
720 if currentAddr != address:
722 self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
723 startAddr = currentAddr = address
725 for i in range(length):
726 segmentdata.append( chr(int(l[9+2*i:11+2*i],16)) )
727 currentAddr = length + currentAddr
728 elif type in (0x01, 0x02, 0x03, 0x04, 0x05):
731 sys.stderr.write("Ignored unknown field (type 0x%02x) in ihex file.\n" % type)
733 self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
735 def loadTIText(self, file):
736 """load data from a (opened) file in TI-Text format"""
740 #Convert data for MSP430, TXT-File is parsed line by line
746 if l[0] == 'q': break
747 elif l[0] == '@': #if @ => new address => send frame and set new addr.
748 #create a new segment
750 self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
751 startAddr = int(l[1:],16)
754 for i in string.split(l):
755 segmentdata.append(chr(int(i,16)))
757 self.segments.append( Segment(startAddr, string.join(segmentdata,'')) )
759 def loadELF(self, file):
760 """load data from a (opened) file in ELF object format.
761 File must be seekable"""
763 obj = elf.ELFObject()
765 if obj.e_type != elf.ELFObject.ET_EXEC:
766 raise Exception("No executable")
767 for section in obj.getSections():
769 sys.stderr.write("ELF section %s at 0x%04x %d bytes\n" % (section.name, section.lma, len(section.data)))
770 if len(section.data):
771 self.segments.append( Segment(section.lma, section.data) )
773 def loadFile(self, filename):
774 """fill memory with the contents of a file. file type is determined from extension"""
775 #TODO: do a contents based detection
776 if filename[-4:].lower() == '.txt':
777 self.loadTIText(open(filename, "rb"))
778 elif filename[-4:].lower() in ('.a43', '.hex'):
779 self.loadIHex(open(filename, "rb"))
781 self.loadELF(open(filename, "rb"))
783 def getMemrange(self, fromadr, toadr):
784 """get a range of bytes from the memory. unavailable values are filled with 0xff."""
786 toadr = toadr + 1 #python indxes are excluding end, so include it
787 while fromadr < toadr:
788 #print "fromto: %04x %04x" % (fromadr, toadr)
789 for seg in self.segments:
791 segend = seg.startaddress + len(seg.data)
792 if seg.startaddress <= fromadr and fromadr < segend:
793 #print "startok 0x%04x %d" % (seg.startaddress, len(seg.data))
794 #print ("0x%04x "*3) % (segend, fromadr, toadr)
795 if toadr > segend: #not all data in segment
796 #print "out of segment"
797 catchlength = segend-fromadr
799 catchlength = toadr-fromadr
802 res = res + seg.data[fromadr-seg.startaddress : fromadr-seg.startaddress+catchlength]
803 fromadr = fromadr + catchlength #adjust start
804 if len(res) >= toadr-fromadr:
808 fromadr = fromadr + 1 #adjust start
810 #print "res: %r" % res
814 class BootStrapLoader(LowLevel):
815 """higher level Bootstrap Loader functions."""
817 ERR_VERIFY_FAILED = "Error: verification failed"
818 ERR_ERASE_CHECK_FAILED = "Error: erase check failed"
820 ACTION_PROGRAM = 0x01 #Mask: program data
821 ACTION_VERIFY = 0x02 #Mask: verify data
822 ACTION_ERASE_CHECK = 0x04 #Mask: erase check
824 #Max. bytes sent within one frame if parsing a TI TXT file.
825 #( >= 16 and == n*16 and <= MAX_DATA_BYTES!)
829 def __init__(self, *args, **kargs):
830 LowLevel.__init__(self, *args, **kargs)
832 self.meraseCycles = 1
833 self.patchRequired = 0
838 self.maxData = self.MAXDATA
842 def preparePatch(self):
843 """prepare to download patch"""
844 if DEBUG > 1: sys.stderr.write("* preparePatch()\n")
847 #Load PC with 0x0220.
848 #This will invoke the patched bootstrap loader subroutines.
849 self.bslTxRx(self.BSL_LOADPC, #Command: Load PC
850 0x0220) #Address to load into PC
851 self.BSLMemAccessWarning = 0 #Error is removed within workaround code
855 """setup after the patch is loaded"""
856 if DEBUG > 1: sys.stderr.write("* postPatch()\n")
858 self.BSLMemAccessWarning = 1 #Turn warning back on.
861 def verifyBlk(self, addr, blkout, action):
862 """verify memory against data or 0xff"""
863 if DEBUG > 1: sys.stderr.write("* verifyBlk()\n")
865 if action & self.ACTION_VERIFY or action & self.ACTION_ERASE_CHECK:
866 if DEBUG: sys.stderr.write(" Check starting at 0x%04x, %d bytes ... \n" % (addr, len(blkout)))
869 blkin = self.bslTxRx(self.BSL_RXBLK, addr, len(blkout))
872 for i in range(len(blkout)):
873 if action & self.ACTION_VERIFY:
874 #Compare data in blkout and blkin
875 if blkin[i] != blkout[i]:
876 sys.stderr.write("Verification failed at 0x%04x (0x%02x, 0x%02x)\n" % (addr+i, ord(blkin[i]), ord(blkout[i])))
878 raise BSLException(self.ERR_VERIFY_FAILED) #Verify failed!
880 elif action & self.ACTION_ERASE_CHECK:
881 #Compare data in blkin with erase pattern
882 if blkin[i] != chr(0xff):
883 sys.stderr.write("Erase Check failed at 0x%04x (0x%02x)\n" % (addr+i, ord(blkin[i])))
885 raise BSLException(self.ERR_ERASE_CHECK_FAILED) #Erase Check failed!
887 def readBlk(self,adr,len):
888 """Read a block of memory."""
889 blkin = self.bslTxRx(self.BSL_RXBLK, addr, len(blkout))
891 def programBlk(self, addr, blkout, action):
892 """program a memory block"""
893 if DEBUG > 1: sys.stderr.write("* programBlk()\n")
895 #Check, if specified range is erased
896 self.verifyBlk(addr, blkout, action & self.ACTION_ERASE_CHECK)
898 if action & self.ACTION_PROGRAM:
899 if DEBUG: sys.stderr.write(" Program starting at 0x%04x, %i bytes ...\n" % (addr, len(blkout)))
902 self.bslTxRx(self.BSL_TXBLK, addr, len(blkout), blkout)
906 self.verifyBlk(addr, blkout, action & self.ACTION_VERIFY)
909 #list of tuples or lists:
910 #segements = [ (addr1, [d0,d1,d2,...]), (addr2, [e0,e1,e2,...])]
911 def programData(self, segments, action):
912 """programm or verify data"""
913 if DEBUG > 1: sys.stderr.write("* programData()\n")
915 currentAddr = seg.startaddress
917 while pstart<len(seg.data):
918 length = self.MAXDATA
919 if pstart+length > len(seg.data):
920 length = len(seg.data) - pstart
921 self.programBlk(currentAddr, seg.data[pstart:pstart+length], action)
922 pstart = pstart + length
923 currentAddr = currentAddr + length
924 self.byteCtr = self.byteCtr + length #total sum
926 def uploadData(self, startaddress, size, wait=0):
927 """upload a datablock"""
928 if DEBUG > 1: sys.stderr.write("* uploadData()\n")
932 length = self.maxData
933 if pstart+length > size:
934 length = size - pstart
935 data = data + self.bslTxRx(self.BSL_RXBLK,
938 wait=wait)[:-2] #cut away checksum
939 pstart = pstart + length
942 def txPasswd(self, passwd=None, wait=0):
943 """transmit password, default if None is given."""
944 if DEBUG > 1: sys.stderr.write("* txPassword(%r)\n" % passwd)
946 #Send "standard" password to get access to protected functions.
947 sys.stderr.write("Transmit default password ...\n")
949 #Flash is completely erased, the contents of all Flash cells is 0xff
950 passwd = chr(0xff)*32
952 #sanity check of password
953 if len(passwd) != 32:
954 raise ValueError, "password has wrong length (%d)\n" % len(passwd)
955 sys.stderr.write('Transmit password ...\n')
958 self.bslTxRx(self.BSL_TXPWORD, #Command: Transmit Password
959 0xffe0, #Address of interupt vectors
960 0x0020, #Number of bytes
962 wait=wait) #if wait is 1, try to sync forever
965 #-----------------------------------------------------------------
967 def actionMassErase(self):
968 """Erase the flash memory completely (with mass erase command)"""
969 sys.stderr.write("Mass Erase...\n")
971 self.bslReset(1) #Invoke the boot loader.
972 for i in range(self.meraseCycles):
973 if i == 1: sys.stderr.write("Additional Mass Erase Cycles...\n")
974 self.bslTxRx(self.BSL_MERAS, #Command: Mass Erase
975 0xff00, #Any address within flash memory.
976 0xa506) #Required setting for mass erase!
977 self.passwd = None #No password file required!
978 #print "Mass Erase complete"
979 #Transmit password to get access to protected BSL functions.
982 def actionStartBSL(self, usepatch=1, adjsp=1, replacementBSL=None, forceBSL=0, mayuseBSL=0, speed=None, bslreset=1):
983 """start BSL, download patch if desired and needed, adjust SP if desired"""
984 sys.stderr.write("Invoking BSL...\n")
987 self.bslReset(1) #Invoke the boot loader.
988 self.txPasswd(self.passwd) #transmit password
990 #Read actual bootstrap loader version.
991 #sys.stderr.write("Reading BSL version ...\n")
992 blkin = self.bslTxRx(self.BSL_RXBLK, #Command: Read/Receive Block
993 0x0ff0, #Start address
994 16) #No. of bytes to read
995 dev_id, bslVerHi, bslVerLo = struct.unpack(">H8xBB4x", blkin[:-2]) #cut away checksum and extract data
999 if self.cpu is None: #cpy type forced?
1000 if deviceids.has_key(dev_id):
1001 self.cpu = deviceids[dev_id] #try to autodectect CPU type
1004 sys.stderr.write("Autodetect successful: %04x -> %s\n" % (dev_id, self.cpu))
1006 sys.stderr.write("Autodetect failed! Unkown ID: %04x. Trying to continue anyway.\n" % dev_id)
1007 self.cpu = F1x #assume something and try anyway..
1009 sys.stderr.write("Current bootstrap loader version: %x.%x (Device ID: %04x)\n" % (bslVerHi, bslVerLo, dev_id))
1011 self.bslVer = (bslVerHi << 8) | bslVerLo
1013 if self.bslVer <= 0x0110: #check if patch is needed
1014 self.BSLMemAccessWarning = 1
1016 self.BSLMemAccessWarning = 0 #Fixed in newer versions of BSL.
1018 if self.bslVer <= 0x0130 and adjsp:
1019 #only do this on BSL where it's needed to prevent
1020 #malfunction with F4xx devices/ newer ROM-BSLs
1022 #Execute function within bootstrap loader
1023 #to prepare stack pointer for the following patch.
1024 #This function will lock the protected functions again.
1025 sys.stderr.write("Adjust SP. Load PC with 0x0C22 ...\n")
1026 self.bslTxRx(self.BSL_LOADPC, #Command: Load PC
1027 0x0C22) #Address to load into PC
1028 #Re-send password to re-gain access to protected functions.
1029 self.txPasswd(self.passwd)
1031 #get internal BSL replacement if needed or forced by the user
1032 #required if speed is set but an old BSL is in the device
1033 #if a BSL is given by the user, that one is used and not the internal one
1034 if ((mayuseBSL and speed and self.bslVer < 0x0150) or forceBSL) and replacementBSL is None:
1035 replacementBSL = Memory() #File to program
1038 sys.stderr.write("Using built in BSL replacement for F4x devices\n")
1040 replacementBSL.loadTIText(cStringIO.StringIO(F4X_BSL)) #parse embedded BSL
1043 sys.stderr.write("Using built in BSL replacement for F1x devices\n")
1045 replacementBSL.loadTIText(cStringIO.StringIO(F1X_BSL)) #parse embedded BSL
1047 #now download the new BSL, if allowed and needed (version lower than the
1048 #the replacement) or forced
1049 if replacementBSL is not None:
1050 self.actionDownloadBSL(replacementBSL)
1052 #debug message with the real BSL version in use (may have changed after replacement BSL)
1054 sys.stderr.write("Current bootstrap loader version: 0x%04x\n" % (self.bslVer,))
1057 #now apply workarounds or patches if BSL in use requires that
1058 if self.bslVer <= 0x0110: #check if patch is needed
1059 if usepatch: #test if patch is desired
1060 sys.stderr.write("Patch for flash programming required!\n")
1061 self.patchRequired = 1
1063 sys.stderr.write("Load and verify patch ...\n")
1065 #Programming and verification is done in one pass.
1066 #The patch file is only read and parsed once.
1067 segments = Memory() #data to program
1068 segments.loadTIText(cStringIO.StringIO(PATCH)) #parse embedded patch
1070 self.programData(segments, self.ACTION_PROGRAM | self.ACTION_VERIFY)
1071 self.patchLoaded = 1
1074 sys.stderr.write("Device needs patch, but not applied (usepatch is false).\n") #message if not patched
1076 #should the baudrate be changed?
1077 if speed is not None:
1078 self.actionChangeBaudrate(speed) #change baudrate
1080 def actionDownloadBSL(self, bslsegments):
1081 sys.stderr.write("Load new BSL into RAM...\n")
1083 self.programData(bslsegments, self.ACTION_PROGRAM)
1084 sys.stderr.write("Verify new BSL...\n")
1086 self.programData(bslsegments, self.ACTION_VERIFY) #File to verify
1088 #Read startvector of bootstrap loader
1089 #blkin = self.bslTxRx(self.BSL_RXBLK, 0x0300, 2)
1090 #blkin = self.bslTxRx(self.BSL_RXBLK, 0x0220, 2)
1091 blkin = self.bslTxRx(self.BSL_RXBLK, bslsegments[0].startaddress, 2)
1092 startaddr = struct.unpack("<H", blkin[:2])[0]
1094 sys.stderr.write("Starting new BSL at 0x%04x...\n" % startaddr)
1096 self.bslTxRx(self.BSL_LOADPC, #Command: Load PC
1097 startaddr) #Address to load into PC
1099 #BSL-Bugs should be fixed within "new" BSL
1100 self.BSLMemAccessWarning = 0
1101 self.patchRequired = 0
1102 self.patchLoaded = 0
1104 #Re-send password to re-gain access to protected functions.
1105 self.txPasswd(self.passwd)
1107 #update version info
1108 #verison only valid for the internal ones, but it also makes sure
1109 #that the patches are not applied if the user d/ls one
1110 self.bslVer = 0x0150
1112 def actionEraseCheck(self):
1113 """check the erasure of required flash cells."""
1114 sys.stderr.write("Erase Check by file ...\n")
1116 if self.data is not None:
1117 self.programData(self.data, self.ACTION_ERASE_CHECK)
1119 raise BSLException, "cannot do erase check against data with not knowing the actual data"
1121 def actionProgram(self):
1122 """program data into flash memory."""
1123 if self.data is not None:
1124 sys.stderr.write("Program ...\n")
1126 self.programData(self.data, self.ACTION_PROGRAM)
1127 sys.stderr.write("%i bytes programmed.\n" % self.byteCtr)
1130 raise BSLException, "programming without data not possible"
1131 def actionFromweb(self):
1132 """Grab GoodFET firmware from the web, then flash it."""
1133 print "%x" % self.dev_id;
1134 print "%s" % firmware[self.dev_id];
1136 os.system("curl %s >%s" % (firmware[self.dev_id],fn))
1139 #fw.loadIhex(open(fn,"rb"));
1141 sys.stderr.write("Program ...\n")
1143 self.programData(fw, self.ACTION_PROGRAM | self.ACTION_VERIFY)
1144 sys.stderr.write("%i bytes programmed.\n" % self.byteCtr)
1147 def actionVerify(self):
1148 """Verify programmed data"""
1149 if self.data is not None:
1150 sys.stderr.write("Verify ...\n")
1152 self.programData(self.data, self.ACTION_VERIFY)
1154 raise BSLException, "verify without data not possible"
1156 def actionReset(self):
1157 """perform a reset, start user programm"""
1158 sys.stderr.write("Reset device ...\n")
1160 self.bslReset(0) #only reset
1162 def actionRun(self, address=0x220):
1163 """start program at specified address"""
1164 sys.stderr.write("Load PC with 0x%04x ...\n" % address)
1166 self.bslTxRx(self.BSL_LOADPC, #Command: Load PC
1167 address) #Address to load into PC
1169 #table with values from slaa089a.pdf
1172 9600:[0x8580, 0x0000],
1173 19200:[0x86e0, 0x0001],
1174 38400:[0x87e0, 0x0002],
1177 9600:[0x8580, 0x0000],
1178 19200:[0x8B00, 0x0001],
1179 38400:[0x8C80, 0x0002],
1182 9600:[0x9800, 0x0000],
1183 19200:[0xb000, 0x0001],
1184 38400:[0xc800, 0x0002],
1187 def actionChangeBaudrate(self, baudrate=9600):
1188 """change baudrate. first the command is sent, then the comm
1189 port is reprogrammed. only possible with newer MSP430-BSL versions.
1190 (ROM >=1.6, downloadable >=1.5)"""
1192 baudconfigs = self.bauratetable[self.cpu]
1194 raise ValueError, "unknown CPU type %s, can't switch baudrate" % self.cpu
1196 a,l = baudconfigs[baudrate]
1198 raise ValueError, "baudrate not valid. valid values are %r" % baudconfigs.keys()
1200 sys.stderr.write("Changing baudrate to %d ...\n" % baudrate)
1202 self.bslTxRx(self.BSL_CHANGEBAUD, #Command: change baudrate
1203 a, l) #args are coded in adr and len
1204 time.sleep(0.010) #recomended delay
1205 self.serialport.setBaudrate(baudrate)
1207 def actionReadBSLVersion(self):
1208 """informational output of BSL version number.
1209 (newer MSP430-BSLs only)"""
1210 ans = self.bslTxRx(self.BSL_TXVERSION, 0) #Command: receive version info
1211 #the following values are in big endian style!!!
1212 family_type, bsl_version = struct.unpack(">H8xH4x", ans[:-2]) #cut away checksum and extract data
1213 print "Device Type: 0x%04x\nBSL version: 0x%04x\n" % (family_type, bsl_version)
1217 """print some help message"""
1218 sys.stderr.write("""
1219 USAGE: %s [options] [file]
1222 If "-" is specified as file the data is read from the stdinput.
1223 A file ending with ".txt" is considered to be in TIText format,
1224 '.a43' and '.hex' as IntelHex and all other filenames are
1225 considered as ELF files.
1228 -h, --help Show this help screen.
1229 -c, --comport=port Specify the communication port to be used.
1234 -P, --password=file Specify a file with the interrupt vectors that
1235 are used as password. This can be any file that
1236 has previously been used to program the device.
1237 (e.g. -P INT_VECT.TXT).
1238 -f, --framesize=num Max. number of data bytes within one transmitted
1239 frame (16 to 240 in steps of 16) (e.g. -f 240).
1240 -m, --erasecycles=num Number of mass erase cycles (default is 1). Some
1241 old F149 devices need additional erase cycles.
1242 On newer devices it is no longer needed. (e.g. for
1244 -U, --unpatched Do not download the BSL patch, even when it is
1245 needed. This is used when a program is downloaded
1246 into RAM and executed from there (and where flash
1247 programming is not needed.)
1248 -D, --debug Increase level of debug messages. This won't be
1249 very useful for the average user...
1250 -I, --intelhex Force fileformat to IntelHex
1251 -T, --titext Force fileformat to be TIText
1252 -N, --notimeout Don't use timeout on serial port (use with care)
1253 -B, --bsl=bsl.txt Load and use new BSL from the TI Text file
1254 -S, --speed=baud Reconfigure speed, only possible with newer
1255 MSP403-BSL versions (>1.5, read slaa089a.pdf for
1256 details). If the --bsl option is not used, an
1257 internal BSL replacement will be loaded.
1258 Needs a target with at least 2kB RAM!
1259 Possible values are 9600, 19200, 38400
1261 -1, --f1x Specify CPU family, in case autodetect fails
1262 -2, --f2x Specify CPU family, in case autodetect fails
1263 -4, --f4x Specify CPU family, in case autodetect fails
1264 --F1x and --f2x are only needed when the "change
1265 baudrate" feature is used and the autodetect feature
1266 fails. If the device ID that is uploaded is known, it
1267 has precedence to the command line option.
1268 --invert-reset Invert signal on RST pin (used for some BSL hardware)
1269 --invert-test Invert signal on TEST/TCK pin (used for some BSL
1271 --swap-reset-test Swap the RST and TEST pins (used for some BSL hardware)
1272 --telos-latch Special twiddle in BSL reset for Telos hardware
1273 --telos-i2c DTR/RTS map via an I2C switch to TCK/RST in Telos Rev.B
1274 --telos Implies options --invert-reset, --invert-test,
1275 --swap-reset-test, and --telos-latch
1276 --telosb Implies options --swap-reset-test, --telos-i2c,
1277 --no-BSL-download, and --speed=38400
1278 --tmote Identical operation to --telosb
1279 --no-BSL-download Do not download replacement BSL (disable automatic)
1280 --force-BSL-download Download replacement BSL even if not needed (the one
1281 in the device would have the required features)
1282 --slow Add delays when operating the conrol pins. Useful if
1283 the pins/circuit has high capacitance.
1285 Program Flow Specifiers:
1286 -e, --masserase Mass Erase (clear all flash memory)
1287 -E, --erasecheck Erase Check by file
1288 -p, --program Program file
1289 -v, --verify Verify by file
1291 The order of the above options matters! The table is ordered by normal
1292 execution order. For the options "Epv" a file must be specified.
1293 Program flow specifiers default to "pvr" if a file is given.
1294 Don't forget to specify "e" or "eE" when programming flash!
1297 -u, --upload=addr Upload a datablock (see also: -s).
1298 -s, --size=num Size of the data block do upload. (Default is 2)
1299 -x, --hex Show a hexadecimal display of the uploaded data.
1301 -b, --bin Get binary uploaded data. This can be used
1302 to redirect the output into a file.
1305 -g, --go=address Start programm execution at specified address.
1306 This implies option --wait.
1307 -r, --reset Reset connected MSP430. Starts application.
1308 This is a normal device reset and will start
1309 the programm that is specified in the reset
1310 vector. (see also -g)
1311 -w, --wait Wait for <ENTER> before closing serial port.
1313 If it says "NAK received" it's probably because you specified no or a
1315 """ % (sys.argv[0], VERSION))
1317 #add some arguments to a function, but don't call it yet, instead return
1318 #a wrapper object for later invocation
1320 """create a callable with some arguments specified in advance"""
1321 def __init__(self, fun, *args, **kwargs):
1323 self.pending = args[:]
1324 self.kwargs = kwargs.copy()
1326 def __call__(self, *args, **kwargs):
1327 if kwargs and self.kwargs:
1328 kw = self.kwargs.copy()
1331 kw = kwargs or self.kwargs
1332 return apply(self.fun, self.pending + args, kw)
1335 #first try if it a function
1337 return "curry(%s, %r, %r)" % (self.fun.func_name, self.pending, self.kwargs)
1338 except AttributeError:
1339 #fallback for callable classes
1340 return "curry(%s, %r, %r)" % (self.fun, self.pending, self.kwargs)
1342 def hexify(line, bytes, width=16):
1343 return '%04x %s%s %s' % (
1345 ('%02x '*len(bytes)) % tuple(bytes),
1346 ' '* (width-len(bytes)),
1347 ('%c'*len(bytes)) % tuple(map(lambda x: (x>=32 and x<127) and x or ord('.'), bytes))
1356 comPort = None #Default setting.
1360 wait = 0 #wait at the end
1362 bsl = BootStrapLoader()
1378 if comPort is None and os.environ.get("GOODFET")!=None:
1379 glob_list = glob.glob(os.environ.get("GOODFET"));
1380 if len(glob_list) > 0:
1381 comPort = glob_list[0];
1383 glob_list = glob.glob("/dev/tty.usbserial*");
1384 if len(glob_list) > 0:
1385 comPort = glob_list[0];
1387 glob_list = glob.glob("/dev/ttyUSB*");
1388 if len(glob_list) > 0:
1389 comPort = glob_list[0];
1392 sys.stderr.write("MSP430 Bootstrap Loader Version: %s\n" % VERSION)
1395 opts, args = getopt.getopt(sys.argv[1:],
1396 "hc:P:wf:m:eEpvrg:UDudsxbITNB:S:V14",
1397 ["help", "comport=", "password=", "wait", "framesize=",
1398 "erasecycles=", "masserase", "erasecheck", "program",
1399 "verify", "reset", "go=", "unpatched", "debug",
1400 "upload=", "download=", "size=", "hex", "bin",
1401 "intelhex", "titext", "notimeout", "bsl=", "speed=",
1402 "bslversion", "f1x", "f2x", "f4x", "invert-reset", "invert-test",
1403 "swap-reset-test", "telos-latch", "telos-i2c", "telos", "telosb",
1404 "tmote","no-BSL-download", "force-BSL-download", "slow",
1405 "dumpivt", "dumpinfo", "fromweb"]
1407 except getopt.GetoptError:
1408 # print help information and exit:
1413 if o in ("-h", "--help"):
1416 elif o in ("-c", "--comport"):
1418 comPort = int(a) #try to convert decimal
1420 comPort = a #take the string and let serial driver decide
1421 elif o in ("-P", "--password"):
1422 #extract password from file
1423 bsl.passwd = Memory(a).getMemrange(0xffe0, 0xffff)
1424 elif o in ("-w", "--wait"):
1426 elif o in ("--dumpivt"):
1428 elif o in ("--dumpinfo"):
1430 elif o in ("-f", "--framesize"):
1432 maxData = int(a) #try to convert decimal
1434 sys.stderr.write("framesize must be a valid number\n")
1436 #Make sure that conditions for maxData are met:
1437 #( >= 16 and == n*16 and <= MAX_DATA_BYTES!)
1438 if maxData > BootStrapLoader.MAX_DATA_BYTES:
1439 maxData = BootStrapLoader.MAX_DATA_BYTES
1442 bsl.maxData = maxData - (maxData % 16)
1443 sys.stderr.write( "Max. number of data bytes within one frame set to %i.\n" % maxData)
1444 elif o in ("-m", "--erasecycles"):
1446 meraseCycles = int(a) #try to convert decimal
1448 sys.stderr.write("erasecycles must be a valid number\n")
1450 #sanity check of value
1451 if meraseCycles < 1:
1452 sys.stderr.write("erasecycles must be a positive number\n")
1454 if meraseCycles > 20:
1455 sys.stderr.write("warning: erasecycles set to a large number (>20): %d\n" % meraseCycles)
1456 sys.stderr.write( "Number of mass erase cycles set to %i.\n" % meraseCycles)
1457 bsl.meraseCycles = meraseCycles
1458 elif o in ("-e", "--masserase"):
1459 toinit.append(bsl.actionMassErase) #Erase Flash
1460 elif o in ("-E", "--erasecheck"):
1461 toinit.append(bsl.actionEraseCheck) #Erase Check (by file)
1462 elif o in ("-p", "--program"):
1463 todo.append(bsl.actionProgram) #Program file
1464 elif o in ("--fromweb"):
1465 toinit.append(bsl.actionMassErase) #Erase Flash
1466 todo.append(bsl.actionFromweb) #Program GoodFET code
1467 elif o in ("-v", "--verify"):
1468 todo.append(bsl.actionVerify) #Verify file
1469 elif o in ("-r", "--reset"):
1471 elif o in ("-g", "--go"):
1473 goaddr = int(a) #try to convert decimal
1476 goaddr = int(a[2:],16) #try to convert hex
1478 sys.stderr.write("go address must be a valid number\n")
1481 elif o in ("-U", "--unpatched"):
1483 elif o in ("-D", "--debug"):
1485 elif o in ("-u", "--upload"):
1487 startaddr = int(a) #try to convert decimal
1490 startaddr = int(a,16) #try to convert hex
1492 sys.stderr.write("upload address must be a valid number\n")
1494 elif o in ("-s", "--size"):
1501 sys.stderr.write("size must be a valid number\n")
1503 elif o in ("-x", "--hex"):
1505 elif o in ("-b", "--bin"):
1507 elif o in ("-I", "--intelhex"):
1509 elif o in ("-T", "--titext"):
1511 elif o in ("-N", "--notimeout"):
1513 elif o in ("-B", "--bsl"):
1514 bslrepl = Memory() #File to program
1516 elif o in ("-V", "--bslversion"):
1517 todo.append(bsl.actionReadBSLVersion) #load replacement BSL as first item
1518 elif o in ("-S", "--speed"):
1520 speed = int(a) #try to convert decimal
1522 sys.stderr.write("speed must be decimal number\n")
1524 elif o in ("-1", "--f1x"):
1526 elif o in ("-2", "--f2x"):
1528 elif o in ("-4", "--f4x"):
1530 elif o in ("--invert-reset", ):
1532 elif o in ("--invert-test", ):
1534 elif o in ("--swap-reset-test", ):
1536 elif o in ("--telos-latch", ):
1538 elif o in ("--telos-i2c", ):
1540 elif o in ("--telos", ):
1545 elif o in ("--telosb", ):
1550 elif o in ("--tmote", ):
1555 elif o in ("--no-BSL-download", ):
1557 elif o in ("--force-BSL-download", ):
1559 elif o in ("--slow", ):
1563 sys.stderr.write("Use -h for help\n");
1564 sys.stderr.write("Use --fromweb to upgrade a GoodFET.\n")
1565 elif len(args) == 1: #a filename is given
1566 if not todo: #if there are no actions yet
1567 todo.extend([ #add some useful actions...
1572 else: #number of args is wrong
1576 if DEBUG: #debug infos
1577 sys.stderr.write("Debug level set to %d\n" % DEBUG)
1578 sys.stderr.write("Python version: %s\n" % sys.version)
1580 #sanity check of options
1581 if notimeout and goaddr is not None and startaddr is not None:
1582 sys.stderr.write("Option --notimeout can not be used together with both --upload and --go\n")
1586 sys.stderr.write("Warning: option --notimeout can cause improper function in some cases!\n")
1589 if goaddr and reset:
1590 sys.stderr.write("Warning: option --reset ignored as --go is specified!\n")
1593 if startaddr and reset:
1594 sys.stderr.write("Warning: option --reset ignored as --upload is specified!\n")
1599 #prepare data to download
1600 bsl.data = Memory() #prepare downloaded data
1601 if filetype is not None: #if the filetype is given...
1602 if filename is None:
1603 raise ValueError("no filename but filetype specified")
1604 if filename == '-': #get data from stdin
1607 file = open(filename, "rb") #or from a file
1608 if filetype == 0: #select load function
1609 bsl.data.loadIHex(file) #intel hex
1611 bsl.data.loadTIText(file) #TI's format
1613 raise ValueError("illegal filetype specified")
1614 else: #no filetype given...
1615 if filename == '-': #for stdin:
1616 bsl.data.loadIHex(sys.stdin) #assume intel hex
1618 bsl.data.loadFile(filename) #autodetect otherwise
1620 if DEBUG > 3: sys.stderr.write("File: %r" % filename)
1622 bsl.comInit(comPort) #init port
1624 #initialization list
1625 if toinit: #erase and erase check
1626 if DEBUG: sys.stderr.write("Preparing device ...\n")
1627 #bsl.actionStartBSL(usepatch=0, adjsp=0) #no workarounds needed
1628 #if speed: bsl.actionChangeBaudrate(speed) #change baud rate as fast as possible
1629 for f in toinit: f()
1631 if todo or goaddr or startaddr:
1632 if DEBUG: sys.stderr.write("Actions ...\n")
1635 usepatch=not unpatched,
1636 replacementBSL=bslrepl,
1638 mayuseBSL=mayuseBSL,
1644 if DEBUG > 0: #debug
1645 #show a nice list of sheduled actions
1646 sys.stderr.write("TODO list:\n")
1649 sys.stderr.write(" %s\n" % f.func_name)
1650 except AttributeError:
1651 sys.stderr.write(" %r\n" % f)
1652 for f in todo: f() #work through todo list
1654 if reset: #reset device first if desired
1657 bsl.txPasswd(); #default pass
1658 data=bsl.uploadData(0xc00,1024);
1661 hex+=("%02x "%ord(c));
1664 bsl.txPasswd(); #default pass
1665 data=bsl.uploadData(0x1000,256);
1668 hex+=("%02x "%ord(c));
1672 if goaddr is not None: #start user programm at specified address
1673 bsl.actionRun(goaddr) #load PC and execute
1675 #upload datablock and output
1676 if startaddr is not None:
1677 if goaddr: #if a program was started...
1678 #don't restart BSL but wait for the device to enter it itself
1679 sys.stderr.write("Waiting for device to reconnect for upload: ")
1681 bsl.txPasswd(bsl.passwd, wait=1) #synchronize, try forever...
1682 data = bsl.uploadData(startaddr, size) #upload data
1684 data = bsl.uploadData(startaddr, size) #upload data
1685 if hexoutput: #depending on output format
1687 while m < len(data): #print a hex display
1688 print hexify(startaddr+m, map(ord,data[m:m+16]))
1691 sys.stdout.write(data) #binary output w/o newline!
1692 wait = 0 #wait makes no sense as after the upload the device is still in BSL
1694 if wait: #wait at the end if desired
1695 sys.stderr.write("Press <ENTER> ...\n") #display a prompt
1697 raw_input() #wait for newline
1699 bsl.comDone() #Release serial communication port
1701 if __name__ == '__main__':
1705 raise #let pass exit() calls
1706 except KeyboardInterrupt:
1707 if DEBUG: raise #show full trace in debug mode
1708 sys.stderr.write("user abort.\n") #short messy in user mode
1709 sys.exit(1) #set errorlevel for script usage
1710 except Exception, msg: #every Exception is caught and displayed
1711 if DEBUG: raise #show full trace in debug mode
1712 sys.stderr.write("\nAn error occoured:\n%s\n" % msg) #short messy in user mode
1713 sys.exit(1) #set errorlevel for script usage