Debian Codegraph @

ports/stm32/boards/NUCLEO_WB55/rfcore_firmware.py

raw
1 # This file is part of the MicroPython project, http://micropython.org/
2 #
3 # The MIT License (MIT)
4 #
5 # Copyright (c) 2020 Damien P. George
6 # Copyright (c) 2020 Jim Mussared
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining a copy
9 # of this software and associated documentation files (the "Software"), to deal
10 # in the Software without restriction, including without limitation the rights
11 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 # copies of the Software, and to permit persons to whom the Software is
13 # furnished to do so, subject to the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be included in
16 # all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 # THE SOFTWARE.
25
26 # This script provides helpers for working with the FUS/WS firmware on the WB55.
27 # It can be frozen into the MicroPython firmware (via manifest.py)
28 #
29 # The current FUS and WS firmware version and state can be queried via the
30 # `stm` module, e.g.
31 # stm.rfcore_status() (returns the first word of the device info table)
32 # stm.rfcore_fw_version(id) (returns a 5-tuple indicating fw version; id is: 0=FUS, 1=WS)
33 # stm.rfcore_sys_hci(ogf, ocf, cmd_buf) (synchronously execute HCI command on SYS channel)
34 #
35 # To perform a firmware update:
36 #
37 # 1. Generate "obfuscated" binary images using rfcore_makefirmware.py, eg.
38 # $ python3 ./boards/NUCLEO_WB55/rfcore_makefirmware.py ~/src/github.com/STMicroelectronics/STM32CubeWB/Projects/STM32WB_Copro_Wireless_Binaries/STM32WB5x/ /tmp
39 # This will generate /tmp/{fus_102,fus_110,ws_ble_hci}.bin
40 # It may warn that stm32wb5x_FUS_fw_1_0_2.bin cannot be found, newer packs don't include this
41 # which can be ignored unless your currently flashed FUS is older than 1.0.2
42 #
43 # 2. Copy required files to the device filesystem.
44 # $ mpremote cp /tmp/fus_102.bin :
45 # $ mpremote cp /tmp/fus_110.bin :
46 # $ mpremote cp /tmp/ws_ble_hci.bin :
47 # $ mpremote cp ./boards/NUCLEO_WB55/rfcore_firmware.py :
48 # In general, it's always safe to copy all three files and the updater will
49 # figure out what needs to be done. This is the recommended option.
50 # However, if you already have the latest FUS (1.1.0) installed, then just the
51 # WS firmware is required.
52 # If a FUS binary is present, then the existing WS will be removed so it's a good
53 # idea to always include the WS binary if updating FUS.
54 # Note that a WS binary will not be installed unless FUS 1.1.0 is installed.
55 #
56 # 3. Ensure boot.py calls `rfcore_firmware.resume()`.
57 # $ mpremote exec "import rfcore_firmware; rfcore_firmware.install_boot()"
58 # The WB55 will reset several times during the firmware update process, so this
59 # script manages the update state using RTC backup registers.
60 # `rfcore_firmware.resume()` will continue the update operation on startup to
61 # resume any in-progress update operation, and either trigger another reset, or
62 # return 0 to indicate that the operation completed successfully, or a reason
63 # code (see REASON_* below) to indicate failure.
64 #
65 # 4. Call rfcore_firmware.check_for_updates() to start the update process.
66 # $ mpremote exec "import rfcore_firmware; rfcore_firmware.check_for_updates()"
67 # The device will then immediately reboot and when the firmware update completes,
68 # the status will be returned from rfcore_firmware.resume(). See the REASON_ codes below.
69 # You can use the built-in stm.rfcore_fw_version() to query the installed version
70 # from your application code.
71
72 import struct, os
73
74 try:
75 import machine, stm
76 from binascii import crc32
77 from micropython import const
78 except ImportError:
79 # cpython
80 from binascii import crc32
81
82 machine = stm = None
83 const = lambda x: x
84
85
86 _OGF_VENDOR = const(0x3F)
87
88 _OCF_FUS_GET_STATE = const(0x52)
89 _OCF_FUS_FW_UPGRADE = const(0x54)
90 _OCF_FUS_FW_DELETE = const(0x55)
91 _OCF_FUS_START_WS = const(0x5A)
92 _OCF_BLE_INIT = const(0x66)
93
94 _HCI_KIND_VENDOR_RESPONSE = const(0x11)
95
96
97 # The firmware updater will search all of flash for the image to install, so
98 # it's important that the file doesn't exist anywhere on the filesystem and
99 # that the updater only finds the version that we copy into the reserved area.
100 # Otherwise it will find matching headers/footers in the flash filesystem and
101 # get confused leading to either "FUS_STATE_IMG_NOT_AUTHENTIC" or (worse)
102 # corrupting the FUS.
103 # See footnote [1] referenced by Table 9 in AN5185 - Rev 4 -- the address
104 # passed to FUS_FW_UPGRADE is ignored (implying that it must be searching the
105 # flash). This requires that the firmware files have been pre-processed by
106 # rfcore_makefirmware.py and this key must match the one there.
107 _OBFUSCATION_KEY = const(0x0573B55AA)
108
109 # On boards using the internal flash filesystem, this must match the
110 # `_micropy_hw_internal_flash_storage_end` symbol defined by the linker script
111 # (see eg boards/stm32wb55xg.ld).
112 # We erase everything from here until the start of the secure area (defined by
113 # SFSA) just to ensure that no other fragments of firmware files are left
114 # behind. On boards with external flash, this just needs to ensure that it
115 # includes any regions that may contain partial firmware data.
116 # This is non-const so it can be override.
117 STAGING_AREA_START = 0x80C0000
118
119 # First word of device info table indicating FUS state (returned by `stm.rfcore_status()`).
120 _MAGIC_FUS_ACTIVE = const(0xA94656B9) # AN5185
121 _MAGIC_IPCC_MEM_INCORRECT = const(0x3DE96F61) # # AN5185
122
123 # Argument to `stm.rfcore_fw_version()`.
124 _FW_VERSION_FUS = const(0)
125 _FW_VERSION_WS = const(1)
126
127 # No firmware update in progress. Boot normally.
128 _STATE_IDLE = const(0)
129
130 # A previous firmware update failed. Will return reason code from resume().
131 _STATE_FAILED = const(1)
132
133 # Trying to get into the FUS. Keep issuing GET_STATE until the FUS is active.
134 _STATE_WAITING_FOR_FUS = const(2)
135
136 # Trying to get into the WS. Keep issuing START_WS until the WS is active (or fails).
137 _STATE_WAITING_FOR_WS = const(3)
138
139 # FW_DELETE has been issued. Waiting for the WS version to report zero.
140 _STATE_DELETING_WS = const(4)
141
142 # Flash copy has started for FUS/WS. If a reboot occurs, then fail.
143 _STATE_COPYING_FUS = const(5)
144 _STATE_COPYING_WS = const(6)
145
146 # Flash write fully completed, ready for install.
147 _STATE_COPIED_FUS = const(7)
148 _STATE_COPIED_WS = const(8)
149
150 # Check for next update to perform.
151 # Either we've just gotten into the FUS, or the first update in a sequence
152 # has completed. (e.g. FUS done, now do WS).
153 _STATE_CHECK_UPDATES = const(9)
154
155 # Installation has started, keep polling GET_STATE.
156 _STATE_INSTALLING_WS = const(10)
157 _STATE_INSTALLING_FUS = const(11)
158
159 # Update completed successfully.
160 REASON_OK = const(0)
161 # The device reset during flash copy. Possibly WS still installed.
162 REASON_FLASH_COPY_FAILED = const(1)
163 # Unable to start the WS after firmware update.
164 REASON_NO_WS = const(2)
165 # Copying FUS image to staging area caused FUS to fail.
166 REASON_FLASH_FUS_BAD_STATE = const(3)
167 # Copying WS image to staging area caused FUS to fail.
168 REASON_FLASH_WS_BAD_STATE = const(4)
169 # Cannot get into the FUS. Perhaps rfcore misconfigured.
170 REASON_FUS_NOT_RESPONDING = const(5)
171 # After a FUS install, unable to get back to the FUS.
172 REASON_FUS_NOT_RESPONDING_AFTER_FUS = const(6)
173 # After a WS install, unable to get back to the FUS.
174 REASON_FUS_NOT_RESPONDING_AFTER_WS = const(7)
175 # Unable to query rfcore version/active.
176 REASON_RFCORE_NOT_CONFIGURED = const(8)
177 # The WS deletion didn't have any effect.
178 REASON_WS_STILL_PRESENT = const(9)
179 # FUS refused to delete the WS.
180 REASON_WS_DELETION_FAILED = const(10)
181 # FUS returned a specific code for a FUS update.
182 # See AN5185 Rev 4, Table 12. Reason between 0x00-0x11 will be added.
183 REASON_FUS_VENDOR = const(0x10)
184 # FUS returned a specific code for a WS update. Values as for the FUS update.
185 REASON_WS_VENDOR = const(0x30)
186
187 # FUS 1.0.2 must be installed before FUS 1.1.0 can be installed.
188 # A factory Nucleo board has FUS (0, 5, 3, 0, 0) and WS (0, 5, 1, 0, 0).
189 _FUS_VERSION_102 = (1, 0, 2, 0, 0)
190 _FUS_VERSION_110 = (1, 1, 0, 0, 0)
191 _PATH_FUS_102 = "fus_102.bin"
192 _PATH_FUS_110 = "fus_110.bin"
193 _PATH_WS_BLE_HCI = "ws_ble_hci.bin"
194
195 # When installing the FUS/WS it can take a long time to return to the first
196 # GET_STATE HCI command.
197 # e.g. Installing stm32wb5x_BLE_Stack_full_fw.bin takes 3600ms to respond.
198 _INSTALLING_FUS_GET_STATE_TIMEOUT = const(1000)
199 _INSTALLING_WS_GET_STATE_TIMEOUT = const(6000)
200
201
202 def log(msg, *args, **kwargs):
203 print("[rfcore update]", msg.format(*args, **kwargs))
204
205
206 class _Flash:
207 _FLASH_KEY1 = 0x45670123
208 _FLASH_KEY2 = 0xCDEF89AB
209
210 _FLASH_CR_STRT_MASK = 1 << 16
211 _FLASH_CR_LOCK_MASK = 1 << 31
212 _FLASH_SR_BSY_MASK = 1 << 16
213
214 def wait_not_busy(self):
215 while machine.mem32[stm.FLASH + stm.FLASH_SR] & _Flash._FLASH_SR_BSY_MASK:
216 machine.idle()
217
218 def unlock(self):
219 if machine.mem32[stm.FLASH + stm.FLASH_CR] & _Flash._FLASH_CR_LOCK_MASK:
220 # Only unlock if already locked (i.e. FLASH_CR_LOCK is set).
221 machine.mem32[stm.FLASH + stm.FLASH_KEYR] = _Flash._FLASH_KEY1
222 machine.mem32[stm.FLASH + stm.FLASH_KEYR] = _Flash._FLASH_KEY2
223 else:
224 log("Flash was already unlocked.")
225
226 def lock(self):
227 machine.mem32[stm.FLASH + stm.FLASH_CR] = _Flash._FLASH_CR_LOCK_MASK
228
229 def erase_page(self, page):
230 assert 0 <= page <= 255 # 1MiB range (4k page)
231 self.wait_not_busy()
232 cr = page << 3 | 1 << 1 # PNB # PER
233 machine.mem32[stm.FLASH + stm.FLASH_CR] = cr
234 machine.mem32[stm.FLASH + stm.FLASH_CR] = cr | _Flash._FLASH_CR_STRT_MASK
235 self.wait_not_busy()
236 machine.mem32[stm.FLASH + stm.FLASH_CR] = 0
237
238 def write(self, addr, buf, sz, key=0):
239 assert sz % 4 == 0
240 self.wait_not_busy()
241 cr = 1 << 0 # PG
242 machine.mem32[stm.FLASH + stm.FLASH_CR] = cr
243 off = 0
244 while off < sz:
245 v = (buf[off]) | (buf[off + 1] << 8) | (buf[off + 2] << 16) | (buf[off + 3] << 24)
246 machine.mem32[addr + off] = v ^ key
247 off += 4
248 if off % 8 == 0:
249 self.wait_not_busy()
250 if off % 8:
251 machine.mem32[addr + off] = 0
252 self.wait_not_busy()
253 machine.mem32[stm.FLASH + stm.FLASH_CR] = 0
254
255
256 def validate_crc(f):
257 """Should match copy of function in rfcore_makefirmware.py to confirm operation"""
258 f.seek(0)
259 file_crc = 0
260 chunk = 16 * 1024
261 buff = bytearray(chunk)
262 while True:
263 read = f.readinto(buff)
264 if read < chunk:
265 file_crc = crc32(buff[0:read], file_crc)
266 break
267 file_crc = crc32(buff, file_crc)
268
269 file_crc = 0xFFFFFFFF & -file_crc - 1
270 f.seek(0)
271 return file_crc == 0
272
273
274 def check_file_details(filename):
275 with open(filename, "rb") as f:
276 if not validate_crc(f):
277 raise ValueError("file validation failed: incorrect crc")
278
279 # Check the footer on the file
280 f.seek(-64, 2)
281 footer = f.read()
282 details = struct.unpack("<37sIIIIbbbII", footer)
283 (
284 src_filename,
285 addr_1m,
286 addr_640k,
287 addr_512k,
288 addr_256k,
289 vers_major,
290 vers_minor,
291 vers_patch,
292 KEY,
293 crc,
294 ) = details
295 src_filename = src_filename.strip(b"\x00").decode()
296 if KEY != _OBFUSCATION_KEY:
297 raise ValueError("file validation failed: incorrect key")
298
299 return (
300 src_filename,
301 addr_1m,
302 addr_640k,
303 addr_512k,
304 addr_256k,
305 (vers_major, vers_minor, vers_patch),
306 )
307
308
309 def _copy_file_to_flash(filename):
310 flash = _Flash()
311 flash.unlock()
312 # Reset any previously stored address
313 _write_target_addr(0)
314 try:
315 (
316 src_filename,
317 addr_1m,
318 addr_640k,
319 addr_512k,
320 addr_256k,
321 vers,
322 ) = check_file_details(filename)
323
324 # TODO add support for querying the correct flash size on chip
325 addr = load_addr = addr_1m
326
327 log(f"Writing {src_filename} v{vers[0]}.{vers[1]}.{vers[2]} to addr: 0x{addr:x}")
328
329 # Erase the entire staging area in flash.
330 erase_addr = STAGING_AREA_START
331 sfr_sfsa = machine.mem32[stm.FLASH + stm.FLASH_SFR] & 0xFF
332 erase_limit = 0x08000000 + sfr_sfsa * 4096
333 while erase_addr < erase_limit:
334 flash.erase_page((erase_addr - 0x08000000) // 4096)
335 erase_addr += 4096
336
337 # Write the contents of the firmware (note flash.write will apply the
338 # XOR de-obfuscation).
339 with open(filename, "rb") as f:
340 buf = bytearray(4096)
341
342 while 1:
343 sz = f.readinto(buf)
344 if sz == 0:
345 break
346 flash.write(addr, buf, sz, _OBFUSCATION_KEY)
347 addr += 4096
348
349 # Cache the intended target load address
350 _write_target_addr(load_addr)
351
352 finally:
353 flash.lock()
354
355
356 def _parse_vendor_response(data):
357 assert len(data) >= 7
358 assert data[0] == _HCI_KIND_VENDOR_RESPONSE
359 assert data[1] == 0x0E
360 # assert data[3] == 0xff # "Num HCI" -- docs say 0xff, but we see 0x01
361 op = (data[5] << 8) | data[4]
362 return (op >> 10, op & 0x3FF, data[6], data[7] if len(data) > 7 else 0)
363
364
365 def _run_sys_hci_cmd(ogf, ocf, buf=b"", timeout=0):
366 try:
367 ogf_out, ocf_out, status, result = _parse_vendor_response(
368 stm.rfcore_sys_hci(ogf, ocf, buf, timeout)
369 )
370 except OSError:
371 # Timeout or FUS not active.
372 return (0xFF, 0xFF)
373 assert ogf_out == ogf
374 assert ocf_out == ocf
375 return (status, result)
376
377
378 def fus_get_state(timeout=0):
379 return _run_sys_hci_cmd(_OGF_VENDOR, _OCF_FUS_GET_STATE, timeout=timeout)
380
381
382 def fus_is_idle():
383 return fus_get_state() == (0, 0)
384
385
386 def fus_start_ws():
387 return _run_sys_hci_cmd(_OGF_VENDOR, _OCF_FUS_START_WS)
388
389
390 def _fus_fwdelete():
391 return _run_sys_hci_cmd(_OGF_VENDOR, _OCF_FUS_FW_DELETE)
392
393
394 def _fus_run_fwupgrade():
395 # Note: Address is ignored by the FUS (see comments above).
396 addr = _read_target_addr()
397 if not addr:
398 log(f"Update failed: Invalid load address: 0x{addr:x}")
399 return False
400
401 log(f"Loading to: 0x{addr:x}")
402 return _run_sys_hci_cmd(_OGF_VENDOR, _OCF_FUS_FW_UPGRADE, struct.pack("<I", addr))
403
404
405 if stm:
406 # Get/set current state/reason/addr to RTC Backup Domain.
407 # Using the second, third, and fourth-last registers (16, 17, 18) as
408 # the final one (19) is reserved by powerctrl.c for restoring the frequency.
409 # Can be overridden if necessary.
410 REG_RTC_STATE = stm.RTC + stm.RTC_BKP18R
411 REG_RTC_REASON = stm.RTC + stm.RTC_BKP17R
412 REG_RTC_ADDR = stm.RTC + stm.RTC_BKP16R
413
414
415 def _read_state():
416 return machine.mem32[REG_RTC_STATE]
417
418
419 def _write_state(state):
420 machine.mem32[REG_RTC_STATE] = state
421
422
423 def _read_failure_reason():
424 return machine.mem32[REG_RTC_REASON]
425
426
427 def _write_failure_state(reason):
428 machine.mem32[REG_RTC_REASON] = reason
429 _write_state(_STATE_FAILED)
430 return reason
431
432
433 def _read_target_addr():
434 return machine.mem32[REG_RTC_ADDR]
435
436
437 def _write_target_addr(addr):
438 machine.mem32[REG_RTC_ADDR] = addr
439
440
441 # Check for the presence of a given file and attempt to start installing it.
442 def _stat_and_start_copy(path, copying_state, copied_state):
443 try:
444 os.stat(path)
445 except OSError:
446 log("{} not found", path)
447 return False
448
449 log("{} update is available", path)
450 if sum(stm.rfcore_fw_version(_FW_VERSION_WS)):
451 # There was some WS firmware already installed. Need to remove that
452 # before copying to flash (both FUS or WS copy require this).
453 log("Removing existing WS firmware")
454 _write_state(_STATE_DELETING_WS)
455 _fus_fwdelete()
456 else:
457 log("Copying {} to flash", path)
458 # Mark that the flash write has started. Any failure should result in an overall failure.
459 _write_state(copying_state) # Either _STATE_COPYING_FUS or _STATE_COPYING_WS
460 _copy_file_to_flash(path)
461 log("Copying complete")
462 # The entire write has completed successfully, start the install.
463 _write_state(copied_state) # Either _STATE_COPIED_FUS or _STATE_COPIED_WS
464
465 return True
466
467
468 # This should be called in boot.py to resume any in-progress update.
469 # If there's nothing to do, it will return 0 and the app can continue as normal.
470 # If a previous update has failed, then it will return the failure reason.
471 # Otherwise it will attempt to continue the update from where it left off.
472 def resume():
473 log("Checking firmware update progress...")
474
475 if stm.rfcore_status() == _MAGIC_IPCC_MEM_INCORRECT:
476 return _write_failure_state(REASON_RFCORE_NOT_CONFIGURED)
477
478 while True:
479 state = _read_state()
480
481 if state == _STATE_IDLE:
482 log("Firmware update complete")
483 return 0
484
485 elif state == _STATE_FAILED:
486 log("Firmware update failed")
487 return _read_failure_reason()
488
489 # Keep calling GET_STATE until error or FUS.
490 elif state == _STATE_WAITING_FOR_FUS:
491 log("Querying FUS state")
492 status, result = fus_get_state()
493 log("FUS state: {} {}", status, result)
494
495 if status == 0xFF and result == 0xFF:
496 _write_failure_state(REASON_FUS_NOT_RESPONDING)
497 elif status != 0:
498 log("Operation in progress. Re-querying FUS state")
499 elif stm.rfcore_status() == _MAGIC_FUS_ACTIVE:
500 log("FUS active")
501 _write_state(_STATE_CHECK_UPDATES)
502
503 # Keep trying to start the WS until !fus_active() (or error).
504 elif state == _STATE_WAITING_FOR_WS:
505 if stm.rfcore_status() != _MAGIC_FUS_ACTIVE:
506 log("WS active")
507 _write_state(_STATE_IDLE)
508 # Need to force a reset otherwise BLE will fail if FUS has changed.
509 machine.reset()
510 else:
511 log("Starting WS")
512 status, result = fus_start_ws()
513 if status != 0:
514 log("Can't start WS")
515 log("WS version: {}", stm.rfcore_fw_version(_FW_VERSION_WS))
516 _write_failure_state(REASON_NO_WS)
517
518 # Sequence the FUS 1.0.2 -> FUS 1.1.0 -> WS (depending on what's available).
519 elif state == _STATE_CHECK_UPDATES:
520 log("Checking for updates")
521 fus_version = stm.rfcore_fw_version(_FW_VERSION_FUS)
522 log("FUS version {}", fus_version)
523 if fus_version < _FUS_VERSION_102:
524 log("Factory FUS detected")
525 if _stat_and_start_copy(_PATH_FUS_102, _STATE_COPYING_FUS, _STATE_COPIED_FUS):
526 continue
527 elif fus_version >= _FUS_VERSION_102 and fus_version < _FUS_VERSION_110:
528 log("FUS 1.0.2 detected")
529 if _stat_and_start_copy(_PATH_FUS_110, _STATE_COPYING_FUS, _STATE_COPIED_FUS):
530 continue
531 else:
532 log("FUS is up-to-date")
533
534 if fus_version >= _FUS_VERSION_110:
535 if _stat_and_start_copy(
536 _PATH_WS_BLE_HCI,
537 _STATE_COPYING_WS,
538 _STATE_COPIED_WS,
539 ):
540 continue
541 else:
542 log("No WS updates available")
543 else:
544 # Don't attempt to install WS if we're running an old FUS.
545 log("Need latest FUS to install WS")
546
547 # Attempt to go back to WS.
548 # Either this will fail (because WS was removed due to FUS install), or
549 # this whole thing was a no-op and we should be fine to restart WS.
550 _write_state(_STATE_WAITING_FOR_WS)
551
552 # This shouldn't happen - the flash write should always complete and
553 # move straight onto the COPIED state. Failure here indicates that
554 # the rfcore is misconfigured or the WS firmware was not deleted first.
555 elif state == _STATE_COPYING_FUS or state == _STATE_COPYING_WS:
556 log("Flash copy failed mid-write")
557 _write_failure_state(REASON_FLASH_COPY_FAILED)
558
559 # Flash write completed, we should immediately see GET_STATE return 0,0
560 # so we can start the FUS install.
561 elif state == _STATE_COPIED_FUS:
562 if fus_is_idle():
563 log("FUS copy complete, installing")
564 _write_state(_STATE_INSTALLING_FUS)
565 _fus_run_fwupgrade()
566 else:
567 log("FUS copy bad state")
568 _write_failure_state(REASON_FLASH_FUS_BAD_STATE)
569
570 # Keep polling the state until we see a 0,0 (success) or non-transient
571 # error. In general we should expect to see (16,0) several times,
572 # followed by a (255,0), followed by (0, 0).
573 elif state == _STATE_INSTALLING_FUS:
574 log("Installing FUS...")
575 status, result = fus_get_state(_INSTALLING_FUS_GET_STATE_TIMEOUT)
576 log("FUS state: {} {}", status, result)
577 if 0x20 <= status <= 0x2F and result == 0:
578 # FUS_STATE_FUS_UPGRD_ONGOING
579 log("FUS still in progress...")
580 elif 0x10 <= status <= 0x1F and result == 0x11:
581 # FUS_STATE_FW_UPGRD_ONGOING and FUS_FW_ROLLBACK_ERROR
582 # Confusingly this is a "FW_UPGRD" (0x10) not "FUS_UPRD" (0x20).
583 log("Attempted to install same FUS version... re-querying FUS state to resume.")
584 elif status == 0:
585 log("FUS update successful")
586 _write_state(_STATE_CHECK_UPDATES)
587 elif result == 0:
588 # See below (for equivalent path for WS install -- we
589 # sometimes see (255,0) right at the end).
590 log("Re-querying FUS state...")
591 elif result == 0xFF:
592 _write_failure_state(REASON_FUS_NOT_RESPONDING_AFTER_FUS)
593 else:
594 _write_failure_state(REASON_FUS_VENDOR + result)
595
596 # Keep polling the state until we see 0,0 or failure (1,0). Any other
597 # result means retry (but the docs say that 0 and 1 are the only
598 # status values).
599 elif state == _STATE_DELETING_WS:
600 log("Deleting WS...")
601 status, result = fus_get_state()
602 log("FUS state: {} {}", status, result)
603 if status == 0:
604 if sum(stm.rfcore_fw_version(_FW_VERSION_WS)) == 0:
605 log("WS deletion complete")
606 _write_state(_STATE_CHECK_UPDATES)
607 else:
608 log("WS deletion no effect")
609 _write_failure_state(REASON_WS_STILL_PRESENT)
610 elif status == 1:
611 log("WS deletion failed")
612 _write_failure_state(REASON_WS_DELETION_FAILED)
613
614 # As for _STATE_COPIED_FUS above. We should immediately see 0,0.
615 elif state == _STATE_COPIED_WS:
616 if fus_is_idle():
617 log("WS copy complete, installing")
618 _write_state(_STATE_INSTALLING_WS)
619 _fus_run_fwupgrade()
620 else:
621 log("WS copy bad state")
622 _write_failure_state(REASON_FLASH_WS_BAD_STATE)
623
624 # As for _STATE_INSTALLING_FUS above.
625 elif state == _STATE_INSTALLING_WS:
626 log("Installing WS...")
627 status, result = fus_get_state(_INSTALLING_WS_GET_STATE_TIMEOUT)
628 log("FUS state: {} {}", status, result)
629 if 0x10 <= status <= 0x1F and result == 0:
630 # FUS_STATE_FW_UPGRD_ONGOING
631 log("WS still in progress...")
632 elif 0x10 <= status <= 0x1F and result == 0x11:
633 # FUS_FW_ROLLBACK_ERROR
634 log("Attempted to install same WS version... re-querying FUS state to resume.")
635 elif status == 0:
636 log("WS update successful")
637 _write_state(_STATE_WAITING_FOR_WS)
638 elif result in (0, 0xFE):
639 # We get an error response with no payload sometimes at the end
640 # of the update (this is not in AN5185). Additionally during
641 # WS update, newer WS reports (status, result) of (255, 254)
642 # before eventually reporting the correct state of
643 # _STATE_INSTALLING_WS once again. In these cases, re-try the
644 # GET_STATE.
645 # The same thing happens transitioning from WS to FUS mode.
646 # The actual HCI response has no payload, the result=0 comes from
647 # _parse_vendor_response above when len=7.
648 log("Re-querying FUS state...")
649 elif result == 0xFF:
650 # This is specifically a failure sending the HCI command.
651 _write_failure_state(REASON_FUS_NOT_RESPONDING_AFTER_WS)
652 else:
653 _write_failure_state(REASON_WS_VENDOR + result)
654
655
656 def install_boot():
657 boot_py = "/flash/boot.py"
658 header = ""
659 mode = "w"
660 try:
661 with open(boot_py, "r") as boot:
662 header = "\n"
663 mode = "a"
664 for line in boot:
665 if "rfcore_firmware.resume()" in line:
666 print("Already installed.")
667 return
668
669 print("boot.py exists, adding upgrade handler.")
670 except OSError:
671 print("boot.py doesn't exists, adding with upgrade handler.")
672
673 with open(boot_py, mode) as boot:
674 boot.write(header)
675 boot.write("# Handle rfcore updates.\n")
676 boot.write("import rfcore_firmware\n")
677 boot.write("rfcore_firmware.resume()\n")
678
679
680 # Start a firmware update.
681 # This will immediately trigger a reset and start the update process on boot.
682 def check_for_updates(force=False):
683 (
684 src_filename,
685 addr_1m,
686 addr_640k,
687 addr_512k,
688 addr_256k,
689 vers_fus,
690 ) = check_file_details(_PATH_FUS_110)
691 (
692 src_filename,
693 addr_1m,
694 addr_640k,
695 addr_512k,
696 addr_256k,
697 vers_ws,
698 ) = check_file_details(_PATH_WS_BLE_HCI)
699 current_version_fus = stm.rfcore_fw_version(_FW_VERSION_FUS)
700 fus_uptodate = current_version_fus[0:3] == vers_fus
701
702 current_version_ws = stm.rfcore_fw_version(_FW_VERSION_WS)
703 ws_uptodate = current_version_ws[0:3] == vers_ws
704 if fus_uptodate and ws_uptodate and not force:
705 log(f"Already up to date: fus: {current_version_fus}, ws: {current_version_ws}")
706 else:
707 log("Starting firmware update")
708 log(f" - fus: {current_version_fus} -> {vers_fus}")
709 log(f" - ws: {current_version_ws} -> {vers_ws}")
710 _write_state(_STATE_WAITING_FOR_FUS)
711 machine.reset()