Debian Codegraph @

ports/stm32/boards/LEGO_HUB_NO6/appupdate.py

raw
1 # Application firmware update function for LEGO_HUB_NO6.
2 # MIT license; Copyright (c) 2022-2024 Damien P. George
3
4 from micropython import const
5 import random, struct, machine, fwupdate, spiflash, pyb
6
7 _IOCTL_BLOCK_COUNT = const(4)
8 _IOCTL_BLOCK_SIZE = const(5)
9
10 # Mboot addresses the external SPI flash at this location.
11 _MBOOT_SPIFLASH_BASE_ADDR = 0x80000000
12
13 # The raw filesystem is in the first 1MiB of external SPI flash,
14 # but skip the first and last flash sectors.
15 _RAW_FILESYSTEM_ADDR = const(4 * 1024)
16 _RAW_FILESYSTEM_LEN = const(1016 * 1024)
17
18
19 def _copy_file_to_raw_filesystem(filename, flash, block):
20 block_count = flash.ioctl(_IOCTL_BLOCK_COUNT, 0)
21 block_size = flash.ioctl(_IOCTL_BLOCK_SIZE, 0)
22 buf = bytearray(block_size)
23 with open(filename, "rb") as file:
24 while True:
25 n = file.readinto(buf)
26 if not n:
27 break
28 flash.writeblocks(block, buf)
29 block += 1
30 if block >= block_count:
31 print("|", end="")
32 block = 0
33 print(".", end="")
34 print()
35
36
37 def update_app(filename):
38 print(f"Updating application firmware from {filename}")
39
40 # We can't use pyb.Flash() because we need to write to the "reserved" 1M area.
41 flash = spiflash.SPIFlash(start=_RAW_FILESYSTEM_ADDR, len=_RAW_FILESYSTEM_LEN)
42
43 # Partition the raw filesystem into two segments for wear levelling.
44 block_count = flash.ioctl(_IOCTL_BLOCK_COUNT, 0)
45 block_size = flash.ioctl(_IOCTL_BLOCK_SIZE, 0)
46 block_start = random.randrange(0, block_count)
47 print(f"Raw filesystem block layout: 0 .. {block_start} .. {block_count}")
48
49 # Copy the file to the special raw filesystem.
50 _copy_file_to_raw_filesystem(filename, flash, block_start)
51
52 # Enter mboot with a request to do a filesystem-load update.
53 # Note: the filename doesn't mean anything here, but still needs to be non-empty.
54 fwupdate.update_mpy(
55 filename,
56 fs_type=fwupdate.VFS_RAW,
57 fs_base=_MBOOT_SPIFLASH_BASE_ADDR + _RAW_FILESYSTEM_ADDR + block_start * block_size,
58 fs_len=(block_count - block_start) * block_size,
59 fs_base2=_MBOOT_SPIFLASH_BASE_ADDR + _RAW_FILESYSTEM_ADDR,
60 fs_len2=block_start * block_size,
61 )