diff --git a/CHANGELOG.md b/CHANGELOG.md index 12fb09f..fbdf115 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [0.4.0] - unreleased + +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. + +### Added + +- `firmware/esphome/plug-mini.yaml`: the plug's hardware as one public package. Relay output, button, both LEDs, BL0937 power monitoring with calibration and range checks, lifetime and daily energy, chip temperature. No Wi-Fi, API, OTA, names or secrets. Use it as a remote package to build your own config. +- Power, current and voltage are measured every 2 seconds but sent to Home Assistant only on a real change (1 W, 0.05 A, 1 V) plus a heartbeat. Below 1.5 W the plug reads 0. The raw 2 second values stay available on the plug (`id(power)` and so on) for lambdas. +- 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. + +### Changed + +- `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). + ## [0.3.0] - 2026-11-18 First release from this repository, with fresh history. diff --git a/README.md b/README.md index 357aeb9..15bf2ca 100644 --- a/README.md +++ b/README.md @@ -128,17 +128,40 @@ A plain "check for update" in the app does not work: that path uses SwitchBot's ## After conversion -The image Switchback writes is a small bootstrap. It has: +The image Switchback writes is the full hardware profile, so a plug is useful as soon as it joins your Wi-Fi. It shows up as `sbplug-xxxxxx` with: -- the relay, the button (short press toggles, hold 10 seconds to factory reset) and the blue status LED, -- the ESPHome API **without encryption**, -- OTA with the published password **`switchbota`**. +- **Relay**, a switch. It stays off after a power cut. A clean restart or an OTA update does not blip the load. +- **Outlet Power**, **Outlet Current** and **Outlet Voltage**. The plug measures every 2 seconds but only sends a reading when it changes by a real amount (1 W, 0.05 A, 1 V), plus a heartbeat, so your history stays small. Below 1.5 W it reads 0. +- **Outlet Energy** (lifetime, kWh) and **Outlet Daily Energy** (Wh, resets at midnight), once a minute. Both work with the Home Assistant Energy dashboard. +- **Internal Temp**, the chip temperature, as a diagnostic. +- The button: a short press toggles the relay. Hold it 10 seconds to factory reset. +- 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`**. -Adopt the plug in ESPHome or Home Assistant and flash your own config over OTA right away, with your own API key and OTA password. You can build on the same hardware definition as a remote package: +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. + +### Adopt it + +Device Builder and Home Assistant offer an **Adopt** button for a converted plug. Adopting writes a short config that pulls in this repository's firmware, pinned to the release, and adds your own Wi-Fi and a fresh API encryption key. Install it once over OTA and you are done. Change the OTA password at the same time: ```yaml +substitutions: + ota_password: !secret ota_password +``` + +### Or build your own config + +`plug-mini.yaml` is the hardware on its own: relay output, button, LEDs, power monitoring. It has no Wi-Fi, API or OTA section, no names and no secrets, so you can build anything on it. Your config supplies the relay switch, the two button scripts (`on_button_press`, `on_button_hold`) and a time source. `sbplug-common.yaml` shows the defaults. + +```yaml +esphome: + name: kitchen-kettle + packages: - switchback: github://WiFiGUY512/switchback/firmware/esphome/sbplug-common.yaml@v0.3.0 + 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 api: encryption: @@ -151,8 +174,27 @@ ota: wifi: ssid: !secret wifi_ssid password: !secret wifi_password + +time: + - platform: homeassistant + +switch: + - platform: output + name: "Relay" + id: relay + output: relay_output + restore_mode: RESTORE_DEFAULT_ON + +script: + - id: on_button_press + then: + - switch.toggle: relay + - id: on_button_hold + then: [] ``` +Lambdas that act on load (for example, "turn off when the kettle is done") should read the raw 2 second values, `id(power).state`, `id(current).state` and `id(voltage).state`. Home Assistant gets the rate-limited copies. + To flash a config while the plug is still in hotspot mode, join its `sbplug-xxxxxx` network and run `esphome upload your.yaml --device 192.168.4.1` (OTA password `switchbota`). ## Commands diff --git a/firmware/esphome/addon-ble-proxy.yaml b/firmware/esphome/addon-ble-proxy.yaml new file mode 100644 index 0000000..bf8a783 --- /dev/null +++ b/firmware/esphome/addon-ble-proxy.yaml @@ -0,0 +1,30 @@ +#============================================================================== +# Optional: Bluetooth proxy for Home Assistant (add over OTA, after converting) +#============================================================================== +# Not part of any Switchback payload. The Bluetooth stack makes the image too +# large for the flasher's first write, so add it in your own config once the +# 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 +# +# 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 +# under 320 ms while Wi-Fi is up. Long windows (the old 1100 ms setting) +# starve Wi-Fi. Only add this to plugs that are near Bluetooth devices you +# use; a few well placed proxies beat one on every plug. +#============================================================================== + +esp32: + framework: + sdkconfig_options: + CONFIG_BT_BLE_42_FEATURES_SUPPORTED: y + CONFIG_BT_BLE_50_FEATURES_SUPPORTED: y + +esp32_ble_tracker: + scan_parameters: + active: false + +bluetooth_proxy: + active: true diff --git a/firmware/esphome/plug-mini.yaml b/firmware/esphome/plug-mini.yaml new file mode 100644 index 0000000..e2df6f0 --- /dev/null +++ b/firmware/esphome/plug-mini.yaml @@ -0,0 +1,387 @@ +#============================================================================== +# SwitchBot Plug Mini (W1901400 / W1901401, ESP32-C3): hardware package +#============================================================================== +# Everything the plug's hardware can do, and nothing about your network. It has +# no wifi, ota or api keys, no names and no secrets. Use it as a remote package +# and add your own wifi, api and ota: +# +# packages: +# plug: github://WiFiGUY512/switchback/firmware/esphome/plug-mini.yaml@v0.4.0 +# +# Pin a release tag, not main. +# +# WHAT THE PACKAGE NEEDS FROM YOUR CONFIG +# - esphome: name (and friendly_name if you like) +# - wifi: and api: (the status LED follows both) +# - one time source, for Outlet Daily Energy (sntp or homeassistant) +# - a relay switch and two scripts, on_button_press and on_button_hold. +# sbplug-common.yaml has the default ones: a "Relay" switch, short press +# toggles, hold 10 s for a factory reset. Write your own to change that. +# +# IDS YOU CAN USE +# relay_output binary output: drives the relay and the white LED together +# relay_led internal light on the white LED (follows relay_output) +# physical_button the button (inverted, pull-up) +# status_led the blue LED, run by the update_status_led script +# power, current, voltage raw readings every power_update_interval (2 s), +# internal, calibrated and range-checked. Use these in +# lambdas that act on load. Home Assistant gets the +# rate-limited copies below. +# energy lifetime energy (kWh) +# +# ENTITIES IN HOME ASSISTANT +# Outlet Power W, 1 decimal, below 1.5 W reads 0. Sent on a 1 W +# change, else once a minute. +# Outlet Current A, 2 decimals. Sent on a 0.05 A change, else once a +# minute. +# Outlet Voltage V, whole volts. Sent on a 1 V change, else every +# 5 minutes. +# Outlet Energy kWh, lifetime, once a minute +# Outlet Daily Energy Wh, resets at midnight, once a minute +# Internal Temp C, chip temperature, every 5 minutes (diagnostic) +# +# PINS +# GPIO2 button (inverted, pull-up) GPIO18 BL0937 CF +# GPIO6 relay GPIO19 BL0937 CF1 +# GPIO7 white LED (inverted) GPIO20 BL0937 SEL (inverted) +# GPIO8 blue LED (inverted) +# +# LEDS +# White: on while the relay is on. +# Blue: fast blink = no Wi-Fi, solid = Wi-Fi but no API client, +# slow glow = Home Assistant connected. +# +# RELAY THROUGH RESTARTS +# On a clean restart (OTA, restart button) on_shutdown latches the relay pin +# with gpio_hold_en(). The first write to relay_output after boot sets the +# new level and releases the latch, so an OTA does not blip the load. A +# power cut, crash or watchdog reset still drops it. +# +# BLUETOOTH +# Not included, to keep the image small and the radio free for Wi-Fi. Add +# addon-ble-proxy.yaml over OTA if you want a Bluetooth proxy. +#============================================================================== + +substitutions: + pin_button: GPIO02 + pin_relay: GPIO06 + pin_led_white: GPIO07 + pin_led_blue: GPIO08 + pin_hlw_cf: GPIO18 + pin_hlw_cf1: GPIO19 + pin_hlw_sel: GPIO20 + relay_gpio_num: "6" # pin_relay as a bare number, for the hold lambdas + + # BL0937 front end + voltage_divider: "1467" + current_resistor: "0.001" + + # Per-channel calibration. Measured on a W1901400 (Oct 2026 batch) against + # a Kill A Watt at about 1190 W resistive. Set any of them to "1.0" for the + # raw chip reading, or to your own figures for another batch. + voltage_cal: "1.0024" + current_cal: "0.8655" + power_cal: "0.9601" + + # Readings above what the plug can carry (15 A, 1800 W, mains voltage) are + # dropped, so a garbage first sample after boot never reaches history or + # the energy totals. + power_max: "1900" + current_max: "16" + voltage_max: "150" + + # Below this the plug reads 0 W (the BL0937 shows a little noise at no load) + power_floor: "1.5" + + power_update_interval: "2s" + energy_publish_interval: "60s" + +#------------------------------------------------------------------------------ +# Board +#------------------------------------------------------------------------------ +esp32: + board: esp32-c3-devkitm-1 + variant: ESP32C3 + flash_size: 4MB + framework: + type: esp-idf + sdkconfig_options: + CONFIG_ESP_TASK_WDT_TIMEOUT_S: "10" + +esphome: + on_boot: + priority: -100 + then: + - script.execute: update_status_led + on_shutdown: + then: + - lambda: |- + gpio_hold_en((gpio_num_t) ${relay_gpio_num}); + ESP_LOGW("relay_hold", "Relay GPIO%d latched for restart", ${relay_gpio_num}); + +#------------------------------------------------------------------------------ +# The status LED follows Wi-Fi and API state +#------------------------------------------------------------------------------ +api: + on_client_connected: + - script.execute: update_status_led + on_client_disconnected: + - script.execute: update_status_led + +wifi: + on_connect: + - script.execute: update_status_led + on_disconnect: + - script.execute: update_status_led + +# The 40 ms glow effect floods the log at DEBUG +logger: + logs: + light: INFO + +#------------------------------------------------------------------------------ +# Outputs +#------------------------------------------------------------------------------ +output: + # Drive the relay through this. It sets the relay pin, releases a restart + # latch left by on_shutdown (no-op otherwise), and mirrors the white LED. + - platform: template + id: relay_output + type: binary + write_action: + - lambda: |- + gpio_num_t p = (gpio_num_t) ${relay_gpio_num}; + gpio_set_level(p, state); + gpio_hold_dis(p); + id(relay_gpio).set_state(state); + id(relay_led_output).set_state(state); + + - platform: gpio + id: relay_gpio + pin: ${pin_relay} + + - platform: gpio + id: relay_led_output + pin: + number: ${pin_led_white} + inverted: true + + - platform: ledc + id: status_led_output + pin: + number: ${pin_led_blue} + inverted: true + frequency: 1000Hz + +light: + - platform: binary + id: relay_led + output: relay_led_output + internal: true + + - platform: monochromatic + id: status_led + output: status_led_output + internal: true + default_transition_length: 0ms + effects: + - strobe: + name: "Fast Blink" + colors: + - state: true + brightness: 100% + duration: 500ms + - state: false + duration: 500ms + - lambda: + name: "Slow Glow" + update_interval: 40ms + lambda: |- + static float phase = 0; + phase += 0.05; // about 2 s per cycle + if (phase > 3.14159) phase = -3.14159; + float brightness = (sin(phase) + 1.0) / 2.0; + auto call = id(status_led).turn_on(); + call.set_brightness(brightness); + call.set_transition_length(0); + call.perform(); + +script: + - id: update_status_led + then: + - if: + condition: + not: + wifi.connected: + then: + - light.turn_on: + id: status_led + brightness: 100% + effect: "Fast Blink" + else: + - if: + condition: + api.connected: + then: + - light.turn_on: + id: status_led + brightness: 100% + effect: "Slow Glow" + else: + - light.turn_on: + id: status_led + brightness: 100% + effect: none + +# Catch any state change the callbacks missed +interval: + - interval: 30s + then: + - script.execute: update_status_led + +#------------------------------------------------------------------------------ +# Button: short press runs on_button_press, holding it runs on_button_hold +# at the 3 s mark (your config supplies both scripts) +#------------------------------------------------------------------------------ +binary_sensor: + - platform: gpio + id: physical_button + internal: true + pin: + number: ${pin_button} + mode: INPUT_PULLUP + inverted: true + filters: + - delayed_on: 10ms + on_multi_click: + - timing: + - ON for at most 2.9s + - OFF for at least 0.1s + then: + - script.execute: on_button_press + - timing: + - ON for at least 3s + then: + - script.execute: on_button_hold + +#------------------------------------------------------------------------------ +# Power monitoring (BL0937) +#------------------------------------------------------------------------------ +sensor: + # Raw readings: internal, every power_update_interval. Lambdas read these. + - platform: hlw8012 + id: hlw_sensor + model: BL0937 + sel_pin: + number: ${pin_hlw_sel} + inverted: true + cf_pin: ${pin_hlw_cf} + cf1_pin: ${pin_hlw_cf1} + voltage_divider: ${voltage_divider} + current_resistor: ${current_resistor} + update_interval: ${power_update_interval} + change_mode_every: 4 + power: + id: power + internal: true + unit_of_measurement: W + device_class: power + state_class: measurement + accuracy_decimals: 1 + filters: + - multiply: ${power_cal} + - lambda: 'if (x > ${power_max} || x < 0) return {}; return x;' + current: + id: current + internal: true + unit_of_measurement: A + device_class: current + state_class: measurement + accuracy_decimals: 2 + filters: + - multiply: ${current_cal} + - lambda: 'if (x > ${current_max} || x < 0) return {}; return x;' + voltage: + id: voltage + internal: true + unit_of_measurement: V + device_class: voltage + state_class: measurement + accuracy_decimals: 1 + filters: + - multiply: ${voltage_cal} + - lambda: 'if (x > ${voltage_max} || x < 0) return {}; return x;' + energy: + name: "Outlet Energy" + id: energy + unit_of_measurement: kWh + device_class: energy + state_class: total_increasing + accuracy_decimals: 3 + filters: + - multiply: 0.001 + - multiply: ${power_cal} + - heartbeat: ${energy_publish_interval} + + # What Home Assistant sees: the same readings, sent only when they change + # by a real amount, plus a heartbeat. The names match the older firmware, + # so existing entities and their history carry over. + - platform: copy + source_id: power + id: power_published + name: "Outlet Power" + unit_of_measurement: W + device_class: power + state_class: measurement + accuracy_decimals: 1 + filters: + - lambda: 'return x < ${power_floor} ? 0.0f : x;' + - round: 1 + - or: + - delta: 1.0 + - heartbeat: 60s + + - platform: copy + source_id: current + id: current_published + name: "Outlet Current" + unit_of_measurement: A + device_class: current + state_class: measurement + accuracy_decimals: 2 + filters: + - round: 2 + - or: + - delta: 0.05 + - heartbeat: 60s + + - platform: copy + source_id: voltage + id: voltage_published + name: "Outlet Voltage" + unit_of_measurement: V + device_class: voltage + state_class: measurement + accuracy_decimals: 0 + filters: + - round: 0 + - or: + - delta: 1.0 + - heartbeat: 300s + + # Integrates the raw 2 s power, not the rate-limited copy + - platform: total_daily_energy + name: "Outlet Daily Energy" + id: daily_energy + power_id: power + accuracy_decimals: 2 + filters: + - heartbeat: ${energy_publish_interval} + + - platform: internal_temperature + name: "Internal Temp" + update_interval: 300s + accuracy_decimals: 0 + entity_category: diagnostic + filters: + - round: 0 diff --git a/firmware/esphome/sbplug-common.yaml b/firmware/esphome/sbplug-common.yaml index 57e622b..679222e 100644 --- a/firmware/esphome/sbplug-common.yaml +++ b/firmware/esphome/sbplug-common.yaml @@ -1,43 +1,52 @@ #============================================================================== -# SwitchBot Plug Mini (W1901400 / W1901401), ESP32-C3: the hardware +# Switchback bootstrap: shared by every payload (portal, direct, implant) #============================================================================== -# Shared by every Switchback payload. It has no api, ota or wifi section, so -# you can also pull it into your own config as a remote package: +# The full hardware profile (plug-mini.yaml: relay, button, LEDs, power, +# voltage, current, energy) plus the defaults a fresh plug needs: # -# packages: -# switchback: github://WiFiGUY512/switchback/firmware/esphome/sbplug-common.yaml@v0.3.0 +# - a "Relay" switch, off after a power cut (relay_restore_mode) +# - button: short press toggles the relay. Hold 10 s to factory reset, +# which wipes Wi-Fi saved through the hotspot, so a portal plug offers it +# again. The blue LED keeps its status pattern while you hold. +# - a time source for Outlet Daily Energy (sntp) +# - captive portal, and the project info Device Builder and Home Assistant +# use to offer "Adopt" # -# then add your own api, ota and wifi. Pin a release tag, not main. +# This file has no api, ota or wifi section. The payload files add those. # # SIZE LIMIT (for payloads the flasher writes): # The flasher writes from 0x0 and can only write 0x171000 (1,511,424) bytes, -# so firmware.factory.bin has to stay under that. That is why there are no -# BLE components here. Add those later in your own config over OTA. +# so firmware.factory.bin has to stay under that. build_payload.py refuses +# anything larger. Bluetooth is not in the bootstrap for this reason; add +# addon-ble-proxy.yaml later over OTA. # # PARTITIONS: # A converted plug keeps the partition table from the image the flasher # wrote (ESPHome default for 4MB: two app slots). OTA never changes it. -# -# BUTTON: short press toggles the relay. Hold 10 s to factory reset, which -# wipes Wi-Fi saved through the hotspot, so a portal plug offers it again. -# BLUE LED: blinks while the plug is not on Wi-Fi. #============================================================================== substitutions: name: sbplug + friendly_name: "SwitchBot Plug Mini" + switchback_version: "0.4.0" + relay_restore_mode: RESTORE_DEFAULT_OFF + +packages: + hardware: !include plug-mini.yaml esphome: name: ${name} + friendly_name: ${friendly_name} name_add_mac_suffix: true + project: + name: wifiguy512.switchback-plug-mini + version: ${switchback_version} platformio_options: board_build.flash_mode: dio -esp32: - board: esp32-c3-devkitm-1 - variant: ESP32C3 - flash_size: 4MB - framework: - type: esp-idf +dashboard_import: + package_import_url: github://WiFiGUY512/switchback/firmware/esphome/sbplug-portal.yaml@v${switchback_version} + import_full_config: false # UART0 is what the serial pads expose, so boot logs show up on the recovery path. logger: @@ -45,40 +54,34 @@ logger: captive_portal: -status_led: - pin: - number: GPIO8 - inverted: true +time: + - platform: sntp + id: sntp_time switch: - - platform: gpio + - platform: output id: relay name: "Relay" - pin: GPIO6 - restore_mode: RESTORE_DEFAULT_OFF + output: relay_output + restore_mode: ${relay_restore_mode} button: - platform: factory_reset id: factory_reset_button internal: true -binary_sensor: - - platform: gpio - id: plug_button - internal: true - pin: - number: GPIO2 - mode: INPUT_PULLUP - inverted: true - filters: - - delayed_on: 10ms - on_multi_click: - - timing: - - ON for at most 1s - - OFF for at least 0.3s - then: - - switch.toggle: relay - - timing: - - ON for at least 10s - then: - - button.press: factory_reset_button +script: + - id: on_button_press + then: + - switch.toggle: relay + + # Runs at the 3 s mark. Still held 7 s later (10 s in all) = factory reset. + - id: on_button_hold + mode: single + then: + - delay: 7s + - if: + condition: + binary_sensor.is_on: physical_button + then: + - button.press: factory_reset_button diff --git a/pyproject.toml b/pyproject.toml index 2a02b9a..2ba508f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "switchback" -version = "0.3.0" +version = "0.4.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/uv.lock b/uv.lock index 32fb42c..af88c9d 100644 --- a/uv.lock +++ b/uv.lock @@ -736,7 +736,7 @@ wheels = [ [[package]] name = "switchback" -version = "0.3.0" +version = "0.4.0" source = { editable = "." } dependencies = [ { name = "bleak" },