From 809e8adf9ba4449005dbecc0e4ec773aad6db4e4 Mon Sep 17 00:00:00 2001 From: WiFiGUY512 <339406050+WiFiGUY512@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:58:38 -0600 Subject: [PATCH] Make convert friendlier: Wi-Fi picker, clearer prompts, redirect check Found while converting the first real plug with this package. - convert lists the Wi-Fi networks the computer can see (netsh on Windows, nmcli on Linux, the current network on macOS) and leaves out 5 GHz-only ones. Typing a name still works. - The convert question says "Found 1 plug. It will become sbplug-xxxxxx. Convert it?" instead of leading with MAC addresses. - When wohand.com already points at another machine on the network, convert says so. If a Switchback server answers there it offers to follow it; otherwise it asks before touching the plug. Before, the plug converted from the other server while convert reported FAILED. - README: the no-install uvx command comes first, the install steps include the PATH step, and troubleshooting covers both problems. - CHANGELOG: 0.4.0 dated. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 7 +- README.md | 33 ++++++--- src/switchback/ble.py | 5 +- src/switchback/cli.py | 105 ++++++++++++++++++++++++---- src/switchback/wifiscan.py | 140 +++++++++++++++++++++++++++++++++++++ tests/test_wifiscan.py | 120 +++++++++++++++++++++++++++++++ 6 files changed, 387 insertions(+), 23 deletions(-) create mode 100644 src/switchback/wifiscan.py create mode 100644 tests/test_wifiscan.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fbdf115..727c777 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.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. @@ -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). diff --git a/README.md b/README.md index 15bf2ca..a1f0cad 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. @@ -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. diff --git a/src/switchback/ble.py b/src/switchback/ble.py index 3c8210c..734f43a 100644 --- a/src/switchback/ble.py +++ b/src/switchback/ble.py @@ -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 diff --git a/src/switchback/cli.py b/src/switchback/cli.py index c0a10b8..5c74c03 100644 --- a/src/switchback/cli.py +++ b/src/switchback/cli.py @@ -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 @@ -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: @@ -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 @@ -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 (" " 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 @@ -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: @@ -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, @@ -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) diff --git a/src/switchback/wifiscan.py b/src/switchback/wifiscan.py new file mode 100644 index 0000000..0fdae96 --- /dev/null +++ b/src/switchback/wifiscan.py @@ -0,0 +1,140 @@ +"""Wi-Fi networks this computer can see, so the user can pick one instead of typing a name. + +It asks the operating system and sends nothing itself. Every failure ends in an empty +list, and the caller falls back to asking for the name. + + Windows netsh wlan show networks mode=bssid + Linux nmcli device wifi list + macOS only the network the computer is on (macOS hides the rest from programs + without location permission) +""" + +from __future__ import annotations + +import re +import subprocess +import sys +from dataclasses import dataclass + +# The word for "Channel" in the netsh output of common Windows languages. +_CHANNEL = r"(?:channel|kanal|canal|canale|kanaal|kanaƂ)" + + +@dataclass +class Network: + ssid: str + signal: int = 0 # percent, 0 if unknown + band24: bool | None = None # True if any access point is on 2.4 GHz, None if unknown + current: bool = False + + +def _run(cmd: list[str]) -> str: + try: + result = subprocess.run(cmd, capture_output=True, timeout=15, check=False) + except (OSError, subprocess.SubprocessError): + return "" + if result.returncode != 0: + return "" + return result.stdout.decode("utf-8", errors="replace") + + +def _merge(found: dict[str, Network], ssid: str, signal: int, band24: bool | None) -> None: + if not ssid: + return # hidden network + net = found.setdefault(ssid, Network(ssid)) + net.signal = max(net.signal, signal) + if band24: + net.band24 = True + elif band24 is False and net.band24 is None: + net.band24 = False + + +def parse_netsh_networks(text: str) -> list[Network]: + """Parse `netsh wlan show networks mode=bssid`. One SSID block holds one or more BSSIDs.""" + found: dict[str, Network] = {} + ssid = "" + signal = 0 + in_bssid = False + + def flush(channel: int | None) -> None: + if ssid and in_bssid: + _merge(found, ssid, signal, None if channel is None else channel <= 14) + + channel: int | None = None + for line in text.splitlines(): + if m := re.match(r"^\s*SSID\s+\d+\s*:\s?(.*)$", line): + flush(channel) + ssid, signal, channel, in_bssid = m.group(1).strip(), 0, None, False + elif re.match(r"^\s*BSSID\s+\d+\s*:", line): + flush(channel) + signal, channel, in_bssid = 0, None, True + elif in_bssid and (m := re.match(r"^\s*[^:]+:\s*(\d+)\s*%\s*$", line)): + signal = int(m.group(1)) + elif in_bssid and (m := re.match(rf"^\s*{_CHANNEL}\s*:\s*(\d+)\s*$", line, re.IGNORECASE)): + channel = int(m.group(1)) + flush(channel) + # A network listed with no BSSID lines at all still counts, band unknown. + for line in text.splitlines(): + if m := re.match(r"^\s*SSID\s+\d+\s*:\s?(.*)$", line): + _merge(found, m.group(1).strip(), 0, None) + return list(found.values()) + + +def parse_netsh_current(text: str) -> str | None: + """The connected SSID from `netsh wlan show interfaces` (the BSSID line is skipped).""" + for line in text.splitlines(): + if m := re.match(r"^\s*SSID\s*:\s?(.*)$", line): + return m.group(1).strip() or None + return None + + +def parse_nmcli(text: str) -> list[Network]: + """Parse `nmcli -t -f ACTIVE,SIGNAL,FREQ,SSID device wifi list`. SSID is last, colons escaped.""" + found: dict[str, Network] = {} + for line in text.splitlines(): + parts = re.split(r"(? str | None: + """The SSID from `networksetup -getairportnetwork `.""" + m = re.match(r"^Current Wi-Fi Network:\s?(.*)$", text.strip()) + return (m.group(1).strip() or None) if m else None + + +def _order(networks: list[Network]) -> list[Network]: + return sorted(networks, key=lambda n: (not n.current, -n.signal, n.ssid.lower())) + + +def scan() -> list[Network]: + """Networks in range, the computer's own first, then strongest first. Empty if we cannot tell.""" + if sys.platform.startswith("win"): + networks = parse_netsh_networks(_run(["netsh", "wlan", "show", "networks", "mode=bssid"])) + current = parse_netsh_current(_run(["netsh", "wlan", "show", "interfaces"])) + for net in networks: + net.current = net.ssid == current + elif sys.platform == "darwin": + networks = [] + for device in ("en0", "en1"): + ssid = parse_networksetup(_run(["networksetup", "-getairportnetwork", device])) + if ssid: + networks = [Network(ssid, current=True)] + break + else: + networks = parse_nmcli(_run(["nmcli", "-t", "-f", "ACTIVE,SIGNAL,FREQ,SSID", "device", "wifi", "list"])) + return _order(networks) + + +def usable(networks: list[Network]) -> tuple[list[Network], int]: + """The networks a plug can join (2.4 GHz or unknown band), and how many 5 GHz-only ones were left out.""" + keep = [n for n in networks if n.band24 is not False] + return keep, len(networks) - len(keep) diff --git a/tests/test_wifiscan.py b/tests/test_wifiscan.py new file mode 100644 index 0000000..4103014 --- /dev/null +++ b/tests/test_wifiscan.py @@ -0,0 +1,120 @@ +from switchback import wifiscan +from switchback.cli import convert_question, is_private + +NETSH = """ +Interface name : Wi-Fi +There are 4 networks currently visible. + +SSID 1 : Home Net + Network type : Infrastructure + Authentication : WPA2-Personal + Encryption : CCMP + BSSID 1 : aa:bb:cc:00:00:01 + Signal : 61% + Radio type : 802.11ax + Band : 5 GHz + Channel : 149 + BSSID 2 : aa:bb:cc:00:00:02 + Signal : 88% + Radio type : 802.11n + Band : 2.4 GHz + Channel : 6 + +SSID 2 : Fast: Only + Network type : Infrastructure + Authentication : WPA3-Personal + Encryption : CCMP + BSSID 1 : aa:bb:cc:00:00:03 + Signal : 70% + Radio type : 802.11ax + Channel : 36 + +SSID 3 : + Network type : Infrastructure + BSSID 1 : aa:bb:cc:00:00:04 + Signal : 99% + Channel : 1 + +SSID 4 : IoT + Network type : Infrastructure + BSSID 1 : aa:bb:cc:00:00:05 + Signal : 40% + Channel : 11 +""" + +NETSH_INTERFACES = """ + Name : Wi-Fi + State : connected + SSID : Home Net + BSSID : aa:bb:cc:00:00:02 + Channel : 6 +""" + + +def by_name(networks): + return {n.ssid: n for n in networks} + + +def test_netsh_networks(): + nets = by_name(wifiscan.parse_netsh_networks(NETSH)) + assert set(nets) == {"Home Net", "Fast: Only", "IoT"} # the hidden one is dropped + assert nets["Home Net"].band24 is True and nets["Home Net"].signal == 88 + assert nets["Fast: Only"].band24 is False + assert nets["IoT"].band24 is True and nets["IoT"].signal == 40 + + +def test_netsh_without_bssid_lines_keeps_the_names(): + nets = by_name(wifiscan.parse_netsh_networks("SSID 1 : Alpha\n Network type : Infrastructure\nSSID 2 : Beta\n")) + assert set(nets) == {"Alpha", "Beta"} + assert nets["Alpha"].band24 is None + + +def test_netsh_german_channel_word(): + text = "SSID 1 : Netz\n BSSID 1 : aa:bb:cc:00:00:01\n Signal : 50%\n Kanal : 3\n" + assert wifiscan.parse_netsh_networks(text)[0].band24 is True + + +def test_netsh_current(): + assert wifiscan.parse_netsh_current(NETSH_INTERFACES) == "Home Net" + assert wifiscan.parse_netsh_current(" State : disconnected\n") is None + + +def test_nmcli(): + text = "yes:82:2437 MHz:Home Net\nno:60:5180 MHz:Home Net\nno:55:5745 MHz:Fast\\: Only\nno:90:2412 MHz:\n" + nets = by_name(wifiscan.parse_nmcli(text)) + assert set(nets) == {"Home Net", "Fast: Only"} + assert nets["Home Net"].current and nets["Home Net"].band24 is True and nets["Home Net"].signal == 82 + assert nets["Fast: Only"].band24 is False + + +def test_networksetup(): + assert wifiscan.parse_networksetup("Current Wi-Fi Network: Home Net\n") == "Home Net" + assert wifiscan.parse_networksetup("You are not associated with an AirPort network.\n") is None + + +def test_usable_drops_5ghz_only_and_orders_current_first(): + nets = wifiscan._order(wifiscan.parse_netsh_networks(NETSH)) + for net in nets: + net.current = net.ssid == "IoT" + keep, left_out = wifiscan.usable(wifiscan._order(nets)) + assert [n.ssid for n in keep] == ["IoT", "Home Net"] + assert left_out == 1 + + +def test_scan_never_raises(monkeypatch): + monkeypatch.setattr(wifiscan, "_run", lambda cmd: "") + assert wifiscan.scan() == [] + + +class FakePlug: + name = "sbplug-a1b2c3" + + +def test_convert_question(): + assert convert_question(FakePlug(), 1) == "Found 1 plug. It will become sbplug-a1b2c3. Convert it? [y/N] " + assert convert_question(FakePlug(), 3).startswith("Found 3 plugs. The nearest will become sbplug-a1b2c3.") + + +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)