From 6033e125c2c9b88d45de1e2263e66db4809ebd2d Mon Sep 17 00:00:00 2001 From: NinjaLikesCheez Date: Thu, 5 Nov 2026 19:18:07 +0100 Subject: [PATCH 1/5] Add signed OTA updates from GitHub releases and modernize firmware On boot the device checks the latest GitHub release and installs it if newer. Updates are fetched over TLS (verified against the ESP-IDF CA bundle), must carry an ECDSA P-256 signature from the project key, and must contain a version marker matching the release tag so older signed images can't be republished to downgrade devices. Failed boots roll back. A release workflow builds, signs and publishes firmware for v* tags, verifying the signature against the key devices currently trust. Modernization: - pioarduino platform (Arduino-ESP32 3.3.12 / ESP-IDF 5.5) - ArduinoJson 7, ESP32Async web server, ESP-IDF MQTT client - Replace archived double-reset library with a small NVS-based one - Use the CA bundle instead of pinning ISRG Root X1; spacestate.pixelbar.nl now chains to DigiCert Global Root G2, which the old firmware rejects - Split the sketch into modules; min_spiffs partitions for 1.9MB OTA slots Credentials moved from compile-time Secrets.h into NVS (set via the config portal), since release binaries are public. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 35 ++ .github/workflows/release.yml | 92 +++++ .gitignore | 4 + README.md | 110 +++++- keys/ota_signing_key.pub.pem | 0 platformio.ini | 52 ++- scripts/firmware_version.py | 16 + scripts/generate-ota-signing-key.sh | 38 ++ src/Config.h | 70 ++++ src/Constants.h | 95 ----- src/DoubleResetDetector.cpp | 51 +++ src/DoubleResetDetector.h | 30 ++ src/MqttPublisher.cpp | 111 ++++++ src/MqttPublisher.h | 36 ++ src/OtaUpdater.cpp | 335 ++++++++++++++++++ src/OtaUpdater.h | 42 +++ src/README.md | 3 - src/Secrets_example.h | 13 +- src/Settings.cpp | 66 ++++ src/Settings.h | 31 ++ src/SpaceStateSwitch.ino | 525 ---------------------------- src/SpaceStateSync.cpp | 162 +++++++++ src/SpaceStateSync.h | 34 ++ src/main.cpp | 320 +++++++++++++++++ 24 files changed, 1628 insertions(+), 643 deletions(-) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/release.yml create mode 100644 keys/ota_signing_key.pub.pem create mode 100644 scripts/firmware_version.py create mode 100755 scripts/generate-ota-signing-key.sh create mode 100644 src/Config.h delete mode 100644 src/Constants.h create mode 100644 src/DoubleResetDetector.cpp create mode 100644 src/DoubleResetDetector.h create mode 100644 src/MqttPublisher.cpp create mode 100644 src/MqttPublisher.h create mode 100644 src/OtaUpdater.cpp create mode 100644 src/OtaUpdater.h delete mode 100644 src/README.md create mode 100644 src/Settings.cpp create mode 100644 src/Settings.h delete mode 100644 src/SpaceStateSwitch.ino create mode 100644 src/SpaceStateSync.cpp create mode 100644 src/SpaceStateSync.h create mode 100644 src/main.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..e5d1c8c --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,35 @@ +name: Build + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + + - uses: actions/cache@v6 + with: + path: ~/.platformio + key: pio-${{ hashFiles('platformio.ini') }} + + - name: Install PlatformIO + run: pip install platformio + + - name: Build + run: pio run + + - uses: actions/upload-artifact@v7 + with: + name: firmware-dev + path: .pio/build/SpaceStateSwitch/firmware.bin diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5324246 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,92 @@ +# Builds, signs and publishes firmware when a version tag (e.g. v1.2.3) is pushed. +# Devices install the newest release's firmware.bin automatically on boot. +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: write # Create the GitHub release + +jobs: + release: + runs-on: ubuntu-latest + environment: release # Optional: add required reviewers to gate signing + env: + TAG: ${{ github.ref_name }} + steps: + - name: Validate tag + run: | + if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Release tags must look like v1.2.3 (got '$TAG')" + exit 1 + fi + + - uses: actions/checkout@v7 + with: + fetch-depth: 0 # Needed to find the previous release's public key + + - name: Check signing setup + env: + OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }} + run: | + if [[ ! -s keys/ota_signing_key.pub.pem ]]; then + echo "::error::keys/ota_signing_key.pub.pem is empty, run scripts/generate-ota-signing-key.sh (see README)" + exit 1 + fi + if [[ -z "$OTA_SIGNING_KEY" ]]; then + echo "::error::The OTA_SIGNING_KEY secret is not set (see README)" + exit 1 + fi + + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + + - uses: actions/cache@v6 + with: + path: ~/.platformio + key: pio-${{ hashFiles('platformio.ini') }} + + - name: Install tools + run: pip install platformio cryptography + + - name: Build + run: FIRMWARE_VERSION="$TAG" pio run + + - name: Sign + env: + OTA_SIGNING_KEY: ${{ secrets.OTA_SIGNING_KEY }} + run: | + set -euo pipefail + signer=~/.platformio/packages/framework-arduinoespressif32/tools/bin_signing.py + key="$RUNNER_TEMP/ota_signing_key.pem" + trap 'rm -f "$key"' EXIT + (umask 077 && printf '%s\n' "$OTA_SIGNING_KEY" > "$key") + + mkdir -p dist + python "$signer" --bin .pio/build/SpaceStateSwitch/firmware.bin --key "$key" --out dist/firmware.bin + + # Make sure devices will accept it. Devices check against the key in the firmware + # they're running, i.e. the previous release's key (which differs during rotation). + trusted_key="$RUNNER_TEMP/trusted_key.pub.pem" + previous_tag=$(git describe --tags --abbrev=0 --match 'v*' "$TAG^" 2>/dev/null || true) + if [[ -n "$previous_tag" ]] && git show "$previous_tag:keys/ota_signing_key.pub.pem" > "$trusted_key" 2>/dev/null && [[ -s "$trusted_key" ]]; then + echo "Verifying against the public key of $previous_tag" + else + echo "Verifying against the committed public key" + cp keys/ota_signing_key.pub.pem "$trusted_key" + fi + python "$signer" --verify dist/firmware.bin --pubkey "$trusted_key" | tee verify.log + grep -q "SUCCESSFUL" verify.log + + # The device checks the signed image really contains this version. + grep -qaF $'\x1f'"SSS-FW-VERSION:${TAG#v}"$'\x1f' dist/firmware.bin + + (cd dist && sha256sum firmware.bin > firmware.bin.sha256) + + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$TAG" dist/firmware.bin dist/firmware.bin.sha256 --verify-tag --generate-notes --title "$TAG" diff --git a/.gitignore b/.gitignore index ca4c9fd..8a229b4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ .vscode/launch.json .vscode/ipch /src/Secrets.h + +# OTA signing private keys must never be committed (the public key in keys/ is fine) +*.pem +!keys/*.pub.pem diff --git a/README.md b/README.md index 85e4263..9c68a54 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,111 @@ # SpaceStateSwitch -This contains the code of the Arduino of the SpaceState Switch at the hackerspace. Code created by DiverAlpha, referencing the old code of royvandongen. +Firmware for the space state switch at Pixelbar. It runs on an ESP32 (Wemos D1 Mini32). It reads the physical switch and publishes the state to [spacestate.pixelbar.nl](https://spacestate.pixelbar.nl), to MQTT (with Home Assistant discovery) and to a small local JSON API. On every boot it checks GitHub for a newer release and installs it over the air. + +Code created by DiverAlpha, referencing the old code of royvandongen. + +## Behaviour + +| LED colour | Meaning | +| --- | --- | +| Green | Space is open | +| Red | Space is closed | +| Blue | Not connected to WiFi | +| Purple (blinking) | Installing a firmware update | + +- If the switch changes, the new state is sent to the space state website. Failed submissions are retried every 10 seconds. +- Every 10 minutes the online state is fetched. If someone changed the state on the website, that override is shown until the switch is flipped again. +- **Double press reset** to open the config portal. It runs as WiFi network `space-state-switch` with password `1337hacker` and closes after 2 minutes. In the portal you set the WiFi network, the MQTT broker and the space state API credentials. Password and token fields start empty; leave them empty to keep the stored value. + +### HTTP API + +`http://space-state-switch.local/` + +- `GET /`: current state (`is_open`, `state`, `is_overwritten`, `physical_state`) +- `GET /info`: device, network and firmware info +- `GET /heap`: memory usage + +### MQTT + +- `space-state-switch/state`: `1` (open) or `0` (closed), retained and re-published every 5 minutes +- `space-state-switch/LWT`: `online` / `offline` +- Home Assistant discovery on `homeassistant/binary_sensor/space-state-switch/config` + +## Building + +This uses [PlatformIO](https://platformio.org) with the [pioarduino](https://github.com/pioarduino/platform-espressif32) platform (Arduino-ESP32 3.x / ESP-IDF 5.x). + +```sh +pio run # build +pio run -t upload # flash over USB +pio device monitor # serial logs +``` + +Local builds report version `dev` and **never update themselves**, so a build you flashed by hand won't be replaced by the latest release. To put a device back on automatic updates, flash a release build (see below), for example by building it locally with `FIRMWARE_VERSION=v1.2.3 pio run -t upload`. + +### Migrating from the old firmware + +The partition table changed to make room for two OTA slots, and partition tables can't be changed over the air. Flash the first version of this firmware **over USB** with `pio run -t upload`. WiFi and MQTT settings are kept. + +Space state credentials are no longer compiled in. Enter them in the config portal, or put them in `src/Secrets.h` (see `src/Secrets_example.h`) for that first USB flash. They are then stored on the device. + +## OTA updates + +On boot, after connecting to WiFi, the device: + +1. Fetches `https://api.github.com/repos/pixelbar/SpaceStateSwitch/releases/latest`. +2. Stops if the release tag (`vX.Y.Z`) isn't newer than the running version. +3. Streams the release's `firmware.bin` into the inactive OTA partition. +4. Checks the image's ECDSA signature and checks that the signed image contains the version the tag claims. If either check fails, the update is thrown away and the current firmware keeps running. +5. Reboots into the new firmware. If the new firmware doesn't get as far as connecting to WiFi (it crashes, or the config portal times out), the bootloader rolls back to the previous version. + +### Security model + +- **Transport:** every connection uses TLS. Certificates are checked against the Mozilla CA bundle that ships with ESP-IDF. +- **Authenticity:** TLS only proves the bytes came from GitHub. Devices also require a signature from the project's private key. Someone who gets into the GitHub repository or the release assets still can't install their own firmware without that key. +- **No downgrades:** only strictly newer versions are installed. The version is checked against a marker inside the signed image, so an older signed image can't be re-uploaded under a newer tag. +- **No secrets in firmware:** release binaries are public, so credentials live in the device's NVS, not in the binary. + +### One-time setup + +1. Generate the signing key pair: + + ```sh + scripts/generate-ota-signing-key.sh + ``` + + This writes `keys/ota_signing_key.pub.pem` (commit it) and `ota_signing_key.pem` (private, git-ignored). + +2. Store the private key as a GitHub Actions secret, keep a copy in the space's password manager, then delete the local file: + + ```sh + gh secret set OTA_SIGNING_KEY < ota_signing_key.pem + rm ota_signing_key.pem + ``` + +3. Commit the public key. Flash a release build to the device over USB once, because the device needs firmware that contains the public key. + +Until a public key is committed, OTA is disabled and the release workflow fails rather than publishing unsigned firmware. + +### Releasing + +```sh +git tag v1.2.3 +git push origin v1.2.3 +``` + +The [release workflow](.github/workflows/release.yml) builds with that version, signs the binary, checks the signature against the committed public key, and publishes a GitHub release with `firmware.bin`. Devices pick it up the next time they boot. + +The workflow runs in a `release` GitHub environment. Add required reviewers to that environment if you want someone to approve each signing. + +### Rotating the signing key + +A device only accepts updates signed with the key built into the firmware it's running. To rotate the key: + +1. Run `FORCE=1 scripts/generate-ota-signing-key.sh new_key.pem` and commit the new public key. +2. Release a version while `OTA_SIGNING_KEY` still holds the **old** private key. Devices accept it because it's signed with the key they trust, and it contains the new public key. +3. Once devices have updated, set `OTA_SIGNING_KEY` to the new private key (`gh secret set OTA_SIGNING_KEY < new_key.pem`). + +The release workflow checks each release against the public key of the *previous* release, which is the key devices actually trust, so it catches a key that was swapped too early. Devices still on firmware older than the rotation release will reject new releases and have to be updated over USB. + +If the private key is lost, devices have to be re-flashed over USB. diff --git a/keys/ota_signing_key.pub.pem b/keys/ota_signing_key.pub.pem new file mode 100644 index 0000000..e69de29 diff --git a/platformio.ini b/platformio.ini index 6e57144..e189313 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,24 +1,44 @@ ; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html +[platformio] +default_envs = SpaceStateSwitch + [env:SpaceStateSwitch] -platform = espressif32 +; The official PlatformIO espressif32 platform is stuck on Arduino-ESP32 2.x. +; pioarduino is the community-maintained platform that tracks the current +; Arduino-ESP32 3.x releases (ESP-IDF 5.x). Pinned for reproducible builds. +platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.312-1/platform-espressif32.zip board = wemos_d1_mini32 framework = arduino + upload_speed = 921600 monitor_speed = 115200 -lib_deps = - me-no-dev/AsyncTCP@1.1.1 - https://github.com/me-no-dev/ESPAsyncWebServer.git#f71e3d4 - https://github.com/tzapu/WiFiManager.git#88c378f - bblanchon/ArduinoJson@^6.19.4 - adafruit/Adafruit NeoPixel@^1.10.5 - knolleary/PubSubClient@^2.8 - khoih-prog/ESP_DoubleResetDetector@^1.3.2 +monitor_filters = esp32_exception_decoder + +; Two 1.9MB OTA app slots (the default table only has 1.25MB slots, which is +; too tight for an Arduino 3.x + TLS build). NVS lives at the same offset as in +; the default table, so WiFi / MQTT settings survive the switch. +; NOTE: partition tables cannot be changed over OTA, the first flash after this +; change must be done over USB. +board_build.partitions = min_spiffs.csv + +; Public key used to verify OTA firmware signatures. See README.md. +board_build.embed_txtfiles = keys/ota_signing_key.pub.pem + +; Sets FIRMWARE_VERSION from the FIRMWARE_VERSION environment variable (CI) or +; "dev" for local builds. +extra_scripts = pre:scripts/firmware_version.py + +build_flags = + -DUPDATE_SIGN ; Enable signature verification in the Update library + -DCORE_DEBUG_LEVEL=3 ; Info level logging (log_i / log_w / log_e) +build_src_flags = + -Wall -Wextra + +lib_deps = + esp32async/AsyncTCP@^3.5.0 + esp32async/ESPAsyncWebServer@^3.12.1 + tzapu/WiFiManager@^2.0.17 + bblanchon/ArduinoJson@^7.4.3 + adafruit/Adafruit NeoPixel@^1.15.5 diff --git a/scripts/firmware_version.py b/scripts/firmware_version.py new file mode 100644 index 0000000..3462a9a --- /dev/null +++ b/scripts/firmware_version.py @@ -0,0 +1,16 @@ +# PlatformIO pre-build script: injects FIRMWARE_VERSION into the build. +# +# CI sets the FIRMWARE_VERSION environment variable from the release tag +# (e.g. "1.2.3"). Local builds default to "dev", which disables OTA updates +# so a development build flashed over USB is not immediately replaced by the +# latest release. +import os + +Import("env") # noqa: F821 - provided by PlatformIO/SCons + +version = os.environ.get("FIRMWARE_VERSION", "").strip() or "dev" +if version.startswith("v"): + version = version[1:] + +print(f"Firmware version: {version}") +env.Append(CPPDEFINES=[("FIRMWARE_VERSION", env.StringifyMacro(version))]) # noqa: F821 diff --git a/scripts/generate-ota-signing-key.sh b/scripts/generate-ota-signing-key.sh new file mode 100755 index 0000000..375e868 --- /dev/null +++ b/scripts/generate-ota-signing-key.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Generates the ECDSA P-256 key pair used to sign OTA firmware updates. +# +# scripts/generate-ota-signing-key.sh [private-key-path] +# +# Writes the public key to keys/ota_signing_key.pub.pem (commit this) and the +# private key to the given path (default: ./ota_signing_key.pem, git-ignored). +# Store the private key as the OTA_SIGNING_KEY GitHub Actions secret and in a +# password manager, then delete the local copy. See README.md. +set -euo pipefail + +cd "$(dirname "$0")/.." +private_key="${1:-ota_signing_key.pem}" +public_key="keys/ota_signing_key.pub.pem" + +if [[ -e "$private_key" ]]; then + echo "error: $private_key already exists" >&2 + exit 1 +fi +if [[ -s "$public_key" && "${FORCE:-}" != "1" ]]; then + cat >&2 </dev/null + +echo "Private key: $private_key (keep secret, do NOT commit)" +echo "Public key: $public_key (commit this)" +echo +echo "Next: gh secret set OTA_SIGNING_KEY < \"$private_key\"" diff --git a/src/Config.h b/src/Config.h new file mode 100644 index 0000000..a9f8ffb --- /dev/null +++ b/src/Config.h @@ -0,0 +1,70 @@ +#pragma once + +#include + +#ifndef FIRMWARE_VERSION +#define FIRMWARE_VERSION "dev" // Normally injected by scripts/firmware_version.py +#endif + +namespace config { + +// MARK: - Hardware + +constexpr uint8_t kNeopixelPin = 27; // IO27, Neopixel header (330 Ohm resistor) +constexpr uint8_t kSwitchPin = 26; // IO26/D0, switch header (INPUT_PULLUP) +constexpr uint8_t kBuiltinLedPin = 2; +constexpr uint16_t kNumberOfPixels = 20; +constexpr uint8_t kNeopixelBrightness = 80; + +// MARK: - Timing + +// A second reset within this window after boot opens the WiFi config portal. +constexpr uint32_t kDoubleResetWindowMs = 5 * 1000; +// How often the physical switch is sampled. +constexpr uint32_t kSwitchPollIntervalMs = 250; +// How often the online space state is fetched, to detect overrides. +constexpr uint32_t kSpaceStatePollIntervalMs = 10 * 60 * 1000; +// Delay before retrying a failed space state submission or fetch. +constexpr uint32_t kSpaceStateRetryIntervalMs = 10 * 1000; +// Delay between MQTT reconnection attempts. +constexpr uint32_t kMqttReconnectIntervalMs = 10 * 1000; +// How often the state is re-published to MQTT. Must be below kMqttExpireAfterS. +constexpr uint32_t kMqttRepublishIntervalMs = 5 * 60 * 1000; +// Home Assistant marks the sensor unavailable after this many seconds without a state message. +constexpr uint32_t kMqttExpireAfterS = 15 * 60; +// How long the config portal stays open before rebooting. +constexpr uint32_t kConfigPortalTimeoutS = 120; +// Timeout for individual HTTP(S) operations. +constexpr uint32_t kHttpTimeoutMs = 15 * 1000; + +// MARK: - Network + +constexpr const char *kHostname = "space-state-switch"; +constexpr const char *kConfigApSsid = "space-state-switch"; +constexpr const char *kConfigApPassword = "1337hacker"; + +// NVS namespace for Settings (unchanged from the original firmware, so settings carry over). +constexpr const char *kPreferencesNamespace = "space-state"; + +// MARK: - Space state API + +constexpr const char *kSpaceStateUrl = "https://spacestate.pixelbar.nl/spacestate.php"; +constexpr const char *kToggleStateUrl = "https://spacestate.pixelbar.nl/togglestate.php"; + +// MARK: - MQTT + +constexpr uint16_t kMqttDefaultPort = 1883; +constexpr const char *kMqttStateTopic = "space-state-switch/state"; +constexpr const char *kMqttAvailabilityTopic = "space-state-switch/LWT"; +constexpr const char *kMqttDiscoveryTopic = "homeassistant/binary_sensor/space-state-switch/config"; + +// MARK: - OTA updates + +// GitHub repository ("owner/name") whose latest release is installed on boot. +constexpr const char *kGithubRepository = "pixelbar/SpaceStateSwitch"; +// Name of the signed firmware asset attached to each release. +constexpr const char *kFirmwareAssetName = "firmware.bin"; + +constexpr const char *kRepositoryUrl = "https://github.com/pixelbar/SpaceStateSwitch"; + +} // namespace config diff --git a/src/Constants.h b/src/Constants.h deleted file mode 100644 index 8102d44..0000000 --- a/src/Constants.h +++ /dev/null @@ -1,95 +0,0 @@ -#ifndef PB_CONTANTS -#define PB_CONTANTS 1 - -// The pin neopixel header (330Ohm resistor) -#define NEOPIXEL_PIN 27 // IO27 - -// The pin for the switch header (INPUT_PULLUP) -#define SWITCH_PIN 26 // IO26/D0 - -#define BUILTIN_LED_PIN 2 - -// The number of Neopixels supported on the header -#define NUMBER_OF_PIXELS 20 - -// Needed for "DoubleResetDetector", telling it to use SPIFFS. -#define ESP_DRD_USE_LITTLEFS false -#define ESP_DRD_USE_SPIFFS true -#define ESP_DRD_USE_EEPROM false - -// Number of seconds after reset during which a -// subsequent reset will be considered a double reset. -#define DRD_TIMEOUT 5 - -// RTC Memory Address for the DoubleResetDetector to use. Required, but not used on the ESP32 -#define DRD_ADDRESS 0 - -// The minimum interval between MQTT connection attempts -#define MQTT_CONNECT_INTERVAL 10000 // miliseconds - -// The interval between checks for the space state if it has been overwritten. -#define SPACE_STATE_CHECK_INTERVAL 10 * 60 * 1000 // 10 minutes in miliseconds. - -// The interval between checks for switch state changes. -#define SWITCH_STATE_INTERVAL 250 // milliseconds - -// The network SSID for the config portal. -#define CONFIG_AP_SSID "space-state-switch" - -// The network password for the config portal. -#define CONFIG_AP_PASSWORD "1337hacker" - -// The hostname for WiFi and mDNS. -#define HOSTNAME_PREFIX "space-state-switch" - -// The namespace used for the ESP32 preferences. -#define PREFERENCES_NAMESPACE "space-state" - -// The key used for the MQTT server in ESP32 Preferences and WiFiManager Parameter. -#define PREFERENCE_MQTT_SERVER_KEY "mqtt_server" - -// The key used for the MQTT port in ESP32 Preferences and WiFiManager Parameter. -#define PREFERENCE_MQTT_PORT_KEY "mqtt_port" - -// The key used for the MQTT username in ESP32 Preferences and WiFiManager Parameter. -#define PREFERENCE_MQTT_USERNAME_KEY "mqtt_username" - -// The key used for the MQTT password in ESP32 Preferences and WiFiManager Parameter. -#define PREFERENCE_MQTT_PASSWORD_KEY "mqtt_password" - - -const char* isrg_root_x1_ca_pem = \ - "-----BEGIN CERTIFICATE-----\n" \ - "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" \ - "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" \ - "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" \ - "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" \ - "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" \ - "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" \ - "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" \ - "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" \ - "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" \ - "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" \ - "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" \ - "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" \ - "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" \ - "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" \ - "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" \ - "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" \ - "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" \ - "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" \ - "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" \ - "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" \ - "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" \ - "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" \ - "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" \ - "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" \ - "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" \ - "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" \ - "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" \ - "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" \ - "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" \ - "-----END CERTIFICATE-----\n"; - - -#endif \ No newline at end of file diff --git a/src/DoubleResetDetector.cpp b/src/DoubleResetDetector.cpp new file mode 100644 index 0000000..15d38ff --- /dev/null +++ b/src/DoubleResetDetector.cpp @@ -0,0 +1,51 @@ +#include "DoubleResetDetector.h" + +#include +#include +#include + +namespace { +constexpr const char *kNamespace = "drd"; +constexpr const char *kKeyArmed = "armed"; +} // namespace + +bool DoubleResetDetector::detect() { + const esp_reset_reason_t reason = esp_reset_reason(); + // The EN/reset button on the ESP32 shows up as a power-on reset. + const bool userReset = reason == ESP_RST_POWERON || reason == ESP_RST_EXT; + + Preferences prefs; + prefs.begin(kNamespace, true); + const bool wasArmed = prefs.getBool(kKeyArmed, false); + prefs.end(); + + if (userReset && wasArmed) { + setArmed(false); + return true; + } + + setArmed(true); + armedAtMs_ = millis(); + return false; +} + +void DoubleResetDetector::loop() { + if (armed_ && millis() - armedAtMs_ > windowMs_) { + setArmed(false); + } +} + +void DoubleResetDetector::stop() { + if (armed_) { + setArmed(false); + } +} + +void DoubleResetDetector::setArmed(bool armed) { + Preferences prefs; + if (prefs.begin(kNamespace, false)) { + prefs.putBool(kKeyArmed, armed); + prefs.end(); + } + armed_ = armed; +} diff --git a/src/DoubleResetDetector.h b/src/DoubleResetDetector.h new file mode 100644 index 0000000..f825d06 --- /dev/null +++ b/src/DoubleResetDetector.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +// Detects two resets in quick succession (e.g. double pressing the reset button). +// +// A flag is armed in NVS on boot and cleared once the device has been running +// for longer than the window. If the device boots while the flag is still armed, +// that's a double reset. Software restarts (OTA, config saved) and crashes are +// ignored so they never trigger the config portal. +class DoubleResetDetector { + public: + explicit DoubleResetDetector(uint32_t windowMs) : windowMs_(windowMs) {} + + // Call once, early in setup(). Returns true if a double reset was detected. + bool detect(); + + // Call from loop(); disarms the detector once the window has passed. + void loop(); + + // Disarms immediately, e.g. before blocking in the config portal. + void stop(); + + private: + void setArmed(bool armed); + + uint32_t windowMs_; + uint32_t armedAtMs_ = 0; + bool armed_ = false; +}; diff --git a/src/MqttPublisher.cpp b/src/MqttPublisher.cpp new file mode 100644 index 0000000..fe49eec --- /dev/null +++ b/src/MqttPublisher.cpp @@ -0,0 +1,111 @@ +#include "MqttPublisher.h" + +#include +#include +#include + +#include "Config.h" +#include "Settings.h" + +namespace { +constexpr const char *kPayloadOnline = "online"; +constexpr const char *kPayloadOffline = "offline"; +constexpr const char *kPayloadOpen = "1"; +constexpr const char *kPayloadClosed = "0"; +} // namespace + +void MqttPublisher::begin(const Settings &settings, StateProvider currentState) { + if (!settings.hasMqtt()) { + Serial.println("[MQTT] No server configured"); + return; + } + currentState_ = currentState; + + // The client copies all strings, so temporaries are fine here. + esp_mqtt_client_config_t cfg = {}; + cfg.broker.address.hostname = settings.mqttServer.c_str(); + cfg.broker.address.port = settings.mqttPort; + cfg.broker.address.transport = MQTT_TRANSPORT_OVER_TCP; + cfg.credentials.client_id = config::kHostname; + if (!settings.mqttUsername.isEmpty()) { + cfg.credentials.username = settings.mqttUsername.c_str(); + cfg.credentials.authentication.password = settings.mqttPassword.c_str(); + } + cfg.session.last_will.topic = config::kMqttAvailabilityTopic; + cfg.session.last_will.msg = kPayloadOffline; + cfg.session.last_will.qos = 1; + cfg.session.last_will.retain = 1; + cfg.network.reconnect_timeout_ms = config::kMqttReconnectIntervalMs; + + client_ = esp_mqtt_client_init(&cfg); + if (client_ == nullptr) { + Serial.println("[MQTT] Failed to create client"); + return; + } + esp_mqtt_client_register_event(client_, MQTT_EVENT_ANY, &MqttPublisher::onEvent, this); + if (esp_mqtt_client_start(client_) != ESP_OK) { + Serial.println("[MQTT] Failed to start client"); + } +} + +void MqttPublisher::publishState(bool open) { + if (!connected_) { + return; + } + // Non-blocking: queued in the client's outbox and sent by the MQTT task. + esp_mqtt_client_enqueue(client_, config::kMqttStateTopic, open ? kPayloadOpen : kPayloadClosed, 0, 0, 0, true); +} + +void MqttPublisher::onEvent(void *arg, const char *base, int32_t eventId, void *eventData) { + auto *self = static_cast(arg); + switch (static_cast(eventId)) { + case MQTT_EVENT_CONNECTED: + Serial.println("[MQTT] Connected"); + self->connected_ = true; + esp_mqtt_client_publish(self->client_, config::kMqttAvailabilityTopic, kPayloadOnline, 0, 1, 1); + self->publishDiscovery(); + if (self->currentState_) { + self->publishState(self->currentState_()); + } + break; + case MQTT_EVENT_DISCONNECTED: + if (self->connected_) { + Serial.println("[MQTT] Disconnected"); + } + self->connected_ = false; + break; + case MQTT_EVENT_ERROR: + Serial.println("[MQTT] Connection error"); + break; + default: + break; + } +} + +void MqttPublisher::publishDiscovery() { + // Home Assistant MQTT discovery, using abbreviated keys: + // https://www.home-assistant.io/integrations/mqtt/#discovery-messages + JsonDocument payload; + payload["dev_cla"] = "opening"; + payload["stat_t"] = config::kMqttStateTopic; + payload["pl_on"] = kPayloadOpen; + payload["pl_off"] = kPayloadClosed; + payload["uniq_id"] = config::kHostname; + payload["name"] = "Space state"; + payload["avty_t"] = config::kMqttAvailabilityTopic; + payload["exp_aft"] = config::kMqttExpireAfterS; + + JsonObject device = payload["dev"].to(); + device["name"] = "Space state switch"; + device["cu"] = String("http://") + WiFi.localIP().toString() + "/"; + device["mdl"] = "ESP32"; + device["mf"] = "renssies"; + device["sw"] = FIRMWARE_VERSION; + device["ids"].to().add(WiFi.macAddress()); + + String json; + serializeJson(payload, json); + if (esp_mqtt_client_publish(client_, config::kMqttDiscoveryTopic, json.c_str(), json.length(), 1, 1) < 0) { + Serial.println("[MQTT] Failed to publish Home Assistant discovery"); + } +} diff --git a/src/MqttPublisher.h b/src/MqttPublisher.h new file mode 100644 index 0000000..f98b4e5 --- /dev/null +++ b/src/MqttPublisher.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +#include + +struct Settings; +struct esp_mqtt_client; + +// Publishes the space state to MQTT, including Home Assistant discovery. +// +// Uses the ESP-IDF MQTT client, which runs in its own task and handles +// (re)connecting in the background, so the main loop never blocks on the broker. +class MqttPublisher { + public: + using StateProvider = bool (*)(); + + // Starts the client if an MQTT server is configured. `currentState` is called + // (from the MQTT task) to publish the state after (re)connecting. + void begin(const Settings &settings, StateProvider currentState); + + // Thread-safe. No-op when not connected; the state is re-sent on (re)connect. + void publishState(bool open); + + bool isConnected() const { + return connected_; + } + + private: + static void onEvent(void *arg, const char *base, int32_t eventId, void *eventData); + void publishDiscovery(); + + esp_mqtt_client *client_ = nullptr; + StateProvider currentState_ = nullptr; + std::atomic connected_{false}; +}; diff --git a/src/OtaUpdater.cpp b/src/OtaUpdater.cpp new file mode 100644 index 0000000..6bb963d --- /dev/null +++ b/src/OtaUpdater.cpp @@ -0,0 +1,335 @@ +#include "OtaUpdater.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "Config.h" + +#ifndef UPDATE_SIGN +#error "OTA requires signature verification: build with -DUPDATE_SIGN (see platformio.ini)" +#endif + +// The public key is embedded from keys/ota_signing_key.pub.pem (board_build.embed_txtfiles). +// An empty file disables OTA. +extern const char kOtaPublicKeyPem[] asm("_binary_keys_ota_signing_key_pub_pem_start"); + +namespace { + +// Marker embedded in every image. After the signature has been verified, the +// downloaded image is searched for the marker of the version the release claims +// to be, binding the (unsigned) release tag to the (signed) image contents. +// The 0x1F separators can't appear in a version string, so a match is unambiguous. +#define VERSION_MARKER_PREFIX "\x1fSSS-FW-VERSION:" +#define VERSION_MARKER_SUFFIX "\x1f" +const char kVersionMarker[] = VERSION_MARKER_PREFIX FIRMWARE_VERSION VERSION_MARKER_SUFFIX; + +// Arduino-ESP32's Update library appends a zero-padded signature of this size. +constexpr size_t kSignatureBlockSize = 512; + +struct Version { + long major = 0; + long minor = 0; + long patch = 0; + + // Parses "1.2.3" or "v1.2.3". Pre-release / build suffixes are rejected. + static bool parse(const char *s, Version &out) { + if (s == nullptr) { + return false; + } + if (*s == 'v' || *s == 'V') { + s++; + } + long *parts[] = {&out.major, &out.minor, &out.patch}; + for (int i = 0; i < 3; i++) { + if (!isdigit(static_cast(*s))) { + return false; + } + char *end = nullptr; + *parts[i] = strtol(s, &end, 10); + s = end; + if (i < 2) { + if (*s != '.') { + return false; + } + s++; + } + } + return *s == '\0'; + } + + bool operator>(const Version &o) const { + if (major != o.major) return major > o.major; + if (minor != o.minor) return minor > o.minor; + return patch > o.patch; + } +}; + +struct Release { + String version; // Tag without the leading "v" + String firmwareUrl; +}; + +std::unique_ptr makeTlsClient() { + auto client = std::make_unique(); + // Verify servers against the Mozilla CA bundle shipped with ESP-IDF, so GitHub + // rotating certificates or CDN hosts doesn't break updates. + client->useBuiltinCACertBundle(); + client->setHandshakeTimeout(config::kHttpTimeoutMs / 1000); + return client; +} + +void addCommonHeaders(HTTPClient &http) { + http.setUserAgent("SpaceStateSwitch/" FIRMWARE_VERSION); + http.setConnectTimeout(config::kHttpTimeoutMs); + http.setTimeout(config::kHttpTimeoutMs); + // Avoid chunked transfer encoding so the body can be streamed directly. + http.useHTTP10(true); +} + +bool fetchLatestRelease(NetworkClientSecure &client, Release &release) { + const String url = String("https://api.github.com/repos/") + config::kGithubRepository + "/releases/latest"; + + HTTPClient http; + if (!http.begin(client, url)) { + Serial.println("[OTA] Invalid release URL"); + return false; + } + addCommonHeaders(http); + http.addHeader("Accept", "application/vnd.github+json"); + http.addHeader("X-GitHub-Api-Version", "2022-11-28"); + + const int status = http.GET(); + if (status != HTTP_CODE_OK) { + // 404 simply means there are no releases yet. + Serial.printf("[OTA] Release lookup failed: %d %s\n", status, status < 0 ? http.errorToString(status).c_str() : ""); + http.end(); + return false; + } + + // The full response is large (release notes, uploader details, ...); only keep what we need. + JsonDocument filter; + filter["tag_name"] = true; + filter["assets"][0]["name"] = true; + filter["assets"][0]["browser_download_url"] = true; + + JsonDocument doc; + const DeserializationError error = deserializeJson(doc, http.getStream(), DeserializationOption::Filter(filter)); + http.end(); + if (error) { + Serial.printf("[OTA] Failed to parse release: %s\n", error.c_str()); + return false; + } + + String tag = doc["tag_name"] | ""; + if (tag.startsWith("v") || tag.startsWith("V")) { + tag.remove(0, 1); + } + release.version = tag; + + for (JsonObject asset : doc["assets"].as()) { + if (strcmp(asset["name"] | "", config::kFirmwareAssetName) == 0) { + release.firmwareUrl = asset["browser_download_url"] | ""; + } + } + return true; +} + +// Searches the given partition for `needle` in the first `length` bytes. +bool partitionContains(const esp_partition_t *partition, size_t length, const String &needle) { + constexpr size_t kChunkSize = 4096; + const size_t overlap = needle.length() - 1; + std::unique_ptr buffer(new (std::nothrow) uint8_t[kChunkSize + overlap]); + if (!buffer) { + return false; + } + + size_t carried = 0; + for (size_t offset = 0; offset < length; offset += kChunkSize) { + const size_t toRead = std::min(kChunkSize, length - offset); + if (esp_partition_read(partition, offset, buffer.get() + carried, toRead) != ESP_OK) { + return false; + } + const size_t available = carried + toRead; + if (memmem(buffer.get(), available, needle.c_str(), needle.length()) != nullptr) { + return true; + } + // Keep the tail so markers spanning two chunks are still found. + carried = std::min(overlap, available); + memmove(buffer.get(), buffer.get() + available - carried, carried); + } + return false; +} + +bool downloadAndInstall(NetworkClientSecure &client, const Release &release, ota::ProgressCallback onProgress) { + const size_t keyLength = strlen(kOtaPublicKeyPem) + 1; // mbedtls needs the NUL for PEM keys + UpdaterECDSAVerifier verifier(reinterpret_cast(kOtaPublicKeyPem), keyLength, HASH_SHA256); + if (!Update.installSignature(&verifier)) { + Serial.println("[OTA] Failed to install signature verifier"); + return false; + } + + HTTPClient http; + if (!release.firmwareUrl.startsWith("https://") || !http.begin(client, release.firmwareUrl)) { + Serial.println("[OTA] Invalid firmware URL"); + return false; + } + addCommonHeaders(http); + // Release downloads redirect to a CDN. HTTPClient only follows https -> https. + http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); + + const int status = http.GET(); + if (status != HTTP_CODE_OK) { + Serial.printf("[OTA] Firmware download failed: %d %s\n", status, status < 0 ? http.errorToString(status).c_str() : ""); + http.end(); + return false; + } + + const int contentLength = http.getSize(); + if (contentLength <= static_cast(kSignatureBlockSize)) { + Serial.printf("[OTA] Unexpected firmware size: %d\n", contentLength); + http.end(); + return false; + } + const size_t totalSize = static_cast(contentLength); + + if (!Update.begin(totalSize)) { + Serial.printf("[OTA] Cannot start update: %s\n", Update.errorString()); + http.end(); + return false; + } + + NetworkClient *stream = http.getStreamPtr(); + constexpr size_t kBufferSize = 1024; + std::unique_ptr buffer(new (std::nothrow) uint8_t[kBufferSize]); + if (!buffer) { + Update.abort(); + http.end(); + return false; + } + uint32_t lastDataAt = millis(); + while (Update.remaining() > 0) { + const size_t available = stream->available(); + if (available == 0) { + if (!stream->connected() || millis() - lastDataAt > config::kHttpTimeoutMs) { + Serial.println("[OTA] Download interrupted"); + Update.abort(); + http.end(); + return false; + } + delay(1); + continue; + } + + const size_t toRead = std::min({available, kBufferSize, Update.remaining()}); + const size_t read = stream->readBytes(buffer.get(), toRead); + if (read == 0 || Update.write(buffer.get(), read) != read) { + Serial.printf("[OTA] Write failed: %s\n", Update.errorString()); + Update.abort(); + http.end(); + return false; + } + lastDataAt = millis(); + if (onProgress) { + onProgress(Update.progress(), totalSize); + } + } + http.end(); + + // Verifies the image and its signature, then sets it as the boot partition. + if (!Update.end()) { + Serial.printf("[OTA] Verification failed, keeping current firmware: %s\n", Update.errorString()); + return false; + } + + const esp_partition_t *running = esp_ota_get_running_partition(); + const esp_partition_t *updated = esp_ota_get_boot_partition(); + const String expectedMarker = String(VERSION_MARKER_PREFIX) + release.version + VERSION_MARKER_SUFFIX; + if (updated == nullptr || updated == running || + !partitionContains(updated, totalSize - kSignatureBlockSize, expectedMarker)) { + Serial.printf("[OTA] Signed image is not version %s, refusing to boot it\n", release.version.c_str()); + esp_ota_set_boot_partition(running); + return false; + } + + return true; +} + +} // namespace + +// Defer the rollback decision until ota::markFirmwareValid() is called, rather than +// accepting a freshly installed image as soon as it starts. +extern "C" bool verifyRollbackLater() { + return true; +} + +namespace ota { + +Result checkAndUpdate(ProgressCallback onProgress) { + // Reference the marker so the linker keeps it in the image. + (void)*static_cast(kVersionMarker); + + Version current; + if (!Version::parse(FIRMWARE_VERSION, current)) { + Serial.println("[OTA] Development build (" FIRMWARE_VERSION "), automatic updates disabled"); + return Result::Disabled; + } + if (kOtaPublicKeyPem[0] == '\0') { + Serial.println("[OTA] No signing key compiled in, automatic updates disabled"); + return Result::Disabled; + } + if (!WiFi.isConnected()) { + return Result::Failed; + } + + Serial.printf("[OTA] Running %s, checking %s for updates\n", FIRMWARE_VERSION, config::kGithubRepository); + auto client = makeTlsClient(); + + Release release; + if (!fetchLatestRelease(*client, release)) { + return Result::Failed; + } + + Version latest; + if (!Version::parse(release.version.c_str(), latest)) { + Serial.printf("[OTA] Ignoring release with unsupported tag '%s'\n", release.version.c_str()); + return Result::Failed; + } + if (!(latest > current)) { + Serial.printf("[OTA] Up to date (latest release: %s)\n", release.version.c_str()); + return Result::UpToDate; + } + if (release.firmwareUrl.isEmpty()) { + Serial.printf("[OTA] Release %s has no %s asset\n", release.version.c_str(), config::kFirmwareAssetName); + return Result::Failed; + } + + Serial.printf("[OTA] Installing %s\n", release.version.c_str()); + if (!downloadAndInstall(*client, release, onProgress)) { + return Result::Failed; + } + + Serial.printf("[OTA] Update to %s installed, rebooting\n", release.version.c_str()); + Serial.flush(); + ESP.restart(); + return Result::Failed; // Unreachable +} + +void markFirmwareValid() { + const esp_partition_t *running = esp_ota_get_running_partition(); + esp_ota_img_states_t state; + if (esp_ota_get_state_partition(running, &state) == ESP_OK && state == ESP_OTA_IMG_PENDING_VERIFY) { + if (esp_ota_mark_app_valid_cancel_rollback() == ESP_OK) { + Serial.println("[OTA] New firmware confirmed, rollback cancelled"); + } + } +} + +} // namespace ota diff --git a/src/OtaUpdater.h b/src/OtaUpdater.h new file mode 100644 index 0000000..b7f99c7 --- /dev/null +++ b/src/OtaUpdater.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +// Over-the-air updates from GitHub releases. +// +// On boot the device asks the GitHub API for the latest release of +// config::kGithubRepository. If its tag (e.g. "v1.2.3") is newer than the running +// FIRMWARE_VERSION, the release's signed firmware asset is streamed into the +// inactive OTA partition and the device reboots into it. +// +// Security: +// - All traffic uses TLS, verified against the ESP-IDF Mozilla CA bundle. +// - The image must carry a valid ECDSA P-256 signature from the key whose public +// half is keys/ota_signing_key.pub.pem. TLS only proves the bytes came from +// GitHub; the signature proves they came from us, so a compromised GitHub +// account or release cannot push arbitrary firmware. +// - The signed image must contain a version marker matching the release tag, +// so an older (validly signed) image can't be re-published under a newer tag +// to downgrade devices. +// - Only strictly newer versions are installed; "dev" builds never update. +// - If the new firmware fails to boot and connect, the bootloader rolls back to +// the previous image (see markFirmwareValid()). +namespace ota { + +enum class Result { + Disabled, // Dev build or no signing key compiled in. + UpToDate, + Failed, // Network/verification error; the running firmware is kept. + // On success the device reboots, so there is no "Updated" result. +}; + +using ProgressCallback = void (*)(size_t written, size_t total); + +// Checks GitHub for a newer release and installs it. Requires WiFi to be connected. +Result checkAndUpdate(ProgressCallback onProgress = nullptr); + +// Confirms the running image is healthy, cancelling a pending rollback. +// Call once the firmware has proven it works (e.g. connected to WiFi). +void markFirmwareValid(); + +} // namespace ota diff --git a/src/README.md b/src/README.md deleted file mode 100644 index 85e4263..0000000 --- a/src/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# SpaceStateSwitch - -This contains the code of the Arduino of the SpaceState Switch at the hackerspace. Code created by DiverAlpha, referencing the old code of royvandongen. diff --git a/src/Secrets_example.h b/src/Secrets_example.h index 1d933ad..f5c6274 100644 --- a/src/Secrets_example.h +++ b/src/Secrets_example.h @@ -1,10 +1,17 @@ #ifndef PB_SECRETS #define PB_SECRETS 1 -// The authentication token used for the request of setting the current space state. -#define SPACESTATE_REQUEST_TOKEN "token" +// OPTIONAL. Copy to Secrets.h (git-ignored) to seed the space state credentials +// on a device that doesn't have them stored yet. On first boot they are copied +// into NVS, so later OTA updates (which never contain Secrets.h) keep working. +// +// The credentials can also be set in the WiFi config portal instead. +// Never add Secrets.h to a release build: release binaries are public. // The username used for the request of setting the current space state. #define SPACESTATE_REQUEST_USERNAME "user" -#endif \ No newline at end of file +// The authentication token used for the request of setting the current space state. +#define SPACESTATE_REQUEST_TOKEN "token" + +#endif diff --git a/src/Settings.cpp b/src/Settings.cpp new file mode 100644 index 0000000..bf59c70 --- /dev/null +++ b/src/Settings.cpp @@ -0,0 +1,66 @@ +#include "Settings.h" + +#include + +#include "Config.h" + +#if __has_include("Secrets.h") +#include "Secrets.h" +#endif + +namespace { +// NVS keys are limited to 15 characters. The MQTT keys match the original firmware +// so existing devices keep their configuration. +constexpr const char *kKeyMqttServer = "mqtt_server"; +constexpr const char *kKeyMqttPort = "mqtt_port"; +constexpr const char *kKeyMqttUsername = "mqtt_username"; +constexpr const char *kKeyMqttPassword = "mqtt_password"; +constexpr const char *kKeySpaceStateUsername = "ss_username"; +constexpr const char *kKeySpaceStateToken = "ss_token"; +} // namespace + +void Settings::load() { + Preferences prefs; + // Open read-write so the namespace is created on first boot. + if (!prefs.begin(config::kPreferencesNamespace, false)) { + log_e("Failed to open preferences"); + return; + } + + mqttServer = prefs.getString(kKeyMqttServer, ""); + mqttServer.trim(); + // The original firmware stored the port as a string. + mqttPort = prefs.getString(kKeyMqttPort, "").toInt(); + if (mqttPort == 0) { + mqttPort = config::kMqttDefaultPort; + } + mqttUsername = prefs.getString(kKeyMqttUsername, ""); + mqttPassword = prefs.getString(kKeyMqttPassword, ""); + spaceStateUsername = prefs.getString(kKeySpaceStateUsername, ""); + spaceStateToken = prefs.getString(kKeySpaceStateToken, ""); + prefs.end(); + +#if defined(SPACESTATE_REQUEST_USERNAME) && defined(SPACESTATE_REQUEST_TOKEN) + if (!hasSpaceStateCredentials()) { + Serial.println("[Settings] Migrating space state credentials from Secrets.h to NVS"); + spaceStateUsername = SPACESTATE_REQUEST_USERNAME; + spaceStateToken = SPACESTATE_REQUEST_TOKEN; + save(); + } +#endif +} + +void Settings::save() const { + Preferences prefs; + if (!prefs.begin(config::kPreferencesNamespace, false)) { + log_e("Failed to open preferences for writing"); + return; + } + prefs.putString(kKeyMqttServer, mqttServer); + prefs.putString(kKeyMqttPort, String(mqttPort)); + prefs.putString(kKeyMqttUsername, mqttUsername); + prefs.putString(kKeyMqttPassword, mqttPassword); + prefs.putString(kKeySpaceStateUsername, spaceStateUsername); + prefs.putString(kKeySpaceStateToken, spaceStateToken); + prefs.end(); +} diff --git a/src/Settings.h b/src/Settings.h new file mode 100644 index 0000000..4c590aa --- /dev/null +++ b/src/Settings.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +// Runtime configuration, persisted in NVS and editable through the WiFi config portal. +// +// Credentials deliberately live here rather than being compiled in: release +// firmware is published publicly on GitHub, so anything compiled into it can be +// extracted by anyone. +struct Settings { + String mqttServer; + uint16_t mqttPort = 0; + String mqttUsername; + String mqttPassword; + + String spaceStateUsername; + String spaceStateToken; + + // Loads the settings from NVS. If no space state credentials are stored yet and + // an (optional, git-ignored) src/Secrets.h is present, those are used and persisted + // so that later OTA builds, which never contain Secrets.h, keep working. + void load(); + void save() const; + + bool hasMqtt() const { + return !mqttServer.isEmpty(); + } + bool hasSpaceStateCredentials() const { + return !spaceStateUsername.isEmpty() && !spaceStateToken.isEmpty(); + } +}; diff --git a/src/SpaceStateSwitch.ino b/src/SpaceStateSwitch.ino deleted file mode 100644 index b19f04b..0000000 --- a/src/SpaceStateSwitch.ino +++ /dev/null @@ -1,525 +0,0 @@ -#include "Constants.h" -#include "Secrets.h" - -#include -#include // Built in with ESP32 -#include // Built in with ESP32 -#include // Built in with ESP32 -#include // Built in with ESP32 -#include // Built in with ESP32 - -#include -#include -#include -#include - -#include -#include -#include -#include -#include "SPIFFS.h" - -#include -#include - -char mqttServer[40]; -char mqttPort[6] = "1883"; -char mqttUsername[34]; -char mqttPassword[34]; - -WiFiManager wifiManager; -WiFiManagerParameter paramMQTTServer(PREFERENCE_MQTT_SERVER_KEY, "MQTT Server", mqttServer, 40); -WiFiManagerParameter paramMQTTPort(PREFERENCE_MQTT_PORT_KEY, "MQTT Port", mqttPort, 6); -WiFiManagerParameter paramMQTTUsername(PREFERENCE_MQTT_USERNAME_KEY, "MQTT Auth Username (leave blank if unauthenticated)", mqttUsername, 40, " type='username' autocapitalize='none'"); -WiFiManagerParameter paramMQTTPassword(PREFERENCE_MQTT_PASSWORD_KEY, "MQTT Auth Password (leave blank if unauthenticated)", mqttPassword, 40, " type='password'"); - -Preferences preferences; - -WiFiClient espClient; -PubSubClient mqttClient(espClient); - -Adafruit_NeoPixel neopixels(NUMBER_OF_PIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800); - -String hostname; -String mqttStateTopic; -String mqttLastWillTopic; - -bool currentSpaceState = false; // false == off/closed, true == on/open -bool hasDeterminedInitalState = false; -bool currentSwitchState = false; // false == off/closed, true == on/open -bool performingRequest = false; -bool shouldSubmitCurrentSwitchState = false; - -unsigned long lastSwitchStateCheck = 0; -unsigned long lastMQTTConnectTime = 0; - -DoubleResetDetector* drd; - -AsyncWebServer webServer(80); - -void setup() { - SPIFFS.begin(true); // Format spiffs if not formatted. - - Serial.begin(115200); - - neopixels.begin(); - updateLEDs(); - - drd = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS); - - pinMode(SWITCH_PIN, INPUT_PULLUP); - pinMode(BUILTIN_LED_PIN, OUTPUT); - - hostname = "space-state-switch"; - mqttStateTopic = "space-state-switch/state"; - mqttLastWillTopic = "space-state-switch/LWT"; - - readPreferences(); - - setupWiFiManager(); - - setupHTTPServer(); - - xTaskCreate(checkSpaceStateTask, "CheckSpaceState", 6000, NULL, 5, NULL); - xTaskCreate(submitSpaceStateTask, "SubmitSpaceState", 6000, NULL, 5, NULL); -} - -void setupWiFiManager() { - - wifiManager.addParameter(¶mMQTTServer); - wifiManager.addParameter(¶mMQTTPort); - wifiManager.addParameter(¶mMQTTUsername); - wifiManager.addParameter(¶mMQTTPassword); - - wifiManager.setConfigPortalTimeout(120); - wifiManager.setConfigPortalBlocking(true); - wifiManager.setHostname(hostname); - wifiManager.setSaveConfigCallback(saveConfigCallback); - wifiManager.setConfigPortalTimeoutCallback(configModeTimeoutCallback); - wifiManager.setWiFiAutoReconnect(true); - wifiManager.setDebugOutput(false); - - if (drd->detectDoubleReset()) { - drd->stop(); - Serial.print("Double reset detected, starting config portal with password: "); - Serial.println(CONFIG_AP_PASSWORD); - wifiManager.startConfigPortal(CONFIG_AP_SSID, CONFIG_AP_PASSWORD); - } else { - Serial.print("If the switch fails to connect to the known network it with the following password: "); - Serial.println(CONFIG_AP_PASSWORD); - } - - if(wifiManager.autoConnect(CONFIG_AP_SSID, CONFIG_AP_PASSWORD)) { - Serial.println("Connected...yaay :)"); - Serial.print("IP Address: "); - Serial.print(WiFi.localIP()); - Serial.print(" MAC Address: "); - Serial.println(WiFi.macAddress()); - if (!MDNS.begin(hostname.c_str())) { - Serial.println("Failed to start mDNS"); - } - MDNS.addService("http", "tcp", 80); - MDNS.addServiceTxt("http", "tcp", "id", WiFi.macAddress().c_str()); - MDNS.addServiceTxt("http", "tcp", "ma", WiFi.macAddress().c_str()); - MDNS.addServiceTxt("http", "tcp", "hw", "esp32"); - updateLEDs(); - } -} - -void setupHTTPServer() { - webServer.onNotFound([](AsyncWebServerRequest *request) { - if (request->method() == HTTP_OPTIONS) { - request->send(200); - } else { - request->send(404, "text/html", "Page Not FoundPage Not Found"); - } - }); - - webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { - AsyncJsonResponse * response = new AsyncJsonResponse(); - response->addHeader("X-Server","ESP Async Web Server"); - - JsonObject root = response->getRoot(); - root["is_open"] = currentSpaceState; - root["state"] = stringForState(currentSpaceState); - root["is_overwritten"] = currentSpaceState != currentSwitchState; - root["physical_state"] = currentSwitchState; - JsonArray array = root.createNestedArray("endpoints"); - array.add("GET /heap"); - array.add("GET /info"); - response->setLength(); - - request->send(response); - }); - - webServer.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request) { - AsyncJsonResponse *response = new AsyncJsonResponse(); - response->addHeader("X-Server","ESP Async Web Server"); - - JsonObject root = response->getRoot(); - root["uptime"] = millis(); - root["heap"] = ESP.getFreeHeap(); - response->setLength(); - request->send(response); - }); - - webServer.on("/info", HTTP_GET, [](AsyncWebServerRequest *request) { - AsyncJsonResponse *response = new AsyncJsonResponse(); - response->addHeader("X-Server","ESP Async Web Server"); - - JsonObject root = response->getRoot(); - root["chip_id"] = WiFi.macAddress(); - root["ip_address"] = WiFi.localIP(); - root["mac_address"] = WiFi.macAddress(); - root["uptime"] = millis(); - root["change_wifi_instructions"] = "Double press the reset button to enter config mode."; - if (strlen(mqttServer) > 1) { - root["mqtt_server"] = mqttServer; - } else { - root["mqtt_server"] = nullptr; - } - JsonObject aboutObject = root.createNestedObject("about"); - aboutObject["original_by"] = "meepe"; - aboutObject["modified_by"] = "renssies"; - aboutObject["hardware"] = "Arduino on a ESP32 Wemos D1 Mini Alternative"; - aboutObject["repository"] = "https://github.com/pixelbar/SpaceStateSwitch"; - response->setLength(); - - request->send(response); - }); - - webServer.begin(); -} - -void readPreferences() { - Serial.println("Reading preferences"); - - if(!preferences.begin(PREFERENCES_NAMESPACE, true)) { - Serial.println("Failed to open read-only preferences"); - if(!preferences.begin(PREFERENCES_NAMESPACE, false)) { - Serial.println("Failed to open write preferences"); - } - } - - preferences.getString(PREFERENCE_MQTT_SERVER_KEY, mqttServer, 40); - preferences.getString(PREFERENCE_MQTT_PORT_KEY, mqttPort, 6); - preferences.getString(PREFERENCE_MQTT_USERNAME_KEY, mqttUsername, 34); - preferences.getString(PREFERENCE_MQTT_PASSWORD_KEY, mqttPassword, 34); - - Serial.print("MQTT Server: "); - Serial.println(mqttServer); - - if (atoi(mqttPort) <= 0) { - strcpy(mqttPort, "1883"); - } - - paramMQTTServer.setValue(mqttServer, 40); - paramMQTTPort.setValue(mqttPort, 6); - paramMQTTUsername.setValue(mqttUsername, 34); - paramMQTTPassword.setValue(mqttPassword, 34); - - preferences.end(); - -} - -void loop() { - drd->loop(); - mqttClient.loop(); - connectMQTT(); - - checkSwitchState(); -} - -void checkSwitchState() { - unsigned long now = millis(); - if ((now - lastSwitchStateCheck) <= SWITCH_STATE_INTERVAL) { - return; - } - bool newSwitchState = digitalRead(SWITCH_PIN) == LOW; - lastSwitchStateCheck = now; - if (!hasDeterminedInitalState) { - currentSpaceState = newSwitchState; - currentSwitchState = newSwitchState; - hasDeterminedInitalState = true; - - Serial.print("Determined original state: "); - Serial.println(stringForState(newSwitchState)); - spaceStateDidChange(newSwitchState, !newSwitchState); - return; - } - if (currentSwitchState == newSwitchState) { - return; - } - currentSwitchState = newSwitchState; - currentSpaceState = newSwitchState; - - spaceStateDidChange(newSwitchState, !newSwitchState); - shouldSubmitCurrentSwitchState = true; -} - -void submitSpaceStateTask(void *param) { - WiFiClientSecure *client = new WiFiClientSecure; - client->setCACert(isrg_root_x1_ca_pem); - while(true) { - vTaskDelay(portTICK_PERIOD_MS * 200); - if (!shouldSubmitCurrentSwitchState) { - continue; - } - if (WiFi.status() != WL_CONNECTED) { - continue; - } - if (!client) { - Serial.println("Failed to create secure client"); - client->stop(); - continue; - } - - String url = "https://spacestate.pixelbar.nl/togglestate.php"; - url += "?user="; - url += SPACESTATE_REQUEST_USERNAME; - url += "&token="; - url += SPACESTATE_REQUEST_TOKEN; - url += "&state="; - url += stringForState(currentSwitchState); - - HTTPClient httpsClient; - httpsClient.useHTTP10(true); - if (!httpsClient.begin(*client, url)) { // HTTPS - Serial.println("Malformed request"); - httpsClient.end(); - client->stop(); - continue; - } - Serial.print("GETting URL: "); - Serial.println(url); - performingRequest = true; - updateLEDs(); - int httpCode = httpsClient.GET(); - if (httpCode <= 0) { - httpsClient.end(); - client->stop(); - Serial.printf("Failed to perform submit GET request, error: %s\n", httpsClient.errorToString(httpCode).c_str()); - performingRequest = false; - continue; - } - Serial.printf("Submit space state response code: %d\n", httpCode); - if (httpCode >= 200 && httpCode < 400) { - shouldSubmitCurrentSwitchState = false; - } - performingRequest = false; - httpsClient.end(); - client->stop(); - - } -} - -void checkSpaceStateTask(void *param) { - WiFiClientSecure *client = new WiFiClientSecure; - client->setCACert(isrg_root_x1_ca_pem); - bool hasPerformedFirstCheck = false; - while(true) { - if (hasPerformedFirstCheck) { - vTaskDelay(portTICK_PERIOD_MS * SPACE_STATE_CHECK_INTERVAL); - } - if (performingRequest) { - continue; - } - if (WiFi.status() != WL_CONNECTED) { - continue; - } - if (!client) { - Serial.println("Failed to create secure client"); - client->stop(); - continue; - } - hasPerformedFirstCheck = true; - - const char url[46] = "https://spacestate.pixelbar.nl/spacestate.php"; - - HTTPClient httpsClient; - httpsClient.useHTTP10(true); - if (!httpsClient.begin(*client, url)) { // HTTPS - Serial.println("Malformed request"); - httpsClient.end(); - client->stop(); - continue; - } - Serial.print("GETting URL: "); - Serial.println(url); - updateLEDs(); - int httpCode = httpsClient.GET(); - if (httpCode <= 0) { - httpsClient.end(); - client->stop(); - Serial.printf("Failed to perform GET request, error: %s\n", httpsClient.errorToString(httpCode).c_str()); - continue; - } - Serial.printf("Response code: %d\n", httpCode); - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { - DynamicJsonDocument doc(128); - DeserializationError error = deserializeJson(doc, httpsClient.getStream()); - if (error.code() == error.Ok && doc.containsKey("state") && doc["state"].is()) { - String stateString = doc["state"].as(); - bool onlineSpaceState = stateString.equals("open"); - if (onlineSpaceState != currentSpaceState) { - Serial.println("An space state overwrite was detected"); - currentSpaceState = onlineSpaceState; - spaceStateDidChange(onlineSpaceState, !onlineSpaceState); - } - } else { - Serial.print("Unsupported response from space state"); - Serial.println(httpsClient.getString()); - } - doc.clear(); - } - httpsClient.end(); - client->stop(); - } -} - -void spaceStateDidChange(bool newState, bool oldState) { - currentSpaceState = newState; - Serial.print("Space state has changed to: '"); - Serial.print(stringForState(newState)); - Serial.print("', previous: '"); - Serial.print(stringForState(oldState)); - Serial.println("'"); - updateLEDs(); - publishStateTopic(newState); -} - -String stringForState(bool state) { - if (state) { - return "open"; - } else { - return "closed"; - } -} - -void updateLEDs() { - int ledState = currentSpaceState ? HIGH : LOW; - digitalWrite(BUILTIN_LED_PIN, ledState); - - uint32_t neopixelColor = neopixels.Color(255, 0, 0); // Red - - if (currentSpaceState) { - neopixelColor = neopixels.Color(0, 255, 0); // Green - } - if (WiFi.status() != WL_CONNECTED) { - neopixelColor = neopixels.Color(0, 0, 255); // Blue - } - - neopixels.fill(neopixelColor); - neopixels.setBrightness(80); - neopixels.show(); -} - -// -// MARK: - MQTT -// - -void connectMQTT() { - if (WiFi.status() != WL_CONNECTED) { - return; - } - if (mqttClient.connected()) { - return; - } - String mqttServerStr = String(mqttServer); - mqttServerStr.trim(); - if (mqttServerStr.isEmpty()) { - return; - } - long now = millis(); - if ((now - lastMQTTConnectTime) < MQTT_CONNECT_INTERVAL && lastMQTTConnectTime != 0) { - return; - } - int mqttPortInt = atoi(mqttPort); - if (mqttPortInt <= 0) { - mqttPortInt = 1883; - } - mqttClient.setServer(mqttServerStr.c_str(), mqttPortInt); - if (mqttClient.connect(hostname.c_str(), mqttUsername, mqttPassword, mqttLastWillTopic.c_str(), 0, true, "offline")) { - Serial.println("[MQTT]: Connected"); - mqttClient.publish(mqttLastWillTopic.c_str(), "online", true); - publishHADiscoveryTopic(); - publishStateTopic(currentSpaceState); - } else { - Serial.println("[MQTT]: Failed to connect"); - } - lastMQTTConnectTime = now; -} - -void publishHADiscoveryTopic() { - String topic = "homeassistant/binary_sensor/" + hostname + "/config"; - - DynamicJsonDocument payload(512); - payload["dev_cla"] = "opening"; - payload["stat_t"] = mqttStateTopic; - payload["pl_on"] = "1"; - payload["pl_off"] = "0"; - payload["uniq_id"] = hostname; - payload["name"] = "Space state"; - payload["avty_t"] = mqttLastWillTopic; - payload["exp_aft"] = 900; // Seconds after which the sensor is deemed unresponsive. - - JsonObject deviceObject = payload.createNestedObject("dev"); - deviceObject["name"] = "Space state switch"; - deviceObject["cu"] = String("http://") + WiFi.localIP().toString() + "/"; - deviceObject["mdl"] = "ESP32"; - deviceObject["mf"] = "renssies"; - - JsonArray ids = deviceObject.createNestedArray("ids"); - ids.add(WiFi.macAddress()); - - char payloadBuffer[512]; - serializeJson(payload, payloadBuffer); - - mqttClient.setBufferSize(512); // The discovery payload is rather big so we temporarily increase the max size. - if(!mqttClient.publish(topic.c_str(), payloadBuffer, true)) { - Serial.println("[MQTT]: Failed to publish HA discovery"); - } else { - Serial.println("[MQTT]: Published HA discovery"); - } - mqttClient.setBufferSize(MQTT_MAX_PACKET_SIZE); -} - -void publishStateTopic(bool state) { - if (!mqttClient.connected()) { - return; - } - if (!mqttClient.publish(mqttStateTopic.c_str(), String(state).c_str())) { - Serial.println("[MQTT]: Failed to publish state"); - } -} - -// -// MARK: - Callbacks -// - -void saveConfigCallback() { - Serial.println("Should save config"); - - strcpy(mqttServer, paramMQTTServer.getValue()); - strcpy(mqttPort, paramMQTTPort.getValue()); - strcpy(mqttUsername, paramMQTTUsername.getValue()); - strcpy(mqttPassword, paramMQTTPassword.getValue()); - - preferences.begin(PREFERENCES_NAMESPACE, false); - - preferences.putString(PREFERENCE_MQTT_SERVER_KEY, mqttServer); - preferences.putString(PREFERENCE_MQTT_PORT_KEY, mqttPort); - preferences.putString(PREFERENCE_MQTT_USERNAME_KEY, mqttUsername); - preferences.putString(PREFERENCE_MQTT_PASSWORD_KEY, mqttPassword); - - preferences.end(); - - mqttClient.disconnect(); - MDNS.end(); - - wifiManager.reboot(); -} - -void configModeTimeoutCallback() { - wifiManager.reboot(); -} diff --git a/src/SpaceStateSync.cpp b/src/SpaceStateSync.cpp new file mode 100644 index 0000000..99882c3 --- /dev/null +++ b/src/SpaceStateSync.cpp @@ -0,0 +1,162 @@ +#include "SpaceStateSync.h" + +#include +#include +#include +#include + +#include "Config.h" + +namespace { + +String urlEncode(const String &value) { + static const char *kHex = "0123456789ABCDEF"; + String out; + out.reserve(value.length() * 3); + for (size_t i = 0; i < value.length(); i++) { + const char c = value[i]; + if (isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || c == '~') { + out += c; + } else { + out += '%'; + out += kHex[(c >> 4) & 0xF]; + out += kHex[c & 0xF]; + } + } + return out; +} + +const char *stateName(bool open) { + return open ? "open" : "closed"; +} + +} // namespace + +void SpaceStateSync::begin(const String &username, const String &token, OverrideCallback onOverride) { + username_ = username; + token_ = token; + onOverride_ = onOverride; + if (username_.isEmpty() || token_.isEmpty()) { + Serial.println("[SpaceState] No credentials configured, changes won't be submitted"); + } + xTaskCreate(&SpaceStateSync::taskEntry, "SpaceStateSync", 8192, this, 1, &task_); +} + +void SpaceStateSync::submit(bool open) { + pending_ = open ? 1 : 0; + if (task_ != nullptr) { + xTaskNotifyGive(task_); + } +} + +void SpaceStateSync::taskEntry(void *self) { + static_cast(self)->run(); +} + +void SpaceStateSync::run() { + // Signed difference so the comparison survives millis() wrapping around. + auto msUntil = [](uint32_t deadline) { return static_cast(deadline - millis()); }; + uint32_t nextPollAt = millis(); // Fetch the online state straight away on boot. + + for (;;) { + uint32_t waitMs = config::kSpaceStatePollIntervalMs; + + if (!WiFi.isConnected()) { + waitMs = 1000; + } else { + int8_t pending = pending_.load(); + if (pending != kNothingPending) { + if (submitState(pending == 1)) { + // Only clear if no newer state was queued while submitting. + pending_.compare_exchange_strong(pending, kNothingPending); + } else { + waitMs = config::kSpaceStateRetryIntervalMs; + } + } + + if (pending_.load() == kNothingPending && msUntil(nextPollAt) <= 0) { + bool online; + if (fetchState(online)) { + nextPollAt = millis() + config::kSpaceStatePollIntervalMs; + // A submit may have been queued while fetching; the switch wins in that case. + if (pending_.load() == kNothingPending && onOverride_) { + onOverride_(online); + } + } else { + nextPollAt = millis() + config::kSpaceStateRetryIntervalMs; + } + } + + if (pending_.load() == kNothingPending) { + waitMs = std::min(waitMs, std::max(0, msUntil(nextPollAt))); + } + } + + // Sleep until the next poll/retry, or until submit() wakes us up. + ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(waitMs)); + } +} + +bool SpaceStateSync::submitState(bool open) { + if (username_.isEmpty() || token_.isEmpty()) { + return true; // Nothing we can do; don't retry forever. + } + + NetworkClientSecure client; + client.useBuiltinCACertBundle(); + + const String url = String(config::kToggleStateUrl) + "?user=" + urlEncode(username_) + "&token=" + urlEncode(token_) + + "&state=" + stateName(open); + + HTTPClient http; + http.setConnectTimeout(config::kHttpTimeoutMs); + http.setTimeout(config::kHttpTimeoutMs); + if (!http.begin(client, url)) { + Serial.println("[SpaceState] Invalid submit URL"); + return false; + } + // Don't log the URL, it contains the token. + Serial.printf("[SpaceState] Submitting '%s'\n", stateName(open)); + const int status = http.GET(); + http.end(); + + if (status <= 0) { + Serial.printf("[SpaceState] Submit failed: %s\n", HTTPClient::errorToString(status).c_str()); + return false; + } + Serial.printf("[SpaceState] Submit response: %d\n", status); + return status >= 200 && status < 400; +} + +bool SpaceStateSync::fetchState(bool &open) { + NetworkClientSecure client; + client.useBuiltinCACertBundle(); + + HTTPClient http; + http.setConnectTimeout(config::kHttpTimeoutMs); + http.setTimeout(config::kHttpTimeoutMs); + http.useHTTP10(true); // No chunked encoding, so we can parse straight from the stream + if (!http.begin(client, config::kSpaceStateUrl)) { + Serial.println("[SpaceState] Invalid state URL"); + return false; + } + + const int status = http.GET(); + if (status != HTTP_CODE_OK && status != HTTP_CODE_MOVED_PERMANENTLY) { + Serial.printf("[SpaceState] Fetch failed: %d %s\n", status, status < 0 ? HTTPClient::errorToString(status).c_str() : ""); + http.end(); + return false; + } + + JsonDocument doc; + const DeserializationError error = deserializeJson(doc, http.getStream()); + http.end(); + + const char *state = doc["state"]; + if (error || state == nullptr) { + Serial.println("[SpaceState] Unsupported response from space state API"); + return false; + } + open = strcmp(state, "open") == 0; + return true; +} diff --git a/src/SpaceStateSync.h b/src/SpaceStateSync.h new file mode 100644 index 0000000..f5c822b --- /dev/null +++ b/src/SpaceStateSync.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include + +// Keeps spacestate.pixelbar.nl in sync with the switch. +// +// A single background task submits switch changes and periodically fetches the +// online state, so the two never race. If the online state differs from ours +// (someone overrode it on the website) the override callback is invoked. +class SpaceStateSync { + public: + using OverrideCallback = void (*)(bool open); + + void begin(const String &username, const String &token, OverrideCallback onOverride); + + // Queues the given state for submission. Thread-safe; only the latest state is sent. + void submit(bool open); + + private: + static void taskEntry(void *self); + void run(); + bool submitState(bool open); + bool fetchState(bool &open); + + static constexpr int8_t kNothingPending = -1; + + String username_; + String token_; + OverrideCallback onOverride_ = nullptr; + TaskHandle_t task_ = nullptr; + std::atomic pending_{kNothingPending}; +}; diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..ecb1d60 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,320 @@ +// SpaceStateSwitch: reads the physical space state switch at Pixelbar and publishes +// it to spacestate.pixelbar.nl, MQTT (Home Assistant) and a small local JSON API. + +#include +#include +// WiFiManager pulls in the synchronous WebServer; it must come before +// ESPAsyncWebServer so the latter can reconcile the HTTP method enums. +#include +#include + +#include +#include +#include + +#include + +#include "Config.h" +#include "DoubleResetDetector.h" +#include "MqttPublisher.h" +#include "OtaUpdater.h" +#include "Settings.h" +#include "SpaceStateSync.h" + +// setup() runs the OTA update (TLS + signature verification); give it some headroom. +SET_LOOP_TASK_STACK_SIZE(16 * 1024); + +namespace { + +Settings settings; +DoubleResetDetector doubleReset(config::kDoubleResetWindowMs); +WiFiManager wifiManager; +MqttPublisher mqtt; +SpaceStateSync spaceStateSync; +AsyncWebServer webServer(80); +Adafruit_NeoPixel neopixels(config::kNumberOfPixels, config::kNeopixelPin, NEO_GRB + NEO_KHZ800); + +// Shared between the main loop, the sync task, the MQTT task and the web server. +std::atomic spaceOpen{false}; // The effective state (switch, or online override) +std::atomic switchOpen{false}; // The physical switch position +std::atomic ledsDirty{true}; +bool updating = false; + +uint32_t lastSwitchPollAt = 0; +uint32_t lastMqttPublishAt = 0; + +const char *stateName(bool open) { + return open ? "open" : "closed"; +} + +// MARK: - LEDs + +// Only call from the main task; other tasks set ledsDirty instead. +void renderLeds() { + ledsDirty = false; + const bool open = spaceOpen; + digitalWrite(config::kBuiltinLedPin, open ? HIGH : LOW); + + uint32_t color; + if (updating) { + color = Adafruit_NeoPixel::Color(128, 0, 255); // Purple: installing an update + } else if (!WiFi.isConnected()) { + color = Adafruit_NeoPixel::Color(0, 0, 255); // Blue: no WiFi + } else if (open) { + color = Adafruit_NeoPixel::Color(0, 255, 0); // Green: open + } else { + color = Adafruit_NeoPixel::Color(255, 0, 0); // Red: closed + } + neopixels.fill(color); + neopixels.show(); +} + +// MARK: - Space state + +bool readSwitch() { + return digitalRead(config::kSwitchPin) == LOW; +} + +void setSpaceState(bool open, const char *reason) { + const bool previous = spaceOpen.exchange(open); + if (previous == open) { + return; + } + Serial.printf("Space state changed to '%s' (%s)\n", stateName(open), reason); + ledsDirty = true; + mqtt.publishState(open); +} + +void pollSwitch() { + if (millis() - lastSwitchPollAt < config::kSwitchPollIntervalMs) { + return; + } + lastSwitchPollAt = millis(); + + const bool open = readSwitch(); + if (open == switchOpen) { + return; + } + switchOpen = open; + setSpaceState(open, "switch"); + spaceStateSync.submit(open); +} + +// Called from the sync task when the website reports a different state. +void onOnlineState(bool open) { + if (open != spaceOpen) { + setSpaceState(open, "overridden online"); + } +} + +// MARK: - WiFi + +void setupWiFi(bool forcePortal) { + // WiFiManagerParameter copies the default value. Secrets aren't pre-filled, so + // they can't be read back from the portal; leaving them empty keeps the stored value. + static WiFiManagerParameter mqttServer("mqtt_server", "MQTT server (leave blank to disable)", settings.mqttServer.c_str(), 64); + static WiFiManagerParameter mqttPort("mqtt_port", "MQTT port", String(settings.mqttPort).c_str(), 5, " type='number' min='1' max='65535'"); + static WiFiManagerParameter mqttUsername("mqtt_username", "MQTT username (blank if unauthenticated)", settings.mqttUsername.c_str(), 64, " autocapitalize='none'"); + static WiFiManagerParameter mqttPassword("mqtt_password", "MQTT password (blank keeps current)", "", 64, " type='password'"); + static WiFiManagerParameter spaceStateUsername("ss_username", "Space state API user", settings.spaceStateUsername.c_str(), 64, " autocapitalize='none'"); + static WiFiManagerParameter spaceStateToken("ss_token", "Space state API token (blank keeps current)", "", 128, " type='password'"); + + wifiManager.addParameter(&mqttServer); + wifiManager.addParameter(&mqttPort); + wifiManager.addParameter(&mqttUsername); + wifiManager.addParameter(&mqttPassword); + wifiManager.addParameter(&spaceStateUsername); + wifiManager.addParameter(&spaceStateToken); + + wifiManager.setSaveParamsCallback([]() { + settings.mqttServer = mqttServer.getValue(); + settings.mqttServer.trim(); + const long port = String(mqttPort.getValue()).toInt(); + settings.mqttPort = (port > 0 && port <= 65535) ? port : config::kMqttDefaultPort; + settings.mqttUsername = mqttUsername.getValue(); + if (strlen(mqttPassword.getValue()) > 0 || settings.mqttUsername.isEmpty()) { + settings.mqttPassword = mqttPassword.getValue(); + } + settings.spaceStateUsername = spaceStateUsername.getValue(); + if (strlen(spaceStateToken.getValue()) > 0) { + settings.spaceStateToken = spaceStateToken.getValue(); + } + settings.save(); + Serial.println("Settings saved"); + }); + // Restart after saving, so everything starts with the new configuration. + wifiManager.setSaveConfigCallback([]() { wifiManager.reboot(); }); + wifiManager.setConfigPortalTimeoutCallback([]() { wifiManager.reboot(); }); + wifiManager.setAPCallback([](WiFiManager *) { + doubleReset.stop(); // A reset while in the portal shouldn't count as a double reset. + Serial.printf("Config portal started: connect to '%s' with password '%s'\n", config::kConfigApSsid, config::kConfigApPassword); + }); + + wifiManager.setHostname(config::kHostname); + wifiManager.setConfigPortalTimeout(config::kConfigPortalTimeoutS); + wifiManager.setConfigPortalBlocking(true); + wifiManager.setBreakAfterConfig(true); + wifiManager.setWiFiAutoReconnect(true); + wifiManager.setDebugOutput(false); + + if (forcePortal) { + Serial.println("Double reset detected, starting config portal"); + wifiManager.startConfigPortal(config::kConfigApSsid, config::kConfigApPassword); + } + + // Blocks until connected; opens the portal (and eventually reboots) if that fails. + if (!wifiManager.autoConnect(config::kConfigApSsid, config::kConfigApPassword)) { + ESP.restart(); + } + Serial.printf("Connected: IP %s, MAC %s\n", WiFi.localIP().toString().c_str(), WiFi.macAddress().c_str()); +} + +void setupMdns() { + if (!MDNS.begin(config::kHostname)) { + Serial.println("Failed to start mDNS"); + return; + } + MDNS.addService("http", "tcp", 80); + MDNS.addServiceTxt("http", "tcp", "id", WiFi.macAddress().c_str()); + MDNS.addServiceTxt("http", "tcp", "ma", WiFi.macAddress().c_str()); + MDNS.addServiceTxt("http", "tcp", "hw", "esp32"); + MDNS.addServiceTxt("http", "tcp", "fw", FIRMWARE_VERSION); +} + +// MARK: - Web server + +void sendJson(AsyncWebServerRequest *request, const JsonDocument &doc) { + String body; + serializeJson(doc, body); + request->send(200, "application/json", body); +} + +void setupWebServer() { + webServer.onNotFound([](AsyncWebServerRequest *request) { + if (request->method() == AsyncWebRequestMethod::HTTP_OPTIONS) { + request->send(200); + } else { + request->send(404, "text/html", "Page Not FoundPage Not Found"); + } + }); + + webServer.on("/", AsyncWebRequestMethod::HTTP_GET, [](AsyncWebServerRequest *request) { + JsonDocument doc; + const bool open = spaceOpen; + const bool physical = switchOpen; + doc["is_open"] = open; + doc["state"] = stateName(open); + doc["is_overwritten"] = open != physical; + doc["physical_state"] = physical; + JsonArray endpoints = doc["endpoints"].to(); + endpoints.add("GET /heap"); + endpoints.add("GET /info"); + sendJson(request, doc); + }); + + webServer.on("/heap", AsyncWebRequestMethod::HTTP_GET, [](AsyncWebServerRequest *request) { + JsonDocument doc; + doc["uptime"] = millis(); + doc["heap"] = ESP.getFreeHeap(); + doc["min_heap"] = ESP.getMinFreeHeap(); + sendJson(request, doc); + }); + + webServer.on("/info", AsyncWebRequestMethod::HTTP_GET, [](AsyncWebServerRequest *request) { + JsonDocument doc; + doc["chip_id"] = WiFi.macAddress(); + doc["ip_address"] = WiFi.localIP().toString(); + doc["mac_address"] = WiFi.macAddress(); + doc["uptime"] = millis(); + doc["firmware_version"] = FIRMWARE_VERSION; + doc["change_wifi_instructions"] = "Double press the reset button to enter config mode."; + if (settings.hasMqtt()) { + doc["mqtt_server"] = settings.mqttServer; + doc["mqtt_connected"] = mqtt.isConnected(); + } else { + doc["mqtt_server"] = nullptr; + } + JsonObject about = doc["about"].to(); + about["original_by"] = "meepe"; + about["modified_by"] = "renssies"; + about["hardware"] = "Arduino on a ESP32 Wemos D1 Mini Alternative"; + about["repository"] = config::kRepositoryUrl; + sendJson(request, doc); + }); + + webServer.begin(); +} + +// MARK: - OTA + +void checkForUpdate() { + updating = true; + ota::checkAndUpdate([](size_t written, size_t total) { + static int lastPercent = -1; + const int percent = written * 100 / total; + if (percent / 10 != lastPercent / 10) { + Serial.printf("[OTA] %d%%\n", percent); + // Blink while downloading. + neopixels.setBrightness(percent / 10 % 2 ? config::kNeopixelBrightness / 4 : config::kNeopixelBrightness); + renderLeds(); + } + lastPercent = percent; + }); + // Only returns if no update was installed. + updating = false; + neopixels.setBrightness(config::kNeopixelBrightness); +} + +} // namespace + +void setup() { + Serial.begin(115200); + Serial.printf("\nSpaceStateSwitch %s\n", FIRMWARE_VERSION); + + pinMode(config::kSwitchPin, INPUT_PULLUP); + pinMode(config::kBuiltinLedPin, OUTPUT); + neopixels.begin(); + neopixels.setBrightness(config::kNeopixelBrightness); + + // Show the switch position straight away, even before WiFi is up. + switchOpen = readSwitch(); + spaceOpen = switchOpen.load(); + Serial.printf("Initial switch state: %s\n", stateName(switchOpen)); + renderLeds(); + + settings.load(); + setupWiFi(doubleReset.detect()); + renderLeds(); + + checkForUpdate(); + + // We got this far (connected to WiFi), so a freshly installed update works. + ota::markFirmwareValid(); + + setupMdns(); + setupWebServer(); + mqtt.begin(settings, []() -> bool { return spaceOpen; }); + spaceStateSync.begin(settings.spaceStateUsername, settings.spaceStateToken, onOnlineState); +} + +void loop() { + doubleReset.loop(); + pollSwitch(); + + static bool wasConnected = true; + if (WiFi.isConnected() != wasConnected) { + wasConnected = !wasConnected; + ledsDirty = true; + } + if (ledsDirty) { + renderLeds(); + } + + // Re-publish periodically so Home Assistant's expire_after doesn't kick in. + if (millis() - lastMqttPublishAt > config::kMqttRepublishIntervalMs) { + lastMqttPublishAt = millis(); + mqtt.publishState(spaceOpen); + } + + delay(10); +} From 9fd1e267b38f0cb0c0369985b2c44eac24656b7a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 08:47:58 +0000 Subject: [PATCH 2/5] Mark firmware valid before checking for OTA updates Move ota::markFirmwareValid() to run immediately after WiFi connects, before checkForUpdate(). This prevents the OTA check from causing a rollback if it fails, hangs, or crashes. The rollback decision should be based on whether the firmware successfully connected to WiFi, not on whether a subsequent GitHub API call succeeded. Co-authored-by: NinjaLikesCheez --- src/main.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ecb1d60..50d3f07 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -286,11 +286,13 @@ void setup() { setupWiFi(doubleReset.detect()); renderLeds(); - checkForUpdate(); - // We got this far (connected to WiFi), so a freshly installed update works. + // Mark it valid before checking for a new update, so the OTA check can't cause + // a rollback if it fails or crashes. ota::markFirmwareValid(); + checkForUpdate(); + setupMdns(); setupWebServer(); mqtt.begin(settings, []() -> bool { return spaceOpen; }); From 76cace9ac0eba96c5b83517bf960d94e8f326c2c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 7 Nov 2026 11:00:18 +0000 Subject: [PATCH 3/5] Set MQTT state message as retained Change the retain flag from 0 to 1 in publishState() so the state topic is retained as documented in the README. This ensures Home Assistant and other MQTT clients see the last state immediately on connection without waiting for the next periodic publish. Co-authored-by: NinjaLikesCheez --- src/MqttPublisher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MqttPublisher.cpp b/src/MqttPublisher.cpp index fe49eec..1cfea66 100644 --- a/src/MqttPublisher.cpp +++ b/src/MqttPublisher.cpp @@ -53,7 +53,7 @@ void MqttPublisher::publishState(bool open) { return; } // Non-blocking: queued in the client's outbox and sent by the MQTT task. - esp_mqtt_client_enqueue(client_, config::kMqttStateTopic, open ? kPayloadOpen : kPayloadClosed, 0, 0, 0, true); + esp_mqtt_client_enqueue(client_, config::kMqttStateTopic, open ? kPayloadOpen : kPayloadClosed, 0, 0, 1, true); } void MqttPublisher::onEvent(void *arg, const char *base, int32_t eventId, void *eventData) { From ca1576f50b8154945389cebc1c1955c601559500 Mon Sep 17 00:00:00 2001 From: NinjaLikesCheez Date: Thu, 12 Nov 2026 10:50:43 +0100 Subject: [PATCH 4/5] Fetch space state over HTTP/1.1 spacestate.pixelbar.nl now rejects HTTP/1.0 requests with 426 Upgrade Required, so every state fetch failed. Drop useHTTP10() and read the body with getString(), which handles chunked responses. Co-Authored-By: Claude Opus 5.5 --- src/SpaceStateSync.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/SpaceStateSync.cpp b/src/SpaceStateSync.cpp index 99882c3..ccc1095 100644 --- a/src/SpaceStateSync.cpp +++ b/src/SpaceStateSync.cpp @@ -135,7 +135,7 @@ bool SpaceStateSync::fetchState(bool &open) { HTTPClient http; http.setConnectTimeout(config::kHttpTimeoutMs); http.setTimeout(config::kHttpTimeoutMs); - http.useHTTP10(true); // No chunked encoding, so we can parse straight from the stream + // The server rejects HTTP/1.0 with 426 Upgrade Required, so stay on HTTP/1.1. if (!http.begin(client, config::kSpaceStateUrl)) { Serial.println("[SpaceState] Invalid state URL"); return false; @@ -149,7 +149,8 @@ bool SpaceStateSync::fetchState(bool &open) { } JsonDocument doc; - const DeserializationError error = deserializeJson(doc, http.getStream()); + // getString() decodes chunked transfer encoding; the response is tiny. + const DeserializationError error = deserializeJson(doc, http.getString()); http.end(); const char *state = doc["state"]; From bbdf0f9bb40653dbc4b655d218dbd09055ff745c Mon Sep 17 00:00:00 2001 From: NinjaLikesCheez Date: Thu, 12 Nov 2026 11:57:48 +0100 Subject: [PATCH 5/5] chore: add signing key, add dev open/closed keybindings --- README.md | 6 ++- keys/ota_signing_key.pub.pem | 4 ++ scripts/firmware_version.py | 4 ++ src/Config.h | 7 +++- src/Secrets_example.h | 14 +++---- src/Settings.cpp | 28 ++++++++----- src/Settings.h | 14 ++++--- src/SpaceStateSync.cpp | 81 +++++++++++++++++++----------------- src/SpaceStateSync.h | 6 +-- src/main.cpp | 62 +++++++++++++++++++++++---- 10 files changed, 149 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 9c68a54..8953407 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ Code created by DiverAlpha, referencing the old code of royvandongen. | Blue | Not connected to WiFi | | Purple (blinking) | Installing a firmware update | -- If the switch changes, the new state is sent to the space state website. Failed submissions are retried every 10 seconds. +- If the switch changes, the new state is sent to the [space state API](https://pixelbar.nl/spacestate/) (`POST /api/v1/state`). Network and server errors are retried every 10 seconds; a rejected API key is logged and not retried. - Every 10 minutes the online state is fetched. If someone changed the state on the website, that override is shown until the switch is flipped again. -- **Double press reset** to open the config portal. It runs as WiFi network `space-state-switch` with password `1337hacker` and closes after 2 minutes. In the portal you set the WiFi network, the MQTT broker and the space state API credentials. Password and token fields start empty; leave them empty to keep the stored value. +- **Double press reset** to open the config portal. It runs as WiFi network `space-state-switch` with password `1337hacker` and closes after 2 minutes. In the portal you set the WiFi network, the MQTT broker and the space state API key (an API key with the `write` role) and user. Password and API key fields start empty; leave them empty to keep the stored value. ### HTTP API @@ -49,6 +49,8 @@ The partition table changed to make room for two OTA slots, and partition tables Space state credentials are no longer compiled in. Enter them in the config portal, or put them in `src/Secrets.h` (see `src/Secrets_example.h`) for that first USB flash. They are then stored on the device. +The switch uses the new space state API with a Bearer API key, not the legacy `togglestate.php` token. A device that already has a legacy token stored still needs an API key with the `write` role: ask a spacestate maintainer for one and enter it in the config portal. The stored user is kept. + ## OTA updates On boot, after connecting to WiFi, the device: diff --git a/keys/ota_signing_key.pub.pem b/keys/ota_signing_key.pub.pem index e69de29..85a4a01 100644 --- a/keys/ota_signing_key.pub.pem +++ b/keys/ota_signing_key.pub.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE87f8oZKt9QiqJ2AkYkRsnobvhwgy +7NmuewOB2OLLFRRhiCG4MPFWtvIbVZDNXcGxWWSuWv0Zfb6yNW2eEj/wAA== +-----END PUBLIC KEY----- diff --git a/scripts/firmware_version.py b/scripts/firmware_version.py index 3462a9a..0a1b652 100644 --- a/scripts/firmware_version.py +++ b/scripts/firmware_version.py @@ -14,3 +14,7 @@ print(f"Firmware version: {version}") env.Append(CPPDEFINES=[("FIRMWARE_VERSION", env.StringifyMacro(version))]) # noqa: F821 + +# Development-only features (e.g. serial commands that simulate the switch). +if version == "dev": + env.Append(CPPDEFINES=["DEV_BUILD"]) # noqa: F821 diff --git a/src/Config.h b/src/Config.h index a9f8ffb..4b2c5b1 100644 --- a/src/Config.h +++ b/src/Config.h @@ -48,8 +48,11 @@ constexpr const char *kPreferencesNamespace = "space-state"; // MARK: - Space state API -constexpr const char *kSpaceStateUrl = "https://spacestate.pixelbar.nl/spacestate.php"; -constexpr const char *kToggleStateUrl = "https://spacestate.pixelbar.nl/togglestate.php"; +// GET returns the current state; POST (with a `write` API key) changes it. +// See https://pixelbar.nl/spacestate/ +constexpr const char *kSpaceStateApiUrl = "https://spacestate.pixelbar.nl/api/v1/state"; +// Reported to the API as the `method` of a state change. +constexpr const char *kSpaceStateMethod = "button"; // MARK: - MQTT diff --git a/src/Secrets_example.h b/src/Secrets_example.h index f5c6274..ca2652d 100644 --- a/src/Secrets_example.h +++ b/src/Secrets_example.h @@ -1,17 +1,17 @@ #ifndef PB_SECRETS #define PB_SECRETS 1 -// OPTIONAL. Copy to Secrets.h (git-ignored) to seed the space state credentials -// on a device that doesn't have them stored yet. On first boot they are copied +// OPTIONAL. Copy to Secrets.h (git-ignored) to seed the space state API key +// on a device that doesn't have one stored yet. On first boot it is copied // into NVS, so later OTA updates (which never contain Secrets.h) keep working. // -// The credentials can also be set in the WiFi config portal instead. +// Both can also be set in the WiFi config portal instead. // Never add Secrets.h to a release build: release binaries are public. -// The username used for the request of setting the current space state. -#define SPACESTATE_REQUEST_USERNAME "user" +// API key with the `write` role for https://spacestate.pixelbar.nl/api/v1/state. +#define SPACESTATE_API_KEY "key" -// The authentication token used for the request of setting the current space state. -#define SPACESTATE_REQUEST_TOKEN "token" +// Optional: recorded as the `user` of state changes (defaults to the hostname). +#define SPACESTATE_USER "space-state-switch" #endif diff --git a/src/Settings.cpp b/src/Settings.cpp index bf59c70..b241abe 100644 --- a/src/Settings.cpp +++ b/src/Settings.cpp @@ -15,8 +15,10 @@ constexpr const char *kKeyMqttServer = "mqtt_server"; constexpr const char *kKeyMqttPort = "mqtt_port"; constexpr const char *kKeyMqttUsername = "mqtt_username"; constexpr const char *kKeyMqttPassword = "mqtt_password"; -constexpr const char *kKeySpaceStateUsername = "ss_username"; -constexpr const char *kKeySpaceStateToken = "ss_token"; +// The user is shared with the old legacy-API firmware. The API key gets its own key: +// the legacy token stored under "ss_token" is not a valid API key. +constexpr const char *kKeySpaceStateUser = "ss_username"; +constexpr const char *kKeySpaceStateApiKey = "ss_api_key"; } // namespace void Settings::load() { @@ -36,15 +38,19 @@ void Settings::load() { } mqttUsername = prefs.getString(kKeyMqttUsername, ""); mqttPassword = prefs.getString(kKeyMqttPassword, ""); - spaceStateUsername = prefs.getString(kKeySpaceStateUsername, ""); - spaceStateToken = prefs.getString(kKeySpaceStateToken, ""); + spaceStateUser = prefs.getString(kKeySpaceStateUser, ""); + spaceStateApiKey = prefs.getString(kKeySpaceStateApiKey, ""); prefs.end(); -#if defined(SPACESTATE_REQUEST_USERNAME) && defined(SPACESTATE_REQUEST_TOKEN) - if (!hasSpaceStateCredentials()) { - Serial.println("[Settings] Migrating space state credentials from Secrets.h to NVS"); - spaceStateUsername = SPACESTATE_REQUEST_USERNAME; - spaceStateToken = SPACESTATE_REQUEST_TOKEN; +#ifdef SPACESTATE_API_KEY + if (!hasSpaceStateApiKey()) { + Serial.println("[Settings] Migrating space state API key from Secrets.h to NVS"); + spaceStateApiKey = SPACESTATE_API_KEY; +#ifdef SPACESTATE_USER + if (spaceStateUser.isEmpty()) { + spaceStateUser = SPACESTATE_USER; + } +#endif save(); } #endif @@ -60,7 +66,7 @@ void Settings::save() const { prefs.putString(kKeyMqttPort, String(mqttPort)); prefs.putString(kKeyMqttUsername, mqttUsername); prefs.putString(kKeyMqttPassword, mqttPassword); - prefs.putString(kKeySpaceStateUsername, spaceStateUsername); - prefs.putString(kKeySpaceStateToken, spaceStateToken); + prefs.putString(kKeySpaceStateUser, spaceStateUser); + prefs.putString(kKeySpaceStateApiKey, spaceStateApiKey); prefs.end(); } diff --git a/src/Settings.h b/src/Settings.h index 4c590aa..cd558ff 100644 --- a/src/Settings.h +++ b/src/Settings.h @@ -13,11 +13,13 @@ struct Settings { String mqttUsername; String mqttPassword; - String spaceStateUsername; - String spaceStateToken; + // Recorded as the `user` of state changes. Defaults to the hostname when empty. + String spaceStateUser; + // Bearer key with the `write` role for the space state API. + String spaceStateApiKey; - // Loads the settings from NVS. If no space state credentials are stored yet and - // an (optional, git-ignored) src/Secrets.h is present, those are used and persisted + // Loads the settings from NVS. If no space state API key is stored yet and an + // (optional, git-ignored) src/Secrets.h is present, that is used and persisted // so that later OTA builds, which never contain Secrets.h, keep working. void load(); void save() const; @@ -25,7 +27,7 @@ struct Settings { bool hasMqtt() const { return !mqttServer.isEmpty(); } - bool hasSpaceStateCredentials() const { - return !spaceStateUsername.isEmpty() && !spaceStateToken.isEmpty(); + bool hasSpaceStateApiKey() const { + return !spaceStateApiKey.isEmpty(); } }; diff --git a/src/SpaceStateSync.cpp b/src/SpaceStateSync.cpp index ccc1095..eeb605f 100644 --- a/src/SpaceStateSync.cpp +++ b/src/SpaceStateSync.cpp @@ -9,35 +9,18 @@ namespace { -String urlEncode(const String &value) { - static const char *kHex = "0123456789ABCDEF"; - String out; - out.reserve(value.length() * 3); - for (size_t i = 0; i < value.length(); i++) { - const char c = value[i]; - if (isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || c == '~') { - out += c; - } else { - out += '%'; - out += kHex[(c >> 4) & 0xF]; - out += kHex[c & 0xF]; - } - } - return out; -} - const char *stateName(bool open) { return open ? "open" : "closed"; } } // namespace -void SpaceStateSync::begin(const String &username, const String &token, OverrideCallback onOverride) { - username_ = username; - token_ = token; +void SpaceStateSync::begin(const String &user, const String &apiKey, OverrideCallback onOverride) { + user_ = user.isEmpty() ? String(config::kHostname) : user; + apiKey_ = apiKey; onOverride_ = onOverride; - if (username_.isEmpty() || token_.isEmpty()) { - Serial.println("[SpaceState] No credentials configured, changes won't be submitted"); + if (apiKey_.isEmpty()) { + Serial.println("[SpaceState] No API key configured, changes won't be submitted"); } xTaskCreate(&SpaceStateSync::taskEntry, "SpaceStateSync", 8192, this, 1, &task_); } @@ -98,34 +81,57 @@ void SpaceStateSync::run() { } bool SpaceStateSync::submitState(bool open) { - if (username_.isEmpty() || token_.isEmpty()) { + if (apiKey_.isEmpty()) { return true; // Nothing we can do; don't retry forever. } + JsonDocument body; + body["state"] = stateName(open); + body["user"] = user_; + body["method"] = config::kSpaceStateMethod; + String payload; + serializeJson(body, payload); + NetworkClientSecure client; client.useBuiltinCACertBundle(); - const String url = String(config::kToggleStateUrl) + "?user=" + urlEncode(username_) + "&token=" + urlEncode(token_) + - "&state=" + stateName(open); - HTTPClient http; http.setConnectTimeout(config::kHttpTimeoutMs); http.setTimeout(config::kHttpTimeoutMs); - if (!http.begin(client, url)) { - Serial.println("[SpaceState] Invalid submit URL"); + if (!http.begin(client, config::kSpaceStateApiUrl)) { + Serial.println("[SpaceState] Invalid state URL"); return false; } - // Don't log the URL, it contains the token. + http.addHeader("Authorization", "Bearer " + apiKey_); + http.addHeader("Content-Type", "application/json"); + Serial.printf("[SpaceState] Submitting '%s'\n", stateName(open)); - const int status = http.GET(); + const int status = http.POST(payload); + const String response = status > 0 ? http.getString() : String(); http.end(); - if (status <= 0) { - Serial.printf("[SpaceState] Submit failed: %s\n", HTTPClient::errorToString(status).c_str()); - return false; + switch (status) { + case HTTP_CODE_OK: + Serial.println("[SpaceState] State changed"); + return true; + case HTTP_CODE_CONFLICT: // The space was already in this state; nothing to do. + Serial.println("[SpaceState] Already in that state"); + return true; + case HTTP_CODE_UNAUTHORIZED: + // Retrying won't help until the key is changed in the config portal. + Serial.println("[SpaceState] Submit rejected: API key missing, invalid or not 'write'"); + return true; + case HTTP_CODE_BAD_REQUEST: + Serial.printf("[SpaceState] Submit rejected as invalid: %s\n", response.c_str()); + return true; + default: + if (status <= 0) { + Serial.printf("[SpaceState] Submit failed: %s\n", HTTPClient::errorToString(status).c_str()); + } else { + Serial.printf("[SpaceState] Submit failed: %d %s\n", status, response.c_str()); + } + return false; // Network or server error: retry. } - Serial.printf("[SpaceState] Submit response: %d\n", status); - return status >= 200 && status < 400; } bool SpaceStateSync::fetchState(bool &open) { @@ -135,14 +141,13 @@ bool SpaceStateSync::fetchState(bool &open) { HTTPClient http; http.setConnectTimeout(config::kHttpTimeoutMs); http.setTimeout(config::kHttpTimeoutMs); - // The server rejects HTTP/1.0 with 426 Upgrade Required, so stay on HTTP/1.1. - if (!http.begin(client, config::kSpaceStateUrl)) { + if (!http.begin(client, config::kSpaceStateApiUrl)) { Serial.println("[SpaceState] Invalid state URL"); return false; } const int status = http.GET(); - if (status != HTTP_CODE_OK && status != HTTP_CODE_MOVED_PERMANENTLY) { + if (status != HTTP_CODE_OK) { Serial.printf("[SpaceState] Fetch failed: %d %s\n", status, status < 0 ? HTTPClient::errorToString(status).c_str() : ""); http.end(); return false; diff --git a/src/SpaceStateSync.h b/src/SpaceStateSync.h index f5c822b..7df2a0c 100644 --- a/src/SpaceStateSync.h +++ b/src/SpaceStateSync.h @@ -13,7 +13,7 @@ class SpaceStateSync { public: using OverrideCallback = void (*)(bool open); - void begin(const String &username, const String &token, OverrideCallback onOverride); + void begin(const String &user, const String &apiKey, OverrideCallback onOverride); // Queues the given state for submission. Thread-safe; only the latest state is sent. void submit(bool open); @@ -26,8 +26,8 @@ class SpaceStateSync { static constexpr int8_t kNothingPending = -1; - String username_; - String token_; + String user_; + String apiKey_; OverrideCallback onOverride_ = nullptr; TaskHandle_t task_ = nullptr; std::atomic pending_{kNothingPending}; diff --git a/src/main.cpp b/src/main.cpp index 50d3f07..f2f5e90 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -71,7 +71,17 @@ void renderLeds() { // MARK: - Space state +#ifdef DEV_BUILD +// Set from the serial console to simulate the switch: -1 = use the physical switch. +int8_t simulatedSwitch = -1; +#endif + bool readSwitch() { +#ifdef DEV_BUILD + if (simulatedSwitch >= 0) { + return simulatedSwitch == 1; + } +#endif return digitalRead(config::kSwitchPin) == LOW; } @@ -100,6 +110,34 @@ void pollSwitch() { spaceStateSync.submit(open); } +#ifdef DEV_BUILD +// Development builds only: simulate the switch from the serial monitor. +// o = open, c = closed, p = back to the physical switch +// The simulated position goes through pollSwitch() exactly like a real one, +// so it is also submitted to the space state API and MQTT. +void pollSerialCommands() { + while (Serial.available() > 0) { + switch (Serial.read()) { + case 'o': + simulatedSwitch = 1; + Serial.println("[Dev] Simulating switch: open"); + break; + case 'c': + simulatedSwitch = 0; + Serial.println("[Dev] Simulating switch: closed"); + break; + case 'p': + simulatedSwitch = -1; + Serial.println("[Dev] Using the physical switch"); + break; + default: + continue; + } + lastSwitchPollAt = millis() - config::kSwitchPollIntervalMs; // Apply on this loop + } +} +#endif + // Called from the sync task when the website reports a different state. void onOnlineState(bool open) { if (open != spaceOpen) { @@ -116,15 +154,15 @@ void setupWiFi(bool forcePortal) { static WiFiManagerParameter mqttPort("mqtt_port", "MQTT port", String(settings.mqttPort).c_str(), 5, " type='number' min='1' max='65535'"); static WiFiManagerParameter mqttUsername("mqtt_username", "MQTT username (blank if unauthenticated)", settings.mqttUsername.c_str(), 64, " autocapitalize='none'"); static WiFiManagerParameter mqttPassword("mqtt_password", "MQTT password (blank keeps current)", "", 64, " type='password'"); - static WiFiManagerParameter spaceStateUsername("ss_username", "Space state API user", settings.spaceStateUsername.c_str(), 64, " autocapitalize='none'"); - static WiFiManagerParameter spaceStateToken("ss_token", "Space state API token (blank keeps current)", "", 128, " type='password'"); + static WiFiManagerParameter spaceStateUser("ss_user", "Space state user (blank uses the hostname)", settings.spaceStateUser.c_str(), 64, " autocapitalize='none'"); + static WiFiManagerParameter spaceStateApiKey("ss_api_key", "Space state API key (blank keeps current)", "", 128, " type='password'"); wifiManager.addParameter(&mqttServer); wifiManager.addParameter(&mqttPort); wifiManager.addParameter(&mqttUsername); wifiManager.addParameter(&mqttPassword); - wifiManager.addParameter(&spaceStateUsername); - wifiManager.addParameter(&spaceStateToken); + wifiManager.addParameter(&spaceStateUser); + wifiManager.addParameter(&spaceStateApiKey); wifiManager.setSaveParamsCallback([]() { settings.mqttServer = mqttServer.getValue(); @@ -135,9 +173,11 @@ void setupWiFi(bool forcePortal) { if (strlen(mqttPassword.getValue()) > 0 || settings.mqttUsername.isEmpty()) { settings.mqttPassword = mqttPassword.getValue(); } - settings.spaceStateUsername = spaceStateUsername.getValue(); - if (strlen(spaceStateToken.getValue()) > 0) { - settings.spaceStateToken = spaceStateToken.getValue(); + settings.spaceStateUser = spaceStateUser.getValue(); + settings.spaceStateUser.trim(); + if (strlen(spaceStateApiKey.getValue()) > 0) { + settings.spaceStateApiKey = spaceStateApiKey.getValue(); + settings.spaceStateApiKey.trim(); } settings.save(); Serial.println("Settings saved"); @@ -270,6 +310,9 @@ void checkForUpdate() { void setup() { Serial.begin(115200); Serial.printf("\nSpaceStateSwitch %s\n", FIRMWARE_VERSION); +#ifdef DEV_BUILD + Serial.println("[Dev] Serial commands: o = open, c = closed, p = physical switch"); +#endif pinMode(config::kSwitchPin, INPUT_PULLUP); pinMode(config::kBuiltinLedPin, OUTPUT); @@ -296,11 +339,14 @@ void setup() { setupMdns(); setupWebServer(); mqtt.begin(settings, []() -> bool { return spaceOpen; }); - spaceStateSync.begin(settings.spaceStateUsername, settings.spaceStateToken, onOnlineState); + spaceStateSync.begin(settings.spaceStateUser, settings.spaceStateApiKey, onOnlineState); } void loop() { doubleReset.loop(); +#ifdef DEV_BUILD + pollSerialCommands(); +#endif pollSwitch(); static bool wasConnected = true;