Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).

## [0.5.0] - 2026-11-22

### 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

- `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.
Expand Down
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -230,7 +234,8 @@ Useful options for `convert`:
- `--server http://<box>` 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.
Expand Down
2 changes: 2 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions firmware/esphome/addon-ble-proxy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions firmware/esphome/plug-mini.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down Expand Up @@ -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: |-
Expand Down
26 changes: 26 additions & 0 deletions firmware/esphome/sbplug-adopt.yaml
Original file line number Diff line number Diff line change
@@ -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:
4 changes: 2 additions & 2 deletions firmware/esphome/sbplug-common.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.
Expand Down
1 change: 1 addition & 0 deletions firmware/esphome/sbplug-direct.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ substitutions:

packages:
common: !include sbplug-common.yaml
name: !include sbplug-name.yaml

api:

Expand Down
48 changes: 48 additions & 0 deletions firmware/esphome/sbplug-name.yaml
Original file line number Diff line number Diff line change
@@ -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<StringRef &>(App.get_name()) = StringRef(name, name_len);
if (friendly_len > 0) {
const_cast<StringRef &>(App.get_friendly_name()) = StringRef(friendly, friendly_len);
}
1 change: 1 addition & 0 deletions firmware/esphome/sbplug-portal.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ substitutions:

packages:
common: !include sbplug-common.yaml
name: !include sbplug-name.yaml

api:

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
42 changes: 40 additions & 2 deletions src/switchback/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -341,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] "
Expand Down Expand Up @@ -374,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)
Expand All @@ -383,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:
Expand Down Expand Up @@ -414,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":
Expand All @@ -434,7 +456,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.")
Expand All @@ -451,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
Expand Down Expand Up @@ -560,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",
Expand All @@ -570,7 +604,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)

Expand Down
7 changes: 5 additions & 2 deletions src/switchback/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading