Add tools/install_release.py, a host script that takes a release from Gitea and puts it on a board over USB the way an update would: it downloads the release's application image and checks it against the release checksums, writes it to the slot that is not running, and rewrites otadata to select that slot as a new image before resetting the board. It reads the board's own partition table and slot selection rather than assuming a layout, refuses a board without the A/B partition table, and writes nothing until the image has been downloaded and verified. A dry run shows what it would do. This lets the A/B slots be tested with real releases while there is no over-the-air update source. The README documents it, and the full image's install steps now clear the slot selection, so that a board which had switched to the second slot runs the image just written. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
1 parent
ae5ed848ad
commit
c6b1537c8c
2 files changed
+303
-2
No files matched your search
@@ -159,12 +159,38 @@ Each release has:
|
||||
|
||||
- `smart-light-<version>-full.bin`: bootloader, partition table and
|
||||
application. Write it at address 0 with
|
||||
`espflash write-bin 0x0 smart-light-<version>-full.bin`. It stops short of
|
||||
the `storage` partition, so the light keeps its Zigbee network.
|
||||
`espflash write-bin 0x0 smart-light-<version>-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-<version>.bin`: the application alone, for a firmware slot.
|
||||
- `smart-light-<version>.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`.
|
||||
|
||||
Executable
+275
@@ -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("<BBII", entry, 2)
|
||||
label = entry[12:28].split(b"\0")[0].decode(errors="replace")
|
||||
partitions[label] = (kind, subtype, offset, size)
|
||||
return partitions
|
||||
|
||||
|
||||
def find_layout(partitions):
|
||||
otadata = next(
|
||||
(
|
||||
p
|
||||
for p in partitions.values()
|
||||
if p[0] == TYPE_DATA and p[1] == SUBTYPE_OTA_DATA
|
||||
),
|
||||
None,
|
||||
)
|
||||
slots = sorted(
|
||||
(
|
||||
p
|
||||
for p in partitions.values()
|
||||
if p[0] == TYPE_APP and SUBTYPE_OTA_FIRST <= p[1] <= SUBTYPE_OTA_LAST
|
||||
),
|
||||
key=lambda p: p[1],
|
||||
)
|
||||
if otadata is None or len(slots) < 2:
|
||||
raise Error(
|
||||
"the board does not have the A/B partition table (an otadata partition "
|
||||
"and two OTA app slots). Flash a release's full image first; see the README."
|
||||
)
|
||||
return otadata, slots
|
||||
|
||||
|
||||
def checksum(sequence):
|
||||
"""The checksum the bootloader keeps with a selection record: CRC-32 of the
|
||||
sequence number alone, started from all ones."""
|
||||
return zlib.crc32(struct.pack("<I", sequence), 0xFFFFFFFF)
|
||||
|
||||
|
||||
def parse_record(sector):
|
||||
"""The (sequence, state) of a selection record, or None if there is no valid
|
||||
one in the sector."""
|
||||
sequence, = struct.unpack_from("<I", sector, 0)
|
||||
state, stored = struct.unpack_from("<II", sector, 24)
|
||||
if sequence == UNINITIALISED or state not in STATE_NAMES:
|
||||
return None
|
||||
return (sequence, state) if stored == checksum(sequence) else None
|
||||
|
||||
|
||||
def current_selection(otadata, slot_count):
|
||||
"""Returns (slot, state, record index, sequence) for the slot the bootloader
|
||||
will run, or None if nothing has been selected yet."""
|
||||
records = [
|
||||
parse_record(otadata[i * SECTOR : (i + 1) * SECTOR]) for i in range(2)
|
||||
]
|
||||
valid = [(record[0], i, record[1]) for i, record in enumerate(records) if record]
|
||||
if not valid:
|
||||
return None
|
||||
sequence, index, state = max(valid)
|
||||
return ((sequence - 1) % slot_count, state, index, sequence)
|
||||
|
||||
|
||||
def new_record(sequence):
|
||||
"""A selection record for a new image, padded to a whole sector."""
|
||||
record = struct.pack("<I20sII", sequence, b"\xff" * 20, STATE_NEW, checksum(sequence))
|
||||
return record + b"\xff" * (SECTOR - len(record))
|
||||
|
||||
|
||||
def next_sequence(selection, target, slot_count):
|
||||
"""The lowest sequence number above the current one that selects `target`.
|
||||
The slot is the sequence number, minus one, modulo the number of slots."""
|
||||
sequence = (selection[3] if selection else 0) + 1
|
||||
while (sequence - 1) % slot_count != target:
|
||||
sequence += 1
|
||||
return sequence
|
||||
|
||||
|
||||
def fetch(url):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response:
|
||||
return response.read()
|
||||
except urllib.error.URLError as error:
|
||||
raise Error(f"could not fetch {url}: {error}") from error
|
||||
|
||||
|
||||
def latest_version():
|
||||
release = json.loads(fetch(f"{SERVER}/api/v1/repos/{REPO}/releases/latest"))
|
||||
return release["tag_name"].lstrip("v")
|
||||
|
||||
|
||||
def download_image(version, slot_size):
|
||||
base = f"{SERVER}/{REPO}/releases/download/v{version}"
|
||||
name = f"smart-light-{version}.bin"
|
||||
image = fetch(f"{base}/{name}")
|
||||
sums = fetch(f"{base}/SHA256SUMS").decode()
|
||||
|
||||
expected = {}
|
||||
for line in sums.splitlines():
|
||||
if line.strip():
|
||||
digest, filename = line.split(None, 1)
|
||||
expected[filename.strip().lstrip("*")] = digest
|
||||
if name not in expected:
|
||||
raise Error(f"{name} is not in the release's SHA256SUMS")
|
||||
if hashlib.sha256(image).hexdigest() != expected[name]:
|
||||
raise Error(f"{name} does not match the release's checksum")
|
||||
if image[0] != APP_IMAGE_MAGIC:
|
||||
raise Error(f"{name} is not an application image")
|
||||
if len(image) > 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}")
|
||||
Reference in new issue
Block a user