diff --git a/README.md b/README.md index 71b3bd9..530c5cc 100644 --- a/README.md +++ b/README.md @@ -159,12 +159,38 @@ Each release has: - `smart-light--full.bin`: bootloader, partition table and application. Write it at address 0 with - `espflash write-bin 0x0 smart-light--full.bin`. It stops short of - the `storage` partition, so the light keeps its Zigbee network. + `espflash write-bin 0x0 smart-light--full.bin`, then clear the slot + selection with `espflash erase-parts otadata` so that the board runs it. + The image stops short of the `storage` partition, so the light keeps its + Zigbee network. - `smart-light-.bin`: the application alone, for a firmware slot. - `smart-light-.elf.gz`: the unstripped build, for decoding backtraces. - `SHA256SUMS`. +### Installing a release over USB + +Once a board has the A/B partition table, `tools/install_release.py` installs a +release into the slot that is not running and switches to it, without +touching the running image until the new one has been downloaded and checked: + +```sh +tools/install_release.py # the latest release +tools/install_release.py 0.1.23 # a particular one +tools/install_release.py --dry-run # show what would be done, write nothing +``` + +It reads the board's partition table and slot selection, downloads the release's +application image and checks it against `SHA256SUMS`, writes it to the idle +slot, rewrites `otadata` to select that slot as a new image, and resets the +board. The firmware logs the version it is running, which slot it came from, +and when it confirms the image, so the log shows the update has worked. Run it +again and the board alternates to the other slot. + +This is a way of testing the A/B slots with real releases, not an update +mechanism for lights in use: it needs the board on a USB cable. There is no +rollback yet (see `TODO.md`), so an image that does not start has to be fixed +by flashing over USB. + The workflow's `runs-on` must match a label of your Gitea runner. If the job's own token is not allowed to create releases, add a token with write access to the repository as a secret named `RELEASE_TOKEN`. diff --git a/tools/install_release.py b/tools/install_release.py new file mode 100755 index 0000000..1c60797 --- /dev/null +++ b/tools/install_release.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Install a release into the idle firmware slot of a connected board, and +switch the board to it. + + tools/install_release.py # the latest release + tools/install_release.py 0.1.23 # a particular one + tools/install_release.py --dry-run # only show what would be done + +The release's application image is downloaded, checked against the release's +checksums, and written to the slot that is not running. The board's `otadata` +partition is then rewritten to select that slot, marked as a new image, and the +board is reset. The firmware logs the version it is running and which slot it +came from, and confirms the new image once it has stayed up for a while. + +Needs `espflash` and a board with the A/B partition table, connected over USB. +Nothing is written to the board until the image has been downloaded and checked. +""" + +import argparse +import hashlib +import json +import shutil +import struct +import subprocess +import sys +import tempfile +import urllib.error +import urllib.request +import zlib +from pathlib import Path + +SERVER = "https://gitea.m5p3nc3r.co.uk" +REPO = "m5p3nc3r/smart_lights" + +PARTITION_TABLE_OFFSET = 0x8000 +PARTITION_TABLE_SIZE = 0xC00 + +# partition types and subtypes, as the bootloader numbers them +TYPE_APP, TYPE_DATA = 0x00, 0x01 +SUBTYPE_OTA_FIRST, SUBTYPE_OTA_LAST = 0x10, 0x1F +SUBTYPE_OTA_DATA = 0x00 + +# otadata is two sectors, each holding one 32-byte selection record +SECTOR = 0x1000 +UNINITIALISED = 0xFFFFFFFF +STATE_NEW = 0x0 +STATE_NAMES = { + 0x0: "New", + 0x1: "PendingVerify", + 0x2: "Valid", + 0x3: "Invalid", + 0x4: "Aborted", + UNINITIALISED: "Undefined", +} + +APP_IMAGE_MAGIC = 0xE9 + + +class Error(Exception): + """Something the user needs to know about, without a traceback.""" + + +def espflash(args, port): + command = ["espflash", *args] + if port: + command += ["--port", port] + result = subprocess.run(command, capture_output=True, text=True) + if result.returncode != 0: + raise Error(f"`{' '.join(command)}` failed:\n{result.stdout}{result.stderr}") + + +def read_flash(offset, size, port, directory): + path = directory / f"read-{offset:#x}.bin" + espflash(["read-flash", f"{offset:#x}", f"{size:#x}", str(path)], port) + return path.read_bytes() + + +def write_flash(offset, data, port, directory): + path = directory / f"write-{offset:#x}.bin" + path.write_bytes(data) + espflash(["write-bin", f"{offset:#x}", str(path)], port) + + +def parse_partition_table(data): + """Maps each partition's label to (type, subtype, offset, size).""" + partitions = {} + for start in range(0, len(data) - 31, 32): + entry = data[start : start + 32] + if entry[:2] != b"\xaa\x50": + break # the end marker, or the table's checksum entry + kind, subtype, offset, size = struct.unpack_from(" slot_size: + raise Error(f"{name} is {len(image)} bytes and the slot holds {slot_size}") + return image + + +def describe(selection): + if selection is None: + return "nothing selected yet (the bootloader runs the first slot)" + slot, state, _, sequence = selection + return f"slot {slot} (sequence {sequence}), image state {STATE_NAMES[state]}" + + +def main(): + parser = argparse.ArgumentParser( + description="Install a release into the idle firmware slot and switch to it." + ) + parser.add_argument( + "version", nargs="?", default="latest", help="e.g. 0.1.23 (default: the latest)" + ) + parser.add_argument("--port", help="serial port of the board, if there are several") + parser.add_argument( + "--slot", type=int, help="write to this slot instead of the idle one" + ) + parser.add_argument( + "--dry-run", action="store_true", help="show what would be done; write nothing" + ) + parser.add_argument( + "--no-reset", action="store_true", help="do not reset the board afterwards" + ) + args = parser.parse_args() + + if shutil.which("espflash") is None: + raise Error("espflash is not installed (cargo install espflash)") + + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + + print("Reading the board's partition table and slot selection...") + table = read_flash(PARTITION_TABLE_OFFSET, PARTITION_TABLE_SIZE, args.port, directory) + otadata_partition, slots = find_layout(parse_partition_table(table)) + otadata_offset = otadata_partition[2] + otadata = read_flash(otadata_offset, 2 * SECTOR, args.port, directory) + + selection = current_selection(otadata, len(slots)) + running = selection[0] if selection else 0 + target = args.slot if args.slot is not None else 1 - running + if not 0 <= target < len(slots): + raise Error(f"there is no slot {target}") + print(f" the board will run {describe(selection)}") + print(f" the image goes into slot {target} at {slots[target][2]:#x}") + + version = latest_version() if args.version == "latest" else args.version.lstrip("v") + print(f"Downloading release {version}...") + image = download_image(version, slots[target][3]) + print(f" {len(image)} bytes, checksum verified") + + if args.dry_run: + print("Dry run: nothing written.") + return + + print(f"Writing slot {target}...") + write_flash(slots[target][2], image, args.port, directory) + + sequence = next_sequence(selection, target, len(slots)) + sector = 0 if selection is None else 1 - selection[2] + print(f"Selecting slot {target} (sequence {sequence}, record {sector})...") + write_flash(otadata_offset + sector * SECTOR, new_record(sequence), args.port, directory) + + if args.no_reset: + print("Done. Reset the board to run it.") + else: + espflash(["reset"], args.port) + print(f"Done. The board is restarting into {version}.") + + +if __name__ == "__main__": + try: + main() + except Error as error: + sys.exit(f"error: {error}")