From 66b2490599113d7f4e89efab31a445e12aa76506 Mon Sep 17 00:00:00 2001 From: WiFiGUY512 <339406050+WiFiGUY512@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:03:01 -0600 Subject: [PATCH 1/3] Record converted plugs by default convert now appends each converted plug (time, name, both MACs) to switchback-plugs.csv in the home folder. --log picks another file and --no-log turns it off. A log that cannot be written no longer stops a run. The README also says what label size --printer expects. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 6 ++++++ README.md | 3 ++- SECURITY.md | 2 ++ src/switchback/cli.py | 11 +++++++++-- src/switchback/convert.py | 7 +++++-- tests/test_wifiscan.py | 9 +++++++++ 6 files changed, 33 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 727c777..e1e70d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## Unreleased + +### Changed + +- `convert` records every converted plug by default, in `switchback-plugs.csv` in your home folder (time, name, both MACs). `--log` picks another file and `--no-log` turns it off. A log that cannot be written no longer stops a run. + ## [0.4.0] - 2026-11-22 A converted plug now boots the full hardware profile, so it reports power and energy right away. No second flash is needed before it is useful. diff --git a/README.md b/README.md index a1f0cad..ab28545 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,8 @@ Useful options for `convert`: - `--server http://` uses a `switchback serve` running on another machine, so you can carry a laptop to the plugs. - `--fw-byte 0D` sets the update trigger's version byte. Switchback already tries 0C, 0D and 0E. - `--domain .lan` finds converted plugs by DNS name when mDNS cannot cross VLANs. -- `--log plugs.csv` keeps a record of converted plugs. `--printer host:9100` prints a label. +- Every converted plug is recorded in `switchback-plugs.csv` in your home folder: time, name and both MAC addresses. The file stays on your computer. `--log other.csv` picks another file and `--no-log` turns it off. +- `--printer host:9100` prints a label on a ZPL printer. The layout is fixed for 1.5 x 0.5 inch labels at 203 dpi. On other label sizes it will print small or clipped. - `--payload my.bin` serves your own ESPHome factory image instead of the portal one. Set the Wi-Fi password with the prompt or the `SWITCHBACK_WIFI_PASS` environment variable rather than `--wifi-pass`, so it stays out of your shell history. diff --git a/SECURITY.md b/SECURITY.md index 5c2e30a..971fd5a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -17,6 +17,8 @@ Switchback never changes your router, your DNS server, your computer's DNS setti **Downloads.** Switchback downloads `SHA256SUMS` and the firmware files from this repository's GitHub Releases, over HTTPS, and refuses any file whose SHA-256 does not match. Verified files are cached in your user cache folder. +**Files it writes.** Besides that cache, `convert` appends one line per converted plug (time, name, both MAC addresses) to `switchback-plugs.csv` in your home folder. Nothing in it leaves your computer. `--no-log` turns it off. + **What it does not do.** It does not contact SwitchBot, does not collect or send telemetry, does not install a service, and does not keep running after you stop it. ## Why this is safe to publish diff --git a/src/switchback/cli.py b/src/switchback/cli.py index 5c74c03..4b06bdc 100644 --- a/src/switchback/cli.py +++ b/src/switchback/cli.py @@ -19,6 +19,9 @@ from switchback import protocol as p from switchback.server import FirmwareServer, Payloads +# Every converted plug is recorded here unless --log or --no-log says otherwise. +DEFAULT_LOG = Path.home() / "switchback-plugs.csv" + EXPERIMENTAL_DIRECT = ( "Direct mode is experimental. Its Wi-Fi patch checks out, but it has not yet converted a real plug. " "If the plug cannot join, it opens its own hotspot instead, the same as portal mode." @@ -434,7 +437,7 @@ def cmd_convert(args: argparse.Namespace) -> int: stage1_timeout=args.stage1_timeout, timeout=args.timeout, domain=args.domain, - log_file=Path(args.log) if args.log else None, + log_file=None if args.no_log else Path(args.log) if args.log else DEFAULT_LOG, printer=args.printer, ) say("Keep each plug powered the whole time. Unplugging during the write can brick it.") @@ -570,7 +573,11 @@ def build_parser() -> argparse.ArgumentParser: cv.add_argument("--stage1-timeout", type=float, default=900.0) cv.add_argument("--timeout", type=float, default=600.0, help="seconds allowed after stage 1") cv.add_argument("--domain", help="DNS suffix such as .lan, to find converted plugs across VLANs") - cv.add_argument("--log", help="append each converted plug to this CSV file") + cv.add_argument( + "--log", + help=f"CSV file that records each converted plug (default: {DEFAULT_LOG.name} in your home folder)", + ) + cv.add_argument("--no-log", action="store_true", help="do not record converted plugs") cv.add_argument("--printer", help="ZPL label printer as host:port (off unless given)") cv.set_defaults(func=cmd_convert) diff --git a/src/switchback/convert.py b/src/switchback/convert.py index df2ef55..286af0c 100644 --- a/src/switchback/convert.py +++ b/src/switchback/convert.py @@ -220,8 +220,11 @@ async def convert(plug: Plug, feed: Feed, opts: Options) -> str: log("Leave it powered for at least another minute. A power cut right after an update can roll it back.") if opts.log_file: - write_log(opts.log_file, plug, address) - log(f"logged to {opts.log_file}") + try: + write_log(opts.log_file, plug, address) + log(f"recorded in {opts.log_file}") + except OSError as error: + log(f"could not record the plug in {opts.log_file}: {error}") if opts.printer: try: label.send(opts.printer, label.render(plug.ble_mac, plug.wifi_mac)) diff --git a/tests/test_wifiscan.py b/tests/test_wifiscan.py index 4103014..f5e8cc4 100644 --- a/tests/test_wifiscan.py +++ b/tests/test_wifiscan.py @@ -118,3 +118,12 @@ def test_convert_question(): def test_is_private(): assert is_private("192.168.20.84") and is_private("10.1.10.96") assert not is_private("3.171.153.12") and not is_private("127.0.0.1") and not is_private(None) + + +def test_log_is_on_by_default(): + from switchback import cli + + parser = cli.build_parser() + assert cli.DEFAULT_LOG.name == "switchback-plugs.csv" + assert parser.parse_args(["convert"]).no_log is False + assert parser.parse_args(["convert", "--no-log"]).no_log is True From a337e6b63756c2b8d04c0683306f8ec8dd1c6ea1 Mon Sep 17 00:00:00 2001 From: WiFiGUY512 <339406050+WiFiGUY512@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:25:26 -0600 Subject: [PATCH 2/3] Name a plug while converting it convert asks for a name such as "Garage Freezer" (or takes --name) and the plug boots as garage-freezer, with no second flash. - sbplug-name.yaml: the portal and direct payloads carry two fixed-size placeholder slots. A boot step before Wi-Fi reads them and, if they were filled in, uses them as the name and friendly name. - image.patch_name fills the slots and fixes the checksum and SHA-256, sharing the code path with the Wi-Fi patch. - sbplug-adopt.yaml: what Adopt imports, without the name slots. - Version 0.5.0, README, CHANGELOG, CI validates the adopt config. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 7 +++- README.md | 12 ++++--- firmware/esphome/addon-ble-proxy.yaml | 4 +-- firmware/esphome/plug-mini.yaml | 8 ++--- firmware/esphome/sbplug-adopt.yaml | 26 +++++++++++++++ firmware/esphome/sbplug-common.yaml | 4 +-- firmware/esphome/sbplug-direct.yaml | 1 + firmware/esphome/sbplug-name.yaml | 48 +++++++++++++++++++++++++++ firmware/esphome/sbplug-portal.yaml | 1 + pyproject.toml | 2 +- src/switchback/cli.py | 31 +++++++++++++++++ src/switchback/image.py | 38 ++++++++++++++++++--- src/switchback/server.py | 30 +++++++++++++---- tests/conftest.py | 6 +++- tests/test_image.py | 35 +++++++++++++++++++ tests/test_server.py | 19 +++++++++++ uv.lock | 2 +- 18 files changed, 248 insertions(+), 28 deletions(-) create mode 100644 firmware/esphome/sbplug-adopt.yaml create mode 100644 firmware/esphome/sbplug-name.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3dfa022..bf88e72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,7 +63,7 @@ jobs: echo "wifi_ssid: ci-only" echo "wifi_password: ci-only-pass" } > secrets.yaml - for config in sbplug-portal.yaml sbplug-direct.yaml sbplug-implant.yaml; do + for config in sbplug-portal.yaml sbplug-direct.yaml sbplug-implant.yaml sbplug-adopt.yaml; do esphome config "$config" > /dev/null echo "$config OK" done diff --git a/CHANGELOG.md b/CHANGELOG.md index e1e70d8..16829f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,12 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). -## Unreleased +## [0.5.0] - unreleased + +### Added + +- Name a plug while you convert it. `convert` asks for a name such as "Garage Freezer" (or takes `--name`), and the plug boots as `garage-freezer`, shown as "Garage Freezer". The published images carry two placeholder slots that Switchback fills in and re-checksums, the same way direct mode handles Wi-Fi. Enter keeps `sbplug-xxxxxx`. It needs firmware from this release or later, and does not work through `--server`. +- `firmware/esphome/sbplug-adopt.yaml`: what the Adopt button imports. It is the portal firmware without the name slots. ### Changed diff --git a/README.md b/README.md index ab28545..4cbd4da 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ uv tool update-shell The second line puts uv's tool folder on your PATH. Open a new terminal afterwards. With [pipx](https://pipx.pypa.io/) it is `pipx install git+https://github.com/WiFiGUY512/switchback`, then `pipx ensurepath`. -To pin a release, add `@v0.4.0` to the URL. There is no exe. The firmware files are not in the package: Switchback downloads them from this repository's [Releases](https://github.com/WiFiGUY512/switchback/releases) and checks each against the release's `SHA256SUMS` before it serves anything. +To pin a release, add `@v0.5.0` to the URL. There is no exe. The firmware files are not in the package: Switchback downloads them from this repository's [Releases](https://github.com/WiFiGUY512/switchback/releases) and checks each against the release's `SHA256SUMS` before it serves anything. ## Quick start @@ -74,7 +74,9 @@ To pin a release, add `@v0.4.0` to the URL. There is no exe. The firmware files - which Wi-Fi to use for the download. It lists the networks your computer can see, so you pick a number and type the password. 5 GHz-only networks are left out, because the plug cannot join them. - It then looks for the plug over Bluetooth and asks `Found 1 plug. It will become sbplug-xxxxxx. Convert it?` - After you answer `y` it gives the plug the Wi-Fi, triggers the update and follows it to the end. + - After you answer `y` it asks for a name, for example `Garage Freezer`. The plug then boots as `garage-freezer` and shows up in Home Assistant as "Garage Freezer". Press Enter to keep `sbplug-xxxxxx`. + + Then it gives the plug the Wi-Fi, triggers the update and follows it to the end. On Linux, ports 80 and 53 need root: `sudo "$(command -v switchback)" convert`. On Windows, allow the one-time firewall prompt. @@ -153,6 +155,8 @@ The image Switchback writes is the full hardware profile, so a plug is useful as - The white LED follows the relay. The blue LED blinks fast with no Wi-Fi, stays on with Wi-Fi but no Home Assistant, and glows slowly once Home Assistant is connected. - The ESPHome API **without encryption**, and OTA with the published password **`switchbota`**. +If you typed a name during `convert`, the plug uses it instead of `sbplug-xxxxxx`: as its hostname, its hotspot name and its name in Home Assistant. Switchback writes the name into the image just before the plug downloads it, so no second flash is needed. + There is no Bluetooth proxy in the image. It would not fit in the first write. Add it later over OTA if you want one (see below). The power readings use a calibration measured on one batch of plugs (October 2026) against a reference meter. Yours should be within a few percent. To use your own figures, set `voltage_cal`, `current_cal` and `power_cal` in your config. @@ -175,8 +179,8 @@ esphome: name: kitchen-kettle packages: - plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.4.0 - # ble: github://WiFiGUY512/switchback/firmware/esphome/addon-ble-proxy.yaml@v0.4.0 + plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.5.0 + # ble: github://WiFiGUY512/switchback/firmware/esphome/addon-ble-proxy.yaml@v0.5.0 api: encryption: diff --git a/firmware/esphome/addon-ble-proxy.yaml b/firmware/esphome/addon-ble-proxy.yaml index bf8a783..05313f5 100644 --- a/firmware/esphome/addon-ble-proxy.yaml +++ b/firmware/esphome/addon-ble-proxy.yaml @@ -6,8 +6,8 @@ # plug runs ESPHome: # # packages: -# plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.4.0 -# ble: github://WiFiGUY512/switchback/firmware/esphome/addon-ble-proxy.yaml@v0.4.0 +# plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.5.0 +# ble: github://WiFiGUY512/switchback/firmware/esphome/addon-ble-proxy.yaml@v0.5.0 # # Wi-Fi and Bluetooth share the ESP32-C3's one radio. Scanning is passive, # and interval and window are left to ESPHome, which keeps the window at or diff --git a/firmware/esphome/plug-mini.yaml b/firmware/esphome/plug-mini.yaml index e2df6f0..be6e830 100644 --- a/firmware/esphome/plug-mini.yaml +++ b/firmware/esphome/plug-mini.yaml @@ -6,7 +6,7 @@ # and add your own wifi, api and ota: # # packages: -# plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.4.0 +# plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.5.0 # # Pin a release tag, not main. # @@ -110,9 +110,9 @@ esp32: esphome: on_boot: - priority: -100 - then: - - script.execute: update_status_led + - priority: -100 + then: + - script.execute: update_status_led on_shutdown: then: - lambda: |- diff --git a/firmware/esphome/sbplug-adopt.yaml b/firmware/esphome/sbplug-adopt.yaml new file mode 100644 index 0000000..2d884a9 --- /dev/null +++ b/firmware/esphome/sbplug-adopt.yaml @@ -0,0 +1,26 @@ +#============================================================================== +# What "Adopt" in Device Builder or Home Assistant imports +#============================================================================== +# The same firmware as the portal payload, without the convert-time name +# slots (sbplug-name.yaml). Adopting gives the plug its name the normal way, +# and adds your Wi-Fi and a fresh API encryption key. Change the OTA password +# at the same time: +# +# substitutions: +# ota_password: !secret ota_password +#============================================================================== + +substitutions: + ota_password: switchbota + +packages: + common: !include sbplug-common.yaml + +api: + +ota: + platform: esphome + password: ${ota_password} + +wifi: + ap: diff --git a/firmware/esphome/sbplug-common.yaml b/firmware/esphome/sbplug-common.yaml index 679222e..93639c1 100644 --- a/firmware/esphome/sbplug-common.yaml +++ b/firmware/esphome/sbplug-common.yaml @@ -28,7 +28,7 @@ substitutions: name: sbplug friendly_name: "SwitchBot Plug Mini" - switchback_version: "0.4.0" + switchback_version: "0.5.0" relay_restore_mode: RESTORE_DEFAULT_OFF packages: @@ -45,7 +45,7 @@ esphome: board_build.flash_mode: dio dashboard_import: - package_import_url: github://WiFiGUY512/switchback/firmware/esphome/sbplug-portal.yaml@v${switchback_version} + package_import_url: github://WiFiGUY512/switchback/firmware/esphome/sbplug-adopt.yaml@v${switchback_version} import_full_config: false # UART0 is what the serial pads expose, so boot logs show up on the recovery path. diff --git a/firmware/esphome/sbplug-direct.yaml b/firmware/esphome/sbplug-direct.yaml index 7cd2b96..617de6c 100644 --- a/firmware/esphome/sbplug-direct.yaml +++ b/firmware/esphome/sbplug-direct.yaml @@ -24,6 +24,7 @@ substitutions: packages: common: !include sbplug-common.yaml + name: !include sbplug-name.yaml api: diff --git a/firmware/esphome/sbplug-name.yaml b/firmware/esphome/sbplug-name.yaml new file mode 100644 index 0000000..a287018 --- /dev/null +++ b/firmware/esphome/sbplug-name.yaml @@ -0,0 +1,48 @@ +#============================================================================== +# Switchback payloads only: a name you choose at conversion time +#============================================================================== +# The published images are built once for everyone, so the name cannot be +# compiled in. Instead the image carries two fixed-size placeholder slots. +# `switchback convert` overwrites them with the name you type, then fixes the +# image checksum and SHA-256, the same way direct mode handles Wi-Fi. +# +# name slot: SB_NAME_ + 23 'C' (31 bytes, the hostname) +# friendly name slot: SB_FRND_ + 55 'D' (63 bytes, shown in Home Assistant) +# +# At boot, before Wi-Fi starts, the plug looks at the slots. Still +# placeholders: nothing happens and the plug is sbplug-xxxxxx. Patched: the +# plug uses that name for its hostname, hotspot and Home Assistant. +# +# This reaches into ESPHome's Application object, so it is tied to the ESPHome +# version the release is built with. It is not part of sbplug-common.yaml, and +# a config you write or adopt does not need it: there you set the name the +# normal way. +#============================================================================== + +esphome: + on_boot: + - priority: 1000 + then: + - lambda: |- + static volatile char name_slot[] = "SB_NAME_CCCCCCCCCCCCCCCCCCCCCCC"; + static volatile char friendly_slot[] = "SB_FRND_DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"; + static char name[sizeof(name_slot)]; + static char friendly[sizeof(friendly_slot)]; + auto copy = [](volatile char *slot, char *out, size_t size) -> size_t { + size_t n = 0; + while (n + 1 < size && slot[n] != 0) { + out[n] = slot[n]; + n++; + } + out[n] = 0; + return n; + }; + size_t name_len = copy(name_slot, name, sizeof(name)); + size_t friendly_len = copy(friendly_slot, friendly, sizeof(friendly)); + // Still the placeholder? A real hostname is lower case, so it never starts with "SB_". + // Compared one character at a time so the marker text exists only inside the slots. + if (name_len == 0 || (name[0] == 'S' && name[1] == 'B' && name[2] == '_')) return; + const_cast(App.get_name()) = StringRef(name, name_len); + if (friendly_len > 0) { + const_cast(App.get_friendly_name()) = StringRef(friendly, friendly_len); + } diff --git a/firmware/esphome/sbplug-portal.yaml b/firmware/esphome/sbplug-portal.yaml index 7004d5a..4183166 100644 --- a/firmware/esphome/sbplug-portal.yaml +++ b/firmware/esphome/sbplug-portal.yaml @@ -19,6 +19,7 @@ substitutions: packages: common: !include sbplug-common.yaml + name: !include sbplug-name.yaml api: diff --git a/pyproject.toml b/pyproject.toml index 2ba508f..3062050 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "switchback" -version = "0.4.0" +version = "0.5.0" description = "Convert a SwitchBot Plug Mini to ESPHome over Wi-Fi and Bluetooth. No app, no cloud." readme = "README.md" requires-python = ">=3.10" diff --git a/src/switchback/cli.py b/src/switchback/cli.py index 4b06bdc..f9f13c6 100644 --- a/src/switchback/cli.py +++ b/src/switchback/cli.py @@ -344,6 +344,20 @@ async def _find_plugs(args: argparse.Namespace, handled: set[str]) -> tuple[Any, return (plugs[0] if plugs else None), len(plugs) +def name_plug(plug: Any, payloads: Payloads, mode: str, ssid: str, password: str, typed: str) -> None: + """Patch the name the user typed into the payload, or reset the payload to the unnamed one.""" + hostname = image.hostname_from(typed) + if not hostname: + payloads.select(mode, ssid, password) + return + friendly = typed.strip() + while len(friendly.encode("utf-8")) > 63: + friendly = friendly[:-1] + payloads.select(mode, ssid, password, name=hostname, friendly_name=friendly) + plug.name = hostname + say(f"It will be {hostname!r}, shown as {friendly!r}.") + + def convert_question(plug: Any, count: int) -> str: if count == 1: return f"Found 1 plug. It will become {plug.name}. Convert it? [y/N] " @@ -377,6 +391,9 @@ async def run() -> int: def cmd_convert(args: argparse.Namespace) -> int: from switchback import ble, convert + if args.name and args.count > 1: + say("--name names one plug. Leave it out with --count and you are asked for each plug.") + return 1 mode = choose_mode(args) if mode == "direct": say(EXPERIMENTAL_DIRECT) @@ -386,6 +403,7 @@ def cmd_convert(args: argparse.Namespace) -> int: return 1 feed: convert.Feed + payloads: Payloads | None = None if args.server: feed = convert.HttpFeed(args.server) try: @@ -417,6 +435,7 @@ def cmd_convert(args: argparse.Namespace) -> int: say("in that server's mode, whatever was chosen here.") if args.yes or ask(f"Follow the server at {seen} instead of this computer? [Y/n] ").lower() != "n": server.close() + payloads = None # that server decides the payload, so no name can be patched in here feed = convert.HttpFeed(f"http://{seen}") say(feed.describe()) if mode == "direct": @@ -454,6 +473,17 @@ async def run() -> int: handled.add(plug.ble_mac) if not args.yes and (await asyncio.to_thread(ask, convert_question(plug, count))).lower() != "y": continue + if payloads is not None and payloads.can_name(mode): + typed = args.name or "" + if not typed and not args.yes: + typed = await asyncio.to_thread(ask, f"Name for this plug (Enter keeps {plug.name}): ") + try: + name_plug(plug, payloads, mode, ssid, password, typed) + except (ValueError, image.ImageError) as error: + say(f"Could not use that name ({error}). It stays {plug.name}.") + payloads.select(mode, ssid, password) + elif args.name: + say(f"This firmware or server cannot take a name. It stays {plug.name}.") try: await convert.convert(plug, feed, opts) done += 1 @@ -563,6 +593,7 @@ def build_parser() -> argparse.ArgumentParser: cv.add_argument("--mode", choices=["portal", "direct"], help="portal (proven) or direct (experimental)") cv.add_argument("--server", help="use a 'switchback serve' on another box, e.g. http://192.0.2.10") cv.add_argument("--count", type=int, default=1, help="how many plugs to convert this run") + cv.add_argument("--name", help="name for the plug, e.g. 'Garage Freezer' (asked for if omitted; one plug only)") cv.add_argument("--yes", action="store_true", help="do not ask before each plug") cv.add_argument( "--fw-byte", diff --git a/src/switchback/image.py b/src/switchback/image.py index c14965d..e39cc09 100644 --- a/src/switchback/image.py +++ b/src/switchback/image.py @@ -16,6 +16,9 @@ SSID_PREFIX = b"SB_SSID_" PASS_PREFIX = b"SB_PASS_" +# Prefix plus the first fill characters, so only the real slot matches. +NAME_PREFIX = b"SB_NAME_CCCC" +FRIENDLY_PREFIX = b"SB_FRND_DDDD" ESP_IMAGE_MAGIC = 0xE9 ESP_CHECKSUM_MAGIC = 0xEF ESP32C3_CHIP_ID = 0x0005 @@ -87,13 +90,17 @@ def has_placeholders(image: bytes) -> bool: return SSID_PREFIX in image and PASS_PREFIX in image -def patch_wifi(image: bytes, ssid: str, password: str, app_offset: int = APP_OFFSET) -> bytes: - """Return a copy of image with the placeholder Wi-Fi replaced and the checksum and hash fixed.""" +def has_name_slots(image: bytes) -> bool: + return NAME_PREFIX in image and FRIENDLY_PREFIX in image + + +def _fill_slots(image: bytes, slots: tuple[tuple[bytes, str, str], ...], app_offset: int, hint: str) -> bytes: + """Overwrite each placeholder slot with its value, then fix the checksum and hash.""" img = bytearray(image) - for prefix, label, value in ((SSID_PREFIX, "Wi-Fi name", ssid), (PASS_PREFIX, "Wi-Fi password", password)): + for prefix, label, value in slots: i = img.find(prefix) if i < 0: - raise ImageError(f"{label} placeholder not found. Is this the direct build?") + raise ImageError(f"{label} placeholder not found. {hint}") end = img.find(b"\x00", i) # the slot runs to the string's null terminator if end < 0 or not (len(prefix) <= end - i <= 64): raise ImageError(f"{label} placeholder slot looks wrong") @@ -110,6 +117,29 @@ def patch_wifi(image: bytes, ssid: str, password: str, app_offset: int = APP_OFF return bytes(img) +def patch_wifi(image: bytes, ssid: str, password: str, app_offset: int = APP_OFFSET) -> bytes: + """Return a copy of image with the placeholder Wi-Fi replaced and the checksum and hash fixed.""" + slots = ((SSID_PREFIX, "Wi-Fi name", ssid), (PASS_PREFIX, "Wi-Fi password", password)) + return _fill_slots(image, slots, app_offset, "Is this the direct build?") + + +def patch_name(image: bytes, name: str, friendly_name: str, app_offset: int = APP_OFFSET) -> bytes: + """Return a copy of image that boots with this hostname and friendly name.""" + slots = ((NAME_PREFIX, "name", name), (FRIENDLY_PREFIX, "friendly name", friendly_name)) + return _fill_slots(image, slots, app_offset, "This firmware is too old to take a name.") + + +def hostname_from(text: str) -> str: + """A valid ESPHome name from what the user typed: 'Garage Freezer' -> 'garage-freezer'.""" + out = [] + for ch in text.strip().lower(): + if ch.isascii() and ch.isalnum(): + out.append(ch) + elif out and out[-1] != "-": + out.append("-") + return "".join(out).strip("-")[:31].strip("-") + + def check_esp32c3(image: bytes, name: str) -> None: # ESP image header: magic at byte 0, chip id at bytes 12 and 13 (5 is the ESP32-C3) if len(image) < 24 or image[0] != ESP_IMAGE_MAGIC or struct.unpack_from(" Payloads: return cls(app.read_bytes(), portal.read_bytes(), direct.read_bytes() if direct else None) - def select(self, mode: str, ssid: str | None = None, password: str | None = None) -> None: - """Serve the portal build, or the direct build with this Wi-Fi patched in.""" + def select( + self, + mode: str, + ssid: str | None = None, + password: str | None = None, + name: str | None = None, + friendly_name: str | None = None, + ) -> None: + """Serve the portal build, or the direct build with this Wi-Fi patched in. + + With a name, that name is patched in too, so the plug boots with it. + """ if mode == "direct": if self.direct is None: raise image.ImageError("direct mode needs the direct payload") if not ssid: raise ValueError("direct mode needs a Wi-Fi name") - patched = image.patch_wifi(self.direct, ssid, password or "") - if not image.verify_image(patched): - raise image.ImageError("the patched image failed its own checksum") - self.payload = patched + payload = image.patch_wifi(self.direct, ssid, password or "") elif mode == "portal": - self.payload = self.portal + payload = self.portal else: raise ValueError(f"unknown mode {mode!r}") + if name: + payload = image.patch_name(payload, name, friendly_name or name) + if payload is not self.portal and not image.verify_image(payload): + raise image.ImageError("the patched image failed its own checksum") + self.payload = payload self.mode = mode self.md5 = hashlib.md5(self.payload).hexdigest() + def can_name(self, mode: str) -> bool: + base = self.direct if mode == "direct" else self.portal + return base is not None and image.has_name_slots(base) + def _make_handler(payloads: Payloads, events: EventLog, arp: Callable[[str], str | None]) -> type: class Handler(BaseHTTPRequestHandler): diff --git a/tests/conftest.py b/tests/conftest.py index 7140c67..2d6320a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,6 +9,8 @@ SSID_SLOT = b"SB_SSID_" + b"A" * 24 PASS_SLOT = b"SB_PASS_" + b"B" * 55 +NAME_SLOT = b"SB_NAME_" + b"C" * 23 +FRIENDLY_SLOT = b"SB_FRND_" + b"D" * 55 def _header(segments: int, hash_appended: int) -> bytearray: @@ -39,7 +41,7 @@ def make_app(segments: list[bytes], hash_appended: bool = True) -> bytes: return bytes(body) -def make_factory(placeholders: bool = True, hash_appended: bool = True) -> bytes: +def make_factory(placeholders: bool = True, hash_appended: bool = True, name_slots: bool = True) -> bytes: img = bytearray(b"\xff" * 0x10000) boot = _header(0, 0) img[: len(boot)] = boot @@ -50,6 +52,8 @@ def make_factory(placeholders: bool = True, hash_appended: bool = True) -> bytes else: data2 = b"no wifi here\x00" data3 = bytes(range(256)) * 3 + if name_slots: + data3 += NAME_SLOT + b"\x00" + FRIENDLY_SLOT + b"\x00" + b"\x00" * 3 img += make_app([data1, data2 + b"\x00" * 3, data3], hash_appended) return bytes(img) diff --git a/tests/test_image.py b/tests/test_image.py index ca3acd2..19b59b1 100644 --- a/tests/test_image.py +++ b/tests/test_image.py @@ -75,3 +75,38 @@ def test_payload_checks(factory, flasher): image.check_payload(bytes(qio)) with pytest.raises(image.ImageError): image.check_esp32c3(b"\xe9" + b"\x00" * 30, "x") + + +def test_name_patch_verifies_and_keeps_size(factory): + patched = image.patch_name(factory, "garage-freezer", "Garage Freezer") + assert len(patched) == len(factory) + assert image.verify_image(patched) + assert b"garage-freezer\x00" in patched and b"Garage Freezer\x00" in patched + assert not image.has_name_slots(patched) + + +def test_name_and_wifi_patches_combine(factory): + patched = image.patch_name(image.patch_wifi(factory, "Home Net", "secret pass"), "kettle", "Kettle") + assert image.verify_image(patched) + assert b"Home Net\x00" in patched and b"kettle\x00" in patched + + +def test_name_too_long_is_refused(factory): + with pytest.raises(image.ImageError): + image.patch_name(factory, "x" * 32, "ok") + with pytest.raises(image.ImageError): + image.patch_name(factory, "ok", "y" * 64) + + +def test_name_needs_slots(): + with pytest.raises(image.ImageError): + image.patch_name(make_factory(name_slots=False), "a", "b") + + +def test_hostname_from(): + assert image.hostname_from("Garage Freezer") == "garage-freezer" + assert image.hostname_from(" Kid's Lamp #2 ") == "kid-s-lamp-2" + assert image.hostname_from("---") == "" + assert image.hostname_from("") == "" + assert len(image.hostname_from("a" * 50)) == 31 + assert not image.hostname_from("a" * 30 + " b").endswith("-") diff --git a/tests/test_server.py b/tests/test_server.py index a64e25a..7150fec 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -69,3 +69,22 @@ def test_bad_files_are_refused(flasher, factory): def test_unknown_mode(server): with pytest.raises(ValueError): server.payloads.select("other") + + +def test_a_name_is_patched_into_either_payload(server): + payloads = server.payloads + assert payloads.can_name("portal") and payloads.can_name("direct") + payloads.select("portal", name="garage-freezer", friendly_name="Garage Freezer") + body = get(server, "/payload.bin") + assert b"garage-freezer\x00" in body and image.verify_image(body) + assert get(server, "/payload.md5").split()[0].decode() == hashlib.md5(body).hexdigest() + payloads.select("direct", "Home Net", "secret pass", name="kettle") + body = get(server, "/payload.bin") + assert b"kettle\x00" in body and b"Home Net\x00" in body and image.verify_image(body) + payloads.select("portal") + assert get(server, "/payload.bin") == payloads.portal + + +def test_old_firmware_cannot_be_named(flasher): + payloads = Payloads(flasher, make_factory(placeholders=False, name_slots=False), None) + assert not payloads.can_name("portal") diff --git a/uv.lock b/uv.lock index af88c9d..0452279 100644 --- a/uv.lock +++ b/uv.lock @@ -736,7 +736,7 @@ wheels = [ [[package]] name = "switchback" -version = "0.4.0" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "bleak" }, From 6fc78de2a493f75d8e0ae4d3c55aff076e586a6a Mon Sep 17 00:00:00 2001 From: WiFiGUY512 <339406050+WiFiGUY512@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:16:57 -0600 Subject: [PATCH 3/3] Date the 0.5.0 release Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16829f9..4e45c69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). -## [0.5.0] - unreleased +## [0.5.0] - 2026-11-22 ### Added