114
|
1 import struct, time
|
113
|
2 from usb import UsbContext
|
|
3
|
|
4 class STLinkException(Exception):
|
|
5 pass
|
|
6
|
115
|
7 ST_VID, STLINK2_PID = 0x0483, 0x3748
|
|
8
|
113
|
9 def checkDevice(device):
|
|
10 return device.VendorId == ST_VID and device.ProductId == STLINK2_PID
|
|
11
|
115
|
12 DFU_MODE, MASS_MODE, DEBUG_MODE = 0, 1, 2
|
117
|
13
|
|
14 CORE_RUNNING = 0x80
|
|
15 CORE_HALTED = 0x81
|
|
16
|
114
|
17 # Commands:
|
|
18 GET_VERSION = 0xf1
|
|
19 DEBUG_COMMAND = 0xf2
|
|
20 DFU_COMMAND = 0xf3
|
|
21 GET_CURRENT_MODE = 0xf5
|
|
22
|
|
23 # dfu commands:
|
|
24 DFU_EXIT = 0x7
|
113
|
25
|
114
|
26 # debug commands:
|
|
27 DEBUG_ENTER = 0x20
|
|
28 DEBUG_EXIT = 0x21
|
|
29 DEBUG_ENTER_SWD = 0xa3
|
|
30 DEBUG_GETSTATUS = 0x01
|
116
|
31 DEBUG_RESETSYS = 0x03
|
115
|
32 DEBUG_READREG = 0x5
|
|
33 DEBUG_WRITEREG = 0x6
|
|
34 DEBUG_READMEM_32BIT = 0x7
|
|
35 DEBUG_WRITEMEM_32BIT = 0x8
|
117
|
36 DEBUG_RUNCORE = 0x9
|
|
37 DEBUG_STEPCORE = 0xa
|
114
|
38
|
115
|
39 JTAG_WRITEDEBUG_32BIT = 0x35
|
114
|
40 JTAG_READDEBUG_32BIT = 0x36
|
|
41
|
|
42 # cortex M3
|
|
43 CM3_REG_CPUID = 0xE000ED00
|
|
44
|
115
|
45 # F4 specifics:
|
|
46 STM32_FLASH_BASE = 0x08000000
|
|
47 STM32_SRAM_BASE = 0x20000000
|
|
48
|
116
|
49 FLASH_KEY1 = 0x45670123
|
|
50 FLASH_KEY2 = 0xcdef89ab
|
115
|
51 # flash registers:
|
116
|
52 FLASH_F4_REGS_ADDR = 0x40023c00
|
115
|
53
|
116
|
54 FLASH_F4_KEYR = FLASH_F4_REGS_ADDR + +0x04
|
115
|
55 FLASH_F4_SR = FLASH_F4_REGS_ADDR + 0x0c
|
|
56 FLASH_F4_CR = FLASH_F4_REGS_ADDR + 0x10
|
|
57
|
|
58 FLASH_F4_CR_START = 16
|
|
59 FLASH_F4_CR_LOCK = 31
|
117
|
60 FLASH_CR_PG = 0
|
115
|
61 FLASH_F4_CR_SER = 1
|
116
|
62 FLASH_CR_MER = 2
|
115
|
63 FLASH_F4_CR_SNB = 3
|
|
64 FLASH_F4_CR_SNB_MASK = 0x38
|
|
65 FLASH_F4_SR_BSY = 16
|
|
66
|
|
67 def calculate_F4_sector(address):
|
|
68 """
|
|
69 from 0x8000000 to 0x80FFFFF
|
|
70 4 sectors of 0x4000 (16 kB)
|
|
71 1 sector of 0x10000 (64 kB)
|
|
72 7 of 0x20000 (128 kB)
|
|
73 """
|
|
74 sectorsizes = [0x4000] * 4 + [0x10000] + [0x20000] * 7
|
|
75 sectorstarts = []
|
|
76 a = STM32_FLASH_BASE
|
|
77 for sectorsize in sectorsizes:
|
|
78 sectorstarts.append(a)
|
|
79 a += sectorsize
|
|
80 # linear search:
|
|
81 sec = 0
|
|
82 while sec < len(sectorsizes) and address >= sectorstarts[sec]:
|
|
83 sec += 1
|
|
84 sec -= 1 # one back.
|
|
85 return sec, sectorsizes[sec]
|
|
86
|
|
87 def calcSectors(address, size):
|
|
88 off = 0
|
|
89 sectors = []
|
|
90 while off < size:
|
|
91 sectornum, sectorsize = calculate_F4_sector(address + off)
|
|
92 sectors.append((sectornum, sectorsize))
|
|
93 off += sectorsize
|
|
94 return sectors
|
|
95
|
114
|
96 class STLink:
|
119
|
97 """ ST link interface code """
|
|
98 def __init__(self, stlink2=None):
|
|
99 if not stlink2:
|
|
100 context = UsbContext()
|
|
101 stlink2s = list(filter(checkDevice, context.DeviceList))
|
|
102 if not stlink2s:
|
|
103 raise STLinkException('Could not find an ST link')
|
|
104 if len(stlink2s) > 1:
|
|
105 print('More then one stlink2 found, picking first one')
|
|
106 stlink2 = stlink2s[0]
|
|
107 self.stlink2 = stlink2
|
113
|
108 def open(self):
|
119
|
109 self.devHandle = self.stlink2.open()
|
114
|
110 if self.devHandle.Configuration != 1:
|
|
111 self.devHandle.Configuration = 1
|
|
112 self.devHandle.claimInterface(0)
|
116
|
113
|
|
114 # First initialization:
|
|
115 if self.CurrentMode == DFU_MODE:
|
|
116 self.exitDfuMode()
|
|
117 if self.CurrentMode != DEBUG_MODE:
|
|
118 self.enterSwdMode()
|
|
119 self.reset()
|
114
|
120 def close(self):
|
117
|
121 # TODO
|
114
|
122 pass
|
115
|
123
|
|
124 # modes:
|
113
|
125 def getCurrentMode(self):
|
114
|
126 cmd = bytearray(16)
|
|
127 cmd[0] = GET_CURRENT_MODE
|
|
128 reply = self.send_recv(cmd, 2) # Expect 2 bytes back
|
|
129 return reply[0]
|
113
|
130 CurrentMode = property(getCurrentMode)
|
114
|
131 @property
|
|
132 def CurrentModeString(self):
|
|
133 modes = {DFU_MODE: 'dfu', MASS_MODE: 'massmode', DEBUG_MODE:'debug'}
|
|
134 return modes[self.CurrentMode]
|
|
135 def exitDfuMode(self):
|
|
136 cmd = bytearray(16)
|
115
|
137 cmd[0:2] = DFU_COMMAND, DFU_EXIT
|
114
|
138 self.send_recv(cmd)
|
|
139 def enterSwdMode(self):
|
|
140 cmd = bytearray(16)
|
115
|
141 cmd[0:3] = DEBUG_COMMAND, DEBUG_ENTER, DEBUG_ENTER_SWD
|
114
|
142 self.send_recv(cmd)
|
|
143 def exitDebugMode(self):
|
|
144 cmd = bytearray(16)
|
115
|
145 cmd[0:2] = DEBUG_COMMAND, DEBUG_EXIT
|
114
|
146 self.send_recv(cmd)
|
|
147
|
|
148 def getVersion(self):
|
|
149 cmd = bytearray(16)
|
|
150 cmd[0] = GET_VERSION
|
|
151 data = self.send_recv(cmd, 6) # Expect 6 bytes back
|
|
152 # Parse 6 bytes into various versions:
|
|
153 b0, b1, b2, b3, b4, b5 = data
|
|
154 stlink_v = b0 >> 4
|
|
155 jtag_v = ((b0 & 0xf) << 2) | (b1 >> 6)
|
|
156 swim_v = b1 & 0x3f
|
|
157 vid = (b3 << 8) | b2
|
|
158 pid = (b5 << 8) | b4
|
|
159 return 'stlink={0} jtag={1} swim={2} vid:pid={3:04X}:{4:04X}'.format(\
|
|
160 stlink_v, jtag_v, swim_v, vid, pid)
|
|
161 Version = property(getVersion)
|
|
162
|
|
163 @property
|
|
164 def ChipId(self):
|
|
165 return self.read_debug32(0xE0042000)
|
|
166 @property
|
|
167 def CpuId(self):
|
|
168 u32 = self.read_debug32(CM3_REG_CPUID)
|
|
169 implementer_id = (u32 >> 24) & 0x7f
|
|
170 variant = (u32 >> 20) & 0xf
|
|
171 part = (u32 >> 4) & 0xfff
|
|
172 revision = u32 & 0xf
|
|
173 return implementer_id, variant, part, revision
|
|
174
|
117
|
175 def getStatus(self):
|
114
|
176 cmd = bytearray(16)
|
115
|
177 cmd[0:2] = DEBUG_COMMAND, DEBUG_GETSTATUS
|
114
|
178 reply = self.send_recv(cmd, 2)
|
|
179 return reply[0]
|
117
|
180 Status = property(getStatus)
|
|
181 @property
|
|
182 def StatusString(self):
|
|
183 s = self.Status
|
|
184 statii = {CORE_RUNNING: 'CORE RUNNING', CORE_HALTED: 'CORE HALTED'}
|
|
185 if s in statii:
|
|
186 return statii[s]
|
|
187
|
116
|
188 def reset(self):
|
|
189 cmd = bytearray(16)
|
|
190 cmd[0:2] = DEBUG_COMMAND, DEBUG_RESETSYS
|
|
191 self.send_recv(cmd, 2)
|
113
|
192
|
115
|
193 # debug commands:
|
114
|
194 def step(self):
|
|
195 cmd = bytearray(16)
|
115
|
196 cmd[0:2] = DEBUG_COMMAND, DEBUG_STEPCORE
|
114
|
197 self.send_recv(cmd, 2)
|
|
198 def run(self):
|
|
199 cmd = bytearray(16)
|
115
|
200 cmd[0:2] = DEBUG_COMMAND, DEBUG_RUNCORE
|
114
|
201 self.send_recv(cmd, 2)
|
115
|
202
|
|
203 # flashing commands:
|
|
204 def writeFlash(self, address, content):
|
|
205 # TODO:
|
|
206 flashsize = 0x100000 # fixed 1 MB for now..
|
|
207 print('WARNING: using 1 MB as flash size')
|
|
208 pagesize = 0x4000 # fixed for now!
|
|
209
|
|
210 # Check address range:
|
|
211 if address < STM32_FLASH_BASE:
|
|
212 raise STLinkException('Flashing below flash start')
|
|
213 if address + len(content) > STM32_FLASH_BASE + flashsize:
|
|
214 raise STLinkException('Flashing above flash size')
|
|
215 if address & 1 == 1:
|
|
216 raise STLinkException('Unaligned flash')
|
|
217 if len(content) & 1 == 1:
|
|
218 print('unaligned length, padding with zero')
|
|
219 content += bytes([0])
|
|
220 if address & (pagesize - 1) != 0:
|
|
221 raise STLinkException('Address not aligned with pagesize')
|
114
|
222
|
115
|
223 # erase required space
|
|
224 sectors = calcSectors(address, len(content))
|
|
225 print('erasing {0} sectors'.format(len(sectors)))
|
|
226 for sector, secsize in sectors:
|
119
|
227 print('erasing sector {0} of {1} bytes'.format(sector, secsize))
|
115
|
228 self.eraseFlashSector(sector)
|
|
229
|
|
230 # program pages:
|
116
|
231 self.unlockFlashIf()
|
119
|
232 self.writeFlashCrPsiz(2) # writes are 32 bits aligned
|
117
|
233 self.setFlashCrPg()
|
|
234
|
119
|
235 print('writing {0} bytes'.format(len(content)), end='')
|
117
|
236 offset = 0
|
119
|
237 t1 = time.time()
|
117
|
238 while offset < len(content):
|
|
239 size = len(content) - offset
|
|
240 if size > 0x8000:
|
|
241 size = 0x8000
|
|
242
|
119
|
243 chunk = content[offset:offset + size]
|
|
244 while len(chunk) % 4 != 0:
|
|
245 print('padding chunk')
|
|
246 chunk = chunk + bytes([0])
|
|
247
|
|
248 # Use simple mem32 writes:
|
|
249 self.write_mem32(address + offset, chunk)
|
|
250
|
117
|
251 offset += size
|
119
|
252 print('.', end='', flush=True)
|
|
253 t2 = time.time()
|
|
254 print('Done!')
|
|
255 print('Speed: {0} bytes/second'.format(len(content)/(t2-t1)))
|
115
|
256
|
116
|
257 self.lockFlash()
|
|
258
|
115
|
259 # verfify program:
|
|
260 self.verifyFlash(address, content)
|
|
261 def eraseFlashSector(self, sector):
|
|
262 self.waitFlashBusy()
|
|
263 self.unlockFlashIf()
|
|
264 self.writeFlashCrSnb(sector)
|
|
265 self.setFlashCrStart()
|
|
266 self.waitFlashBusy()
|
|
267 self.lockFlash()
|
116
|
268 def eraseFlash(self):
|
|
269 self.waitFlashBusy()
|
|
270 self.unlockFlashIf()
|
|
271 self.setFlashCrMer()
|
|
272 self.setFlashCrStart()
|
|
273 self.waitFlashBusy()
|
|
274 self.clearFlashCrMer()
|
|
275 self.lockFlash()
|
115
|
276 def verifyFlash(self, address, content):
|
116
|
277 device_content = self.readFlash(address, len(content))
|
|
278 ok = content == device_content
|
|
279 print('Verify:', ok)
|
|
280 def readFlash(self, address, size):
|
119
|
281 print('Reading {1} bytes from 0x{0:X}'.format(address, size), end='')
|
115
|
282 offset = 0
|
116
|
283 tmp_size = 0x1800
|
115
|
284 t1 = time.time()
|
116
|
285 image = bytes()
|
|
286 while offset < size:
|
115
|
287 # Correct for last page:
|
116
|
288 if offset + tmp_size > size:
|
|
289 tmp_size = size - offset
|
115
|
290
|
|
291 # align size to 4 bytes:
|
116
|
292 aligned_size = tmp_size
|
115
|
293 while aligned_size % 4 != 0:
|
|
294 aligned_size += 1
|
|
295
|
|
296 mem = self.read_mem32(address + offset, aligned_size)
|
116
|
297 image += mem[:tmp_size]
|
115
|
298
|
|
299 # indicate progress:
|
116
|
300 print('.', end='', flush=True)
|
115
|
301
|
|
302 # increase for next piece:
|
116
|
303 offset += tmp_size
|
115
|
304 t2 = time.time()
|
116
|
305 assert size == len(image)
|
119
|
306 print('Done!')
|
|
307 print('Speed: {0} bytes/second'.format(size/(t2-t1)))
|
116
|
308 return image
|
115
|
309 def readFlashSr(self):
|
|
310 return self.read_debug32(FLASH_F4_SR)
|
|
311 def readFlashCr(self):
|
|
312 return self.read_debug32(FLASH_F4_CR)
|
119
|
313 def writeFlashCr(self, x):
|
|
314 self.write_debug32(FLASH_F4_CR, x)
|
115
|
315 def writeFlashCrSnb(self, sector):
|
|
316 x = self.readFlashCr()
|
|
317 x &= ~FLASH_F4_CR_SNB_MASK
|
|
318 x |= sector << FLASH_F4_CR_SNB
|
|
319 x |= 1 << FLASH_F4_CR_SER
|
119
|
320 self.writeFlashCr(x)
|
116
|
321 def setFlashCrMer(self):
|
|
322 x = self.readFlashCr()
|
|
323 x |= 1 << FLASH_CR_MER
|
119
|
324 self.writeFlashCr(x)
|
117
|
325 def setFlashCrPg(self):
|
|
326 x = self.readFlashCr()
|
|
327 x |= 1 << FLASH_CR_PG
|
119
|
328 self.writeFlashCr(x)
|
117
|
329 def writeFlashCrPsiz(self, n):
|
|
330 x = self.readFlashCr()
|
|
331 x &= (0x3 << 8)
|
|
332 x |= n << 8
|
119
|
333 self.writeFlashCr(x)
|
116
|
334 def clearFlashCrMer(self):
|
|
335 x = self.readFlashCr()
|
|
336 x &= ~(1 << FLASH_CR_MER)
|
119
|
337 self.writeFlashCr(x)
|
115
|
338 def setFlashCrStart(self):
|
|
339 x = self.readFlashCr()
|
|
340 x |= 1 << FLASH_F4_CR_START
|
119
|
341 self.writeFlashCr(x)
|
115
|
342 def isFlashBusy(self):
|
|
343 mask = 1 << FLASH_F4_SR_BSY
|
|
344 sr = self.readFlashSr()
|
119
|
345 # Check for error bits:
|
|
346 errorbits = {}
|
|
347 errorbits[7] = 'Programming sequence error'
|
|
348 errorbits[6] = 'Programming parallelism error'
|
|
349 errorbits[5] = 'Programming alignment error'
|
|
350 errorbits[4] = 'Write protection error'
|
|
351 errorbits[1] = 'Operation error'
|
|
352 #errorbits[0] = 'End of operation'
|
|
353 for bit, msg in errorbits.items():
|
|
354 if sr & (1 << bit) == (1 << bit):
|
|
355 raise STLinkException(msg)
|
|
356
|
115
|
357 return sr & mask == mask
|
|
358 def waitFlashBusy(self):
|
|
359 """ block until flash operation completes. """
|
|
360 while self.isFlashBusy():
|
|
361 pass
|
|
362 def isFlashLocked(self):
|
|
363 cr = self.readFlashCr()
|
|
364 mask = 1 << FLASH_F4_CR_LOCK
|
|
365 return cr & mask == mask
|
|
366 def unlockFlashIf(self):
|
|
367 if self.isFlashLocked():
|
|
368 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY1)
|
|
369 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY2)
|
|
370 if self.isFlashLocked():
|
|
371 raise STLinkException('Failed to unlock')
|
|
372 def lockFlash(self):
|
116
|
373 x = self.readFlashCr() | (1 << FLASH_F4_CR_LOCK)
|
|
374 self.write_debug32(FLASH_F4_CR, x)
|
115
|
375
|
114
|
376 # Helper 1 functions:
|
115
|
377 def write_debug32(self, address, value):
|
|
378 cmd = bytearray(16)
|
|
379 cmd[0:2] = DEBUG_COMMAND, JTAG_WRITEDEBUG_32BIT
|
119
|
380 cmd[2:10] = struct.pack('<II', address, value)
|
115
|
381 self.send_recv(cmd, 2)
|
114
|
382 def read_debug32(self, address):
|
|
383 cmd = bytearray(16)
|
115
|
384 cmd[0:2] = DEBUG_COMMAND, JTAG_READDEBUG_32BIT
|
114
|
385 cmd[2:6] = struct.pack('<I', address) # pack into u32 little endian
|
|
386 reply = self.send_recv(cmd, 8)
|
|
387 return struct.unpack('<I', reply[4:8])[0]
|
115
|
388 def write_reg(self, reg, value):
|
|
389 cmd = bytearray(16)
|
|
390 cmd[0:3] = DEBUG_COMMAND, DEBUG_WRITEREG, reg
|
|
391 cmd[3:7] = struct.pack('<I', value)
|
|
392 r = self.send_recv(cmd, 2)
|
|
393 def read_reg(self, reg):
|
|
394 cmd = bytearray(16)
|
|
395 cmd[0:3] = DEBUG_COMMAND, DEBUG_READREG, reg
|
|
396 reply = self.send_recv(cmd, 4)
|
|
397 return struct.unpack('<I', reply)[0]
|
116
|
398 def write_mem32(self, address, content):
|
|
399 assert len(content) % 4 == 0
|
|
400 cmd = bytearray(16)
|
|
401 cmd[0:2] = DEBUG_COMMAND, DEBUG_WRITEMEM_32BIT
|
119
|
402 cmd[2:8] = struct.pack('<IH', address, len(content))
|
116
|
403 self.send_recv(cmd)
|
|
404 self.send_recv(content)
|
115
|
405 def read_mem32(self, address, length):
|
|
406 assert length % 4 == 0
|
|
407 cmd = bytearray(16)
|
|
408 cmd[0:2] = DEBUG_COMMAND, DEBUG_READMEM_32BIT
|
119
|
409 cmd[2:8] = struct.pack('<IH', address, length)
|
115
|
410 reply = self.send_recv(cmd, length) # expect memory back!
|
|
411 return reply
|
114
|
412
|
|
413 # Helper 2 functions:
|
|
414 def send_recv(self, tx, rxsize=0):
|
115
|
415 """ Helper function that transmits and receives data in bulk mode. """
|
114
|
416 # TODO: we could use here the non-blocking libusb api.
|
|
417 tx = bytes(tx)
|
116
|
418 #assert len(tx) == 16
|
114
|
419 self.devHandle.bulkWrite(2, tx) # write to endpoint 2
|
|
420 if rxsize > 0:
|
|
421 return self.devHandle.bulkRead(1, rxsize) # read from endpoint 1
|
|
422
|
|
423 knownChipIds = {0x1: 'x'}
|
|
424
|
|
425 if __name__ == '__main__':
|
|
426 # Test program
|
|
427 sl = STLink()
|
|
428 sl.open()
|
|
429 print('version:', sl.Version)
|
|
430 print('mode before doing anything:', sl.CurrentModeString)
|
|
431 if sl.CurrentMode == DFU_MODE:
|
|
432 sl.exitDfuMode()
|
|
433 sl.enterSwdMode()
|
|
434 print('mode after entering swd mode:', sl.CurrentModeString)
|
|
435
|
|
436 i = sl.ChipId
|
|
437 if i in knownChipIds:
|
|
438 print('chip id: 0x{0:X} -> {1}'.format(i, knownChipIds[i]))
|
|
439 else:
|
|
440 print('chip id: 0x{0:X}'.format(i))
|
|
441 print('cpu: {0}'.format(sl.CpuId))
|
|
442
|
117
|
443 print('status: {0}'.format(sl.StatusString))
|
114
|
444
|
115
|
445 # test registers:
|
|
446 sl.write_reg(3, 0x1337)
|
116
|
447 sl.write_reg(2, 0x1332)
|
117
|
448 sl.write_reg(6, 0x12345)
|
115
|
449 assert sl.read_reg(3) == 0x1337
|
116
|
450 assert sl.read_reg(2) == 0x1332
|
117
|
451 assert sl.read_reg(6) == 0x12345
|
114
|
452
|
|
453 sl.exitDebugMode()
|
|
454 print('mode at end:', sl.CurrentModeString)
|
|
455
|
|
456 sl.close()
|
119
|
457 print('Test succes!')
|
114
|
458
|