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
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

## [0.4.0] - unreleased
## [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 All @@ -13,9 +13,14 @@ A converted plug now boots the full hardware profile, so it reports power and en
- Device Builder and Home Assistant offer **Adopt** for a converted plug (ESPHome project `wifiguy512.switchback-plug-mini`).
- `firmware/esphome/addon-ble-proxy.yaml`: an optional Bluetooth proxy with passive scanning, to add over OTA. It is not in any payload.
- The relay is latched through clean restarts, so an OTA update does not blip the load.
- `switchback convert` lists the Wi-Fi networks the computer can see, so you pick a number instead of typing the name. Networks that are 5 GHz only are left out. Typing a name still works. On macOS only the current network is offered.
- `convert` notices when `wohand.com` already points at another machine on your network. If a Switchback server answers there, it offers to follow that server. If not, it says so before touching the plug.

### Changed

- The README leads with the no-install way to run it (`uvx --from ... switchback convert`). The install steps now include the PATH step.
- The convert question reads "Found 1 plug. It will become sbplug-xxxxxx. Convert it?" instead of leading with MAC addresses.
- The "never fetched anything" failure now says the plug may be converting from another server and to leave it powered.
- `sbplug-common.yaml` now includes `plug-mini.yaml` and adds the bootstrap defaults: the "Relay" switch, the button scripts (short press toggles, hold 10 seconds to factory reset), an sntp time source and the captive portal. The relay switch keeps its name and id. The blue LED shows Wi-Fi and Home Assistant state instead of ESPHome's status pattern.
- The button's short press now accepts presses up to 2.9 seconds (was 1 second).

Expand Down
33 changes: 25 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,32 @@ It does not touch any other device, does not intercept any other name, and does
> [!WARNING]
> This rewrites the plug's bootloader over Wi-Fi. If the plug loses power at the wrong moment, it is bricked. The case is welded shut, so recovery means cutting it open and flashing over the serial pads. **Do not unplug a plug while it converts, and leave it powered for at least a minute after it finishes.** Try one plug before you do a box of them. There is no warranty.

## Install
## Run it

You need Python 3.10 or newer and a computer with Bluetooth that [bleak](https://github.com/hbldh/bleak) supports: Windows 10 or 11, macOS, or Linux with BlueZ.
You need a computer with Bluetooth that [bleak](https://github.com/hbldh/bleak) supports: Windows 10 or 11, macOS, or Linux with BlueZ.

With [uv](https://docs.astral.sh/uv/):
The simplest way needs no install. Get [uv](https://docs.astral.sh/uv/getting-started/installation/), then run Switchback straight from this repository:

```bash
uv tool install git+https://github.com/WiFiGUY512/switchback
uvx --from git+https://github.com/WiFiGUY512/switchback switchback convert
```

Or with [pipx](https://pipx.pypa.io/):
`uvx` fetches Switchback (and Python, if you have none) into a cache and runs it. Nothing is added to your PATH. Run the same line again for the next plug.

The rest of this page writes commands as `switchback ...`. If you did not install it, put `uvx --from git+https://github.com/WiFiGUY512/switchback` in front.

### Or install it

If you will use it often, install it once (Python 3.10 or newer):

```bash
pipx install git+https://github.com/WiFiGUY512/switchback
uv tool install git+https://github.com/WiFiGUY512/switchback
uv tool update-shell
```

To pin a release, add `@v0.3.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.
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.

## Quick start

Expand All @@ -59,7 +68,13 @@ To pin a release, add `@v0.3.0` to the URL. There is no exe. The firmware files
switchback convert
```

It asks how the plug should get on Wi-Fi afterwards, and which Wi-Fi to use for the download. Then it finds the plug over Bluetooth, gives it the Wi-Fi, triggers the update and follows it to the end.
It asks a few questions and does the rest:

- how the plug should get on Wi-Fi afterwards,
- 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.

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 @@ -260,6 +275,8 @@ To build your own payload, see [CONTRIBUTING.md](CONTRIBUTING.md). The `sbplug-i
- **Status 30 or 40 that loops.** The plug cannot find the network. It sees 2.4 GHz only, and the name is case sensitive. Switchback stops after about 45 seconds of this.
- **Status 50 that never turns into "connected".** The plug joined but got no IP address. Use a flat network without VLAN tagging for the download.
- **"refused the Bluetooth update trigger".** Newer stock firmware. Use Path B.
- **"switchback is not recognized" (or "command not found") after installing.** The tool folder is not on your PATH. Run `uv tool update-shell` (or `pipx ensurepath`) and open a new terminal, or use the `uvx` line from [Run it](#run-it), which needs no PATH.
- **"wohand.com resolves to another machine on your network".** A redirect is already in place and points at a different computer. If a Switchback server runs there, `convert` offers to follow it. Otherwise fix the redirect so it points at the computer you are running on.
- **The plug never fetches anything.** Its DNS is not reaching your redirect, or something blocks port 80 to your computer. Run `nslookup www.wohand.com` from a device on the plug's network.
- **A port is busy.** Something else uses port 80 or 53. Stop it, or use `--no-dns` with your own DNS records, or run the server on another box.
- **Bluetooth drops on Windows.** Switchback retries the Wi-Fi step three times. Nothing has been sent to the plug when a connection fails.
Expand Down
5 changes: 3 additions & 2 deletions src/switchback/ble.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,9 @@ def over() -> bool:
return True
if triggered and not saw("stage1") and time.monotonic() - started > 75:
raise Failed(
"the plug never fetched anything from the server. Check that it is on Wi-Fi, that its DNS "
"sends wohand.com to the server, and that nothing blocks port 80 to the server."
"this server saw no download from the plug. Either the plug's DNS does not send wohand.com "
"to this server, or port 80 to it is blocked. If wohand.com points at a different machine, the "
"plug may be converting from there: leave it powered and look for an sbplug-xxxxxx hotspot."
)
return False

Expand Down
105 changes: 93 additions & 12 deletions src/switchback/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@
import argparse
import asyncio
import getpass
import ipaddress
import os
import platform
import socket
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any

from switchback import __version__, dns, firmware, image, label
from switchback import __version__, dns, firmware, image, label, wifiscan
from switchback import protocol as p
from switchback.server import FirmwareServer, Payloads

Expand Down Expand Up @@ -112,6 +114,28 @@ def choose_mode(args: argparse.Namespace) -> str:
return "direct" if ask("Choose 1 or 2 [1]: ").startswith("2") else "portal"


def pick_wifi() -> str:
"""Offer the Wi-Fi networks in range. Returns "" when the user should type a name instead."""
networks, hidden = wifiscan.usable(wifiscan.scan())
if not networks:
return ""
networks = networks[:15]
say("Wi-Fi networks this computer can see:")
for number, net in enumerate(networks, 1):
note = " (this computer is on it)" if net.current else ""
say(f" [{number}] {net.ssid}{note}")
say(" [0] another one (type its name)")
if hidden:
say(f" Left out: {hidden} network(s) that are 5 GHz only. The plug cannot join those.")
while True:
answer = ask("Choose a number [1]: ") or "1"
if answer == "0":
return ""
if answer.isdigit() and 1 <= int(answer) <= len(networks):
return networks[int(answer) - 1].ssid
say(f"Type a number from 0 to {len(networks)}.")


def wifi_details(args: argparse.Namespace, mode: str) -> tuple[str, str]:
ssid = args.wifi_ssid
if not ssid:
Expand All @@ -120,8 +144,10 @@ def wifi_details(args: argparse.Namespace, mode: str) -> tuple[str, str]:
else:
say("The plug needs a Wi-Fi just to download the firmware. It does not keep it.")
say("Use a plain 2.4 GHz network whose DNS sends wohand.com to the server.")
ssid = ask("Wi-Fi name (SSID): ")
password = args.wifi_pass if args.wifi_pass is not None else ask_password()
ssid = pick_wifi() or ask("Wi-Fi name (SSID): ")
if not ssid:
return "", ""
password = args.wifi_pass if args.wifi_pass is not None else ask_password(f"Password for {ssid}: ")
return ssid, password


Expand All @@ -147,20 +173,44 @@ def start_servers(args: argparse.Namespace, payloads: Payloads, ip: str, on_even
return server


def report_dns(ip: str, args: argparse.Namespace) -> bool:
"""Say whether wohand.com points here, and how to fix it if not."""
def report_dns(ip: str, args: argparse.Namespace) -> str | None:
"""Say whether wohand.com points here, and how to fix it if not. Returns what it resolves to."""
dns.flush_cache()
seen = dns.system_lookup("www.wohand.com")
if seen == ip:
say(f"DNS: www.wohand.com resolves to this computer ({ip}). Good.")
return True
return seen
say(f"DNS: on this computer, www.wohand.com resolves to {seen or 'nothing'}, not {ip}.")
if is_private(seen):
say(f" {seen} is another machine on your network, so a redirect is already in place and points THERE.")
say(" A plug on a network with that redirect downloads from that machine, not from this computer.")
return seen
say(" That is fine if only the plugs' network uses the redirect. The plug must get this answer:")
say(f" wohand.com and www.wohand.com -> {ip}")
say(" Ways to do it (the README has steps for common routers and DNS servers):")
say(f" 1. Point the DHCP DNS server of the plugs' network at {ip} (the built-in DNS answers).")
say(f" 2. Or add those two names as local records to {ip} in your own DNS server.")
return False
return seen


def is_private(address: str | None) -> bool:
try:
if address is None:
return False
parsed = ipaddress.ip_address(address)
return parsed.is_private and not parsed.is_loopback
except ValueError:
return False


def switchback_server_at(address: str) -> bool:
"""True if a Switchback firmware server answers at this address ("<md5> <size>" on /payload.md5)."""
try:
with urllib.request.urlopen(f"http://{address}/payload.md5", timeout=3) as response:
fields = response.read(100).decode("ascii", errors="replace").split()
except (OSError, ValueError):
return False
return len(fields) == 2 and len(fields[0]) == 32 and fields[1].isdigit()


# ---------------------------------------------------------------- commands
Expand Down Expand Up @@ -279,10 +329,22 @@ def cmd_scan(args: argparse.Namespace) -> int:


async def _pick_plug(args: argparse.Namespace, handled: set[str]) -> Any:
plug, _ = await _find_plugs(args, handled)
return plug


async def _find_plugs(args: argparse.Namespace, handled: set[str]) -> tuple[Any, int]:
"""The nearest stock plug not handled yet, and how many are in range."""
from switchback import ble

plugs = [plug for plug in await ble.scan(args.scan_time, args.only) if plug.ble_mac not in handled]
return plugs[0] if plugs else None
return (plugs[0] if plugs else None), len(plugs)


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] "
return f"Found {count} plugs. The nearest will become {plug.name}. Convert it? [y/N] "


def cmd_provision(args: argparse.Namespace) -> int:
Expand Down Expand Up @@ -342,9 +404,27 @@ def cmd_convert(args: argparse.Namespace) -> int:
server = start_servers(args, payloads, ip, None)
if not server:
return 1
report_dns(ip, args)
seen = report_dns(ip, args)
feed = convert.LocalFeed(server)
say(f"Serving the {feed.describe()}")
if seen != ip and is_private(seen):
assert seen is not None
if switchback_server_at(seen):
say(f"A Switchback server is answering at {seen}. The plug will take its firmware from there,")
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()
feed = convert.HttpFeed(f"http://{seen}")
say(feed.describe())
if mode == "direct":
say("Treating this run as portal mode: the plug will open its hotspot unless that")
say("server was started with 'switchback serve --mode direct'.")
mode = "portal"
else:
say(f"Nothing at {seen} looks like a Switchback server, so the plug would download nothing.")
say(f"Fix the redirect so wohand.com and www.wohand.com point to {ip}, then run this again.")
if args.yes or ask("Carry on anyway? [y/N] ").lower() != "y":
return 1

opts = convert.Options(
mode=mode,
Expand All @@ -363,12 +443,13 @@ async def run() -> int:
handled: set[str] = set()
done = 0
while done < args.count:
plug = await _pick_plug(args, handled)
say("Looking for stock Plug Minis over Bluetooth ...")
plug, count = await _find_plugs(args, handled)
if plug is None:
say("No more stock Plug Minis in range.")
say("No stock Plug Minis in range." if not handled else "No more stock Plug Minis in range.")
break
handled.add(plug.ble_mac)
if not args.yes and (await asyncio.to_thread(ask, f"Convert {plug}? [y/N] ")).lower() != "y":
if not args.yes and (await asyncio.to_thread(ask, convert_question(plug, count))).lower() != "y":
continue
try:
await convert.convert(plug, feed, opts)
Expand Down
Loading
Loading