Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6b1537c8c | ||
|
|
ae5ed848ad | ||
|
|
35fe7c7bf9 | ||
|
|
bf031b55b7 | ||
|
|
9e7d0d7d1f | ||
|
|
c92adaed01 |
No files matched your search
@@ -0,0 +1,128 @@
|
||||
name: release
|
||||
|
||||
# Every commit to main builds the firmware and publishes a release.
|
||||
#
|
||||
# The version is MAJOR.MINOR from the version in Cargo.toml, with the number
|
||||
# of commits on main as the patch number, so it only ever goes up and can be
|
||||
# worked out again from any commit: Cargo.toml saying 0.1.0 gives 0.1.57 for
|
||||
# the 57th commit. Change MAJOR or MINOR in Cargo.toml to start a new series.
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Must match a label of the Gitea runner.
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
ESPFLASH_VERSION: v4.6.0
|
||||
steps:
|
||||
- name: Check out the repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# the commit count and the previous release tag need the history
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Fetch the Zigbee stack
|
||||
run: |
|
||||
# the submodule is declared with an SSH address; a runner has no key
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init
|
||||
|
||||
- name: Work out the version
|
||||
id: version
|
||||
run: |
|
||||
base=$(sed -n 's/^version = "\([0-9]*\.[0-9]*\)\..*"/\1/p' Cargo.toml | head -n 1)
|
||||
count=$(git rev-list --count HEAD)
|
||||
version="$base.$count"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "Releasing $version"
|
||||
|
||||
# the firmware reads its version from the package, so this is what
|
||||
# ends up in the app descriptor and the boot log
|
||||
sed -i '0,/^version = ".*"/s//version = "'"$version"'"/' Cargo.toml
|
||||
|
||||
- name: Install Rust
|
||||
run: |
|
||||
if ! command -v rustup > /dev/null; then
|
||||
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||
fi
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
# installs the toolchain, components and target that
|
||||
# rust-toolchain.toml asks for
|
||||
rustup toolchain install || true
|
||||
cargo --version
|
||||
|
||||
- name: Install espflash
|
||||
run: |
|
||||
curl -fsSL -o espflash.zip \
|
||||
"https://github.com/esp-rs/espflash/releases/download/${ESPFLASH_VERSION}/espflash-x86_64-unknown-linux-musl.zip"
|
||||
python3 -m zipfile -e espflash.zip "$HOME/espflash-bin"
|
||||
chmod +x "$HOME/espflash-bin/espflash"
|
||||
echo "$HOME/espflash-bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Build the firmware
|
||||
run: cargo build --release
|
||||
|
||||
- name: Package the images
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
elf=target/riscv32imac-unknown-none-elf/release/smart-light
|
||||
mkdir dist
|
||||
|
||||
# the application on its own: what goes into a firmware slot
|
||||
espflash save-image --chip esp32c6 --flash-size 4mb "$elf" "dist/smart-light-$VERSION.bin"
|
||||
|
||||
# bootloader, partition table and application, to be written at
|
||||
# address 0. Without padding it stops short of the storage
|
||||
# partition, so flashing it keeps the light's Zigbee network.
|
||||
espflash save-image --chip esp32c6 --flash-size 4mb --merge --skip-padding \
|
||||
--partition-table partitions.csv "$elf" "dist/smart-light-$VERSION-full.bin"
|
||||
|
||||
# for decoding backtraces
|
||||
gzip -9 -c "$elf" > "dist/smart-light-$VERSION.elf.gz"
|
||||
|
||||
(cd dist && sha256sum * > SHA256SUMS)
|
||||
ls -l dist
|
||||
|
||||
- name: Publish the release
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
# the job's own token if it may create releases, otherwise a token
|
||||
# kept in the RELEASE_TOKEN secret
|
||||
TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
previous=$(git describe --tags --abbrev=0 --match 'v*' 2> /dev/null || true)
|
||||
notes=$(git log --no-merges --pretty='- %s (%h)' -n 50 ${previous:+"$previous..HEAD"})
|
||||
|
||||
payload=$(python3 -c '
|
||||
import json, sys
|
||||
version, sha, notes = sys.argv[1:4]
|
||||
body = "Built from " + sha[:7] + ".\n\n" + notes
|
||||
print(json.dumps({
|
||||
"tag_name": "v" + version,
|
||||
"target_commitish": sha,
|
||||
"name": "smart-light " + version,
|
||||
"body": body,
|
||||
"draft": False,
|
||||
"prerelease": False,
|
||||
}))' "$VERSION" "$GITHUB_SHA" "$notes")
|
||||
|
||||
response=$(curl -fsS -X POST \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$payload" "$API/repos/$REPO/releases")
|
||||
id=$(printf '%s' "$response" | python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')
|
||||
|
||||
for file in dist/*; do
|
||||
curl -fsS -X POST \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$file" \
|
||||
"$API/repos/$REPO/releases/$id/assets?name=$(basename "$file")" > /dev/null
|
||||
echo "uploaded $(basename "$file")"
|
||||
done
|
||||
@@ -2,6 +2,7 @@
|
||||
name = "smart-light"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
|
||||
[features]
|
||||
default = ["esp32c6", "zigbee"]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Matt Spencer
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -142,3 +142,60 @@ sets its speed and intensity. Home Assistant needs a quirk to talk to it:
|
||||
|
||||
3. Restart Home Assistant. The light then has an Effect select and Effect speed
|
||||
and Effect intensity sliders.
|
||||
|
||||
## Releases
|
||||
|
||||
Every commit to `main` builds the firmware on the Gitea runner and publishes a
|
||||
release (`.gitea/workflows/release.yml`).
|
||||
|
||||
The version is the `MAJOR.MINOR` of the version in `Cargo.toml` followed by the
|
||||
number of commits on `main`, so with `0.1.0` in `Cargo.toml` the 57th commit
|
||||
becomes `0.1.57`. It only goes up, and can be worked out again from any commit.
|
||||
To start a new series, change the major or minor number in `Cargo.toml`. The
|
||||
build writes the version into the firmware, which logs it at boot, and the
|
||||
release is tagged `v` plus the version.
|
||||
|
||||
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`, 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`.
|
||||
|
||||
## License
|
||||
|
||||
Released under the [MIT License](LICENSE). The Zigbee stack in
|
||||
`vendor/zigbee-rs` is a separate project with its own licenses.
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
[toolchain]
|
||||
channel = "nightly"
|
||||
# pinned, so that a release builds the same way every time: a floating
|
||||
# "nightly" changes under the project. Move it forward deliberately.
|
||||
channel = "nightly-2026-10-17"
|
||||
components = ["rust-src", "rustfmt", "clippy"]
|
||||
targets = ["riscv32imac-unknown-none-elf"]
|
||||
@@ -45,6 +45,7 @@ const BRIGHTNESS_STEP: i16 = 8;
|
||||
#[esp_rtos::main]
|
||||
async fn main(spawner: embassy_executor::Spawner) -> ! {
|
||||
esp_println::logger::init_logger_from_env();
|
||||
log::info!("smart-light {}", env!("CARGO_PKG_VERSION"));
|
||||
let peripherals = esp_hal::init(esp_hal::Config::default());
|
||||
|
||||
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
||||
|
||||
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