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
|
114
|
13 # Commands:
|
|
14 GET_VERSION = 0xf1
|
|
15 DEBUG_COMMAND = 0xf2
|
|
16 DFU_COMMAND = 0xf3
|
|
17 GET_CURRENT_MODE = 0xf5
|
|
18
|
|
19 # dfu commands:
|
|
20 DFU_EXIT = 0x7
|
113
|
21
|
114
|
22 # debug commands:
|
|
23 DEBUG_ENTER = 0x20
|
|
24 DEBUG_EXIT = 0x21
|
|
25 DEBUG_ENTER_SWD = 0xa3
|
|
26 DEBUG_GETSTATUS = 0x01
|
115
|
27 DEBUG_READREG = 0x5
|
|
28 DEBUG_WRITEREG = 0x6
|
|
29 DEBUG_READMEM_32BIT = 0x7
|
|
30 DEBUG_WRITEMEM_32BIT = 0x8
|
114
|
31
|
115
|
32 JTAG_WRITEDEBUG_32BIT = 0x35
|
114
|
33 JTAG_READDEBUG_32BIT = 0x36
|
|
34
|
|
35 # cortex M3
|
|
36 CM3_REG_CPUID = 0xE000ED00
|
|
37
|
115
|
38 # F4 specifics:
|
|
39 STM32_FLASH_BASE = 0x08000000
|
|
40 STM32_SRAM_BASE = 0x20000000
|
|
41
|
|
42 # flash registers:
|
|
43 FLASH_F4_REGS_ADDR = 0x400223c0
|
|
44
|
|
45 FLASH_F4_SR = FLASH_F4_REGS_ADDR + 0x0c
|
|
46 FLASH_F4_CR = FLASH_F4_REGS_ADDR + 0x10
|
|
47
|
|
48 FLASH_F4_CR_START = 16
|
|
49 FLASH_F4_CR_LOCK = 31
|
|
50 FLASH_F4_CR_SER = 1
|
|
51 FLASH_F4_CR_SNB = 3
|
|
52 FLASH_F4_CR_SNB_MASK = 0x38
|
|
53 FLASH_F4_SR_BSY = 16
|
|
54
|
|
55 def calculate_F4_sector(address):
|
|
56 """
|
|
57 from 0x8000000 to 0x80FFFFF
|
|
58 4 sectors of 0x4000 (16 kB)
|
|
59 1 sector of 0x10000 (64 kB)
|
|
60 7 of 0x20000 (128 kB)
|
|
61 """
|
|
62 sectorsizes = [0x4000] * 4 + [0x10000] + [0x20000] * 7
|
|
63 sectorstarts = []
|
|
64 a = STM32_FLASH_BASE
|
|
65 for sectorsize in sectorsizes:
|
|
66 sectorstarts.append(a)
|
|
67 a += sectorsize
|
|
68 # linear search:
|
|
69 sec = 0
|
|
70 while sec < len(sectorsizes) and address >= sectorstarts[sec]:
|
|
71 sec += 1
|
|
72 sec -= 1 # one back.
|
|
73 return sec, sectorsizes[sec]
|
|
74
|
|
75 def calcSectors(address, size):
|
|
76 off = 0
|
|
77 sectors = []
|
|
78 while off < size:
|
|
79 sectornum, sectorsize = calculate_F4_sector(address + off)
|
|
80 #print('num: {0} size: {1:X} offset: {2}'.format(sectornum, sectorsize, off))
|
|
81 sectors.append((sectornum, sectorsize))
|
|
82 off += sectorsize
|
|
83 return sectors
|
|
84
|
114
|
85 class STLink:
|
113
|
86 def __init__(self):
|
|
87 self.context = UsbContext()
|
|
88 def open(self):
|
|
89 context = UsbContext()
|
|
90 stlink2s = list(filter(checkDevice, context.DeviceList))
|
|
91 if not stlink2s:
|
|
92 raise STLinkException('Could not find an ST link')
|
|
93 if len(stlink2s) > 1:
|
|
94 print('More then one stlink2 found, picking first one')
|
|
95 stlink2 = stlink2s[0]
|
114
|
96 self.devHandle = stlink2.open()
|
|
97 if self.devHandle.Configuration != 1:
|
|
98 self.devHandle.Configuration = 1
|
|
99 self.devHandle.claimInterface(0)
|
|
100 def close(self):
|
|
101 pass
|
115
|
102
|
|
103 # modes:
|
113
|
104 def getCurrentMode(self):
|
114
|
105 cmd = bytearray(16)
|
|
106 cmd[0] = GET_CURRENT_MODE
|
|
107 reply = self.send_recv(cmd, 2) # Expect 2 bytes back
|
|
108 return reply[0]
|
113
|
109 CurrentMode = property(getCurrentMode)
|
114
|
110 @property
|
|
111 def CurrentModeString(self):
|
|
112 modes = {DFU_MODE: 'dfu', MASS_MODE: 'massmode', DEBUG_MODE:'debug'}
|
|
113 return modes[self.CurrentMode]
|
|
114 def exitDfuMode(self):
|
|
115 cmd = bytearray(16)
|
115
|
116 cmd[0:2] = DFU_COMMAND, DFU_EXIT
|
114
|
117 self.send_recv(cmd)
|
|
118 def enterSwdMode(self):
|
|
119 cmd = bytearray(16)
|
115
|
120 cmd[0:3] = DEBUG_COMMAND, DEBUG_ENTER, DEBUG_ENTER_SWD
|
114
|
121 self.send_recv(cmd)
|
|
122 def exitDebugMode(self):
|
|
123 cmd = bytearray(16)
|
115
|
124 cmd[0:2] = DEBUG_COMMAND, DEBUG_EXIT
|
114
|
125 self.send_recv(cmd)
|
|
126
|
|
127 def getVersion(self):
|
|
128 cmd = bytearray(16)
|
|
129 cmd[0] = GET_VERSION
|
|
130 data = self.send_recv(cmd, 6) # Expect 6 bytes back
|
|
131 # Parse 6 bytes into various versions:
|
|
132 b0, b1, b2, b3, b4, b5 = data
|
|
133 stlink_v = b0 >> 4
|
|
134 jtag_v = ((b0 & 0xf) << 2) | (b1 >> 6)
|
|
135 swim_v = b1 & 0x3f
|
|
136 vid = (b3 << 8) | b2
|
|
137 pid = (b5 << 8) | b4
|
|
138
|
|
139 return 'stlink={0} jtag={1} swim={2} vid:pid={3:04X}:{4:04X}'.format(\
|
|
140 stlink_v, jtag_v, swim_v, vid, pid)
|
|
141 Version = property(getVersion)
|
|
142
|
|
143 @property
|
|
144 def ChipId(self):
|
|
145 return self.read_debug32(0xE0042000)
|
|
146 @property
|
|
147 def CpuId(self):
|
|
148 u32 = self.read_debug32(CM3_REG_CPUID)
|
|
149 implementer_id = (u32 >> 24) & 0x7f
|
|
150 variant = (u32 >> 20) & 0xf
|
|
151 part = (u32 >> 4) & 0xfff
|
|
152 revision = u32 & 0xf
|
|
153 return implementer_id, variant, part, revision
|
|
154
|
|
155 def status(self):
|
|
156 cmd = bytearray(16)
|
115
|
157 cmd[0:2] = DEBUG_COMMAND, DEBUG_GETSTATUS
|
114
|
158 reply = self.send_recv(cmd, 2)
|
|
159 return reply[0]
|
113
|
160
|
115
|
161 # debug commands:
|
114
|
162 def step(self):
|
|
163 cmd = bytearray(16)
|
115
|
164 cmd[0:2] = DEBUG_COMMAND, DEBUG_STEPCORE
|
114
|
165 self.send_recv(cmd, 2)
|
|
166 def run(self):
|
|
167 cmd = bytearray(16)
|
115
|
168 cmd[0:2] = DEBUG_COMMAND, DEBUG_RUNCORE
|
114
|
169 self.send_recv(cmd, 2)
|
115
|
170
|
|
171 # flashing commands:
|
|
172 def writeFlash(self, address, content):
|
|
173 # TODO:
|
|
174 flashsize = 0x100000 # fixed 1 MB for now..
|
|
175 print('WARNING: using 1 MB as flash size')
|
|
176 pagesize = 0x4000 # fixed for now!
|
|
177
|
|
178 # Check address range:
|
|
179 if address < STM32_FLASH_BASE:
|
|
180 raise STLinkException('Flashing below flash start')
|
|
181 if address + len(content) > STM32_FLASH_BASE + flashsize:
|
|
182 raise STLinkException('Flashing above flash size')
|
|
183 if address & 1 == 1:
|
|
184 raise STLinkException('Unaligned flash')
|
|
185 if len(content) & 1 == 1:
|
|
186 print('unaligned length, padding with zero')
|
|
187 content += bytes([0])
|
|
188 if address & (pagesize - 1) != 0:
|
|
189 raise STLinkException('Address not aligned with pagesize')
|
114
|
190
|
115
|
191 # erase required space
|
|
192 sectors = calcSectors(address, len(content))
|
|
193 print('erasing {0} sectors'.format(len(sectors)))
|
|
194 for sector, secsize in sectors:
|
|
195 print('erasing sector {0} of size {1}'.format(sector, secsize))
|
|
196 self.eraseFlashSector(sector)
|
|
197
|
|
198 # program pages:
|
|
199 # TODO
|
|
200
|
|
201 # verfify program:
|
|
202 self.verifyFlash(address, content)
|
|
203 def eraseFlashSector(self, sector):
|
|
204 self.waitFlashBusy()
|
|
205 self.unlockFlashIf()
|
|
206 self.writeFlashCrSnb(sector)
|
|
207 self.setFlashCrStart()
|
|
208 self.waitFlashBusy()
|
|
209 self.lockFlash()
|
|
210 def verifyFlash(self, address, content):
|
|
211 print('verifying', address, len(content))
|
|
212 offset = 0
|
|
213 cmp_size = 0x1800
|
|
214 t1 = time.time()
|
|
215 while offset < len(content):
|
|
216 # Correct for last page:
|
|
217 if offset + cmp_size > len(content):
|
|
218 cmp_size = len(content) - offset
|
|
219
|
|
220 # align size to 4 bytes:
|
|
221 aligned_size = cmp_size
|
|
222 while aligned_size % 4 != 0:
|
|
223 aligned_size += 1
|
|
224
|
|
225 mem = self.read_mem32(address + offset, aligned_size)
|
|
226 ok = mem[:cmp_size] == content[offset:offset+cmp_size]
|
|
227
|
|
228 # indicate progress:
|
|
229 okc = '.' if ok else 'x'
|
|
230 print(okc, end='', flush=True)
|
|
231
|
|
232 # increase for next piece:
|
|
233 offset += cmp_size
|
|
234 t2 = time.time()
|
|
235 print('done! {0} bytes/second'.format(len(content)/(t2-t1)))
|
|
236 return content == mem
|
|
237 def readFlashSr(self):
|
|
238 return self.read_debug32(FLASH_F4_SR)
|
|
239 def readFlashCr(self):
|
|
240 return self.read_debug32(FLASH_F4_CR)
|
|
241 def writeFlashCrSnb(self, sector):
|
|
242 x = self.readFlashCr()
|
|
243 x &= ~FLASH_F4_CR_SNB_MASK
|
|
244 x |= sector << FLASH_F4_CR_SNB
|
|
245 x |= 1 << FLASH_F4_CR_SER
|
|
246 self.write_debug32(FLASH_F4_CR, x)
|
|
247 def setFlashCrStart(self):
|
|
248 x = self.readFlashCr()
|
|
249 x |= 1 << FLASH_F4_CR_START
|
|
250 self.write_debug32(FLASH_F4_CR, x)
|
|
251 def isFlashBusy(self):
|
|
252 mask = 1 << FLASH_F4_SR_BSY
|
|
253 sr = self.readFlashSr()
|
|
254 return sr & mask == mask
|
|
255 def waitFlashBusy(self):
|
|
256 """ block until flash operation completes. """
|
|
257 while self.isFlashBusy():
|
|
258 pass
|
|
259 def isFlashLocked(self):
|
|
260 cr = self.readFlashCr()
|
|
261 mask = 1 << FLASH_F4_CR_LOCK
|
|
262 return cr & mask == mask
|
|
263 def unlockFlashIf(self):
|
|
264 if self.isFlashLocked():
|
|
265 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY1)
|
|
266 self.write_debug32(FLASH_F4_KEYR, FLASH_KEY2)
|
|
267 if self.isFlashLocked():
|
|
268 raise STLinkException('Failed to unlock')
|
|
269
|
|
270 def lockFlash(self):
|
|
271 # TODO
|
|
272 pass
|
|
273
|
114
|
274 # Helper 1 functions:
|
115
|
275 def write_debug32(self, address, value):
|
|
276 cmd = bytearray(16)
|
|
277 cmd[0:2] = DEBUG_COMMAND, JTAG_WRITEDEBUG_32BIT
|
|
278 cmd[2:6] = struct.pack('<I', address)
|
|
279 cmd[6:10] = struct.pack('<I', value)
|
|
280 self.send_recv(cmd, 2)
|
114
|
281 def read_debug32(self, address):
|
|
282 cmd = bytearray(16)
|
115
|
283 cmd[0:2] = DEBUG_COMMAND, JTAG_READDEBUG_32BIT
|
114
|
284 cmd[2:6] = struct.pack('<I', address) # pack into u32 little endian
|
|
285 reply = self.send_recv(cmd, 8)
|
|
286 return struct.unpack('<I', reply[4:8])[0]
|
115
|
287 def write_reg(self, reg, value):
|
|
288 cmd = bytearray(16)
|
|
289 cmd[0:3] = DEBUG_COMMAND, DEBUG_WRITEREG, reg
|
|
290 cmd[3:7] = struct.pack('<I', value)
|
|
291 r = self.send_recv(cmd, 2)
|
|
292 def read_reg(self, reg):
|
|
293 cmd = bytearray(16)
|
|
294 cmd[0:3] = DEBUG_COMMAND, DEBUG_READREG, reg
|
|
295 reply = self.send_recv(cmd, 4)
|
|
296 return struct.unpack('<I', reply)[0]
|
|
297 def read_mem32(self, address, length):
|
|
298 assert length % 4 == 0
|
|
299 cmd = bytearray(16)
|
|
300 cmd[0:2] = DEBUG_COMMAND, DEBUG_READMEM_32BIT
|
|
301 cmd[2:6] = struct.pack('<I', address)
|
|
302 cmd[6:8] = struct.pack('<H', length) # uint16
|
|
303 reply = self.send_recv(cmd, length) # expect memory back!
|
|
304 return reply
|
114
|
305
|
|
306 # Helper 2 functions:
|
|
307 def send_recv(self, tx, rxsize=0):
|
115
|
308 """ Helper function that transmits and receives data in bulk mode. """
|
114
|
309 # TODO: we could use here the non-blocking libusb api.
|
|
310 tx = bytes(tx)
|
115
|
311 assert len(tx) == 16
|
114
|
312 self.devHandle.bulkWrite(2, tx) # write to endpoint 2
|
|
313 if rxsize > 0:
|
|
314 return self.devHandle.bulkRead(1, rxsize) # read from endpoint 1
|
|
315
|
|
316 knownChipIds = {0x1: 'x'}
|
|
317
|
|
318 if __name__ == '__main__':
|
|
319 # Test program
|
|
320 sl = STLink()
|
|
321 sl.open()
|
|
322 print('version:', sl.Version)
|
|
323 print('mode before doing anything:', sl.CurrentModeString)
|
|
324 if sl.CurrentMode == DFU_MODE:
|
|
325 sl.exitDfuMode()
|
|
326 sl.enterSwdMode()
|
|
327 print('mode after entering swd mode:', sl.CurrentModeString)
|
|
328
|
|
329 i = sl.ChipId
|
|
330 if i in knownChipIds:
|
|
331 print('chip id: 0x{0:X} -> {1}'.format(i, knownChipIds[i]))
|
|
332 else:
|
|
333 print('chip id: 0x{0:X}'.format(i))
|
|
334 print('cpu: {0}'.format(sl.CpuId))
|
|
335
|
|
336 print('status: {0}'.format(sl.status()))
|
|
337
|
115
|
338 #time.sleep(2.2)
|
|
339
|
|
340 # test registers:
|
|
341 sl.write_reg(3, 0x1337)
|
|
342 sl.write_reg(1, 0x1332)
|
|
343 assert sl.read_reg(3) == 0x1337
|
|
344 assert sl.read_reg(1) == 0x1332
|
114
|
345
|
|
346 sl.exitDebugMode()
|
|
347 print('mode at end:', sl.CurrentModeString)
|
|
348
|
|
349 sl.close()
|
|
350
|