From c08e232339cce8e13eab6e1426621e0623abdf9d Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Thu, 22 Oct 2026 12:08:20 +0200 Subject: [PATCH] =?UTF-8?q?feat(firmware):=20relay-proxy=20PoC=20=E2=80=94?= =?UTF-8?q?=20NodeMCU=20as=20a=20Dingtian=20DT-R004=20+=20cloud=20proxy/wa?= =?UTF-8?q?tchdog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A NodeMCU v3 (ESP8266) that speaks the Dingtian wire contract (binary UDP 60000 with relay_pw, string UDP 60001, config CGI incl. the setconfig gotcha, userset.cgi, Digest input push) so the booth's existing driver needs no change, plus a heartbeat/command/ watchdog path to an ephemeral cloud stand-in (poc/cloud-standin.mjs). Verified at park-lab: the booth's assign flow configured it like real hardware and a button press reached the booth (401→Digest→200) and the cloud with the booth's status. Watchdog probes /health and power-cycles the PC via a spare relay with backoff. IO behind one interface for the ESP32/ Dingtian port. wiki: relay-proxy-firmware page; esp32-flashability-test runbook (esptool lock test); dingtian-relay "can we flash our own firmware" (vendor locks the standard SKU); site-device-installation: booth ufw must allow device-net → 3000 (push targets PORT, not Caddy's 80); open-questions: cloud takeover vs signed ledger (parked). .gitignore: firmware venv/.pio/secrets.h. --- .gitignore | 5 + firmware/relay-proxy/README.md | 71 +++ firmware/relay-proxy/include/config_store.h | 20 + firmware/relay-proxy/include/digest.h | 7 + firmware/relay-proxy/include/io.h | 20 + .../relay-proxy/include/secrets.h.example | 12 + firmware/relay-proxy/platformio.ini | 16 + firmware/relay-proxy/poc/cloud-standin.mjs | 80 +++ firmware/relay-proxy/src/config_store.cpp | 90 ++++ firmware/relay-proxy/src/digest.cpp | 62 +++ firmware/relay-proxy/src/io_nodemcu.cpp | 50 ++ firmware/relay-proxy/src/main.cpp | 469 ++++++++++++++++++ wiki/concepts/esp32-flashability-test.md | 101 ++++ wiki/concepts/site-device-installation.md | 15 + wiki/decisions/open-questions.md | 9 + wiki/entities/dingtian-relay.md | 29 +- wiki/entities/relay-proxy-firmware.md | 73 +++ wiki/index.md | 2 + wiki/log.md | 32 ++ 19 files changed, 1162 insertions(+), 1 deletion(-) create mode 100644 firmware/relay-proxy/README.md create mode 100644 firmware/relay-proxy/include/config_store.h create mode 100644 firmware/relay-proxy/include/digest.h create mode 100644 firmware/relay-proxy/include/io.h create mode 100644 firmware/relay-proxy/include/secrets.h.example create mode 100644 firmware/relay-proxy/platformio.ini create mode 100644 firmware/relay-proxy/poc/cloud-standin.mjs create mode 100644 firmware/relay-proxy/src/config_store.cpp create mode 100644 firmware/relay-proxy/src/digest.cpp create mode 100644 firmware/relay-proxy/src/io_nodemcu.cpp create mode 100644 firmware/relay-proxy/src/main.cpp create mode 100644 wiki/concepts/esp32-flashability-test.md create mode 100644 wiki/entities/relay-proxy-firmware.md diff --git a/.gitignore b/.gitignore index 1235b14..5eac291 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,8 @@ progress.md # local scratch (site snapshots pulled for incident review, never committed) tmp/ + +# Firmware PoC (firmware/relay-proxy/README.md): toolchain venv, build output, Wi-Fi secrets +firmware/.venv/ +firmware/**/.pio/ +firmware/**/include/secrets.h diff --git a/firmware/relay-proxy/README.md b/firmware/relay-proxy/README.md new file mode 100644 index 0000000..5970cb5 --- /dev/null +++ b/firmware/relay-proxy/README.md @@ -0,0 +1,71 @@ +# relay-proxy — Dingtian emulator + cloud proxy/watchdog (PoC) + +A NodeMCU v3 (ESP8266) that **is a Dingtian DT-R004 to the booth server** and, on top, a +**proxy and watchdog toward a cloud service**. The booth's existing `dingtian` driver talks to +it unchanged. It is the seed of the custom firmware for the real Dingtian board (ESP32); the IO +layer is the only board-specific file. + +Why: park-2's booth PC died twice unnoticed. The device that already owns the barrier relay and +the button inputs becomes the resilient core: it reports to the cloud independently of the PC, +can power-cycle the PC, and keeps accepting commands from the cloud when the PC is dead. +See `wiki/entities/dingtian-relay.md` and `wiki/decisions/cloud-service-saas.md`. + +## What it emulates (the booth sees a DT-R004) + +| Surface | Behaviour | +| --- | --- | +| UDP 60000 binary | `FF AA s cmd pwLo pwHi …`: `00` status, `01` write (mask,set), `03` jog. Reply `FF AA s cmd relayByte inputByte`. Wrong `relay_pw` → dropped silently. | +| UDP 60001 string | `00`, `1N`, `2N`, `1N*`. Password-less. Enabled at factory; `harden()` turns it off (`udp2.p=255`). | +| `GET /api/v2/config.cgi` | The config JSON (relay_connect, input_link_relay, input_link_url). | +| `POST /api/v2/config_set.cgi` | Applies + persists (LittleFS). Requires `"command":"setconfig"` like the real device. | +| `GET /userset.cgi?u&old&u&new&` | Web-login rotation, `&0&` ok / `&2&` wrong old password. | +| Input push | On input change, Digest-authenticated GET to the booth's `on_path`/`off_path`. | +| `input_link_relay` | Factory ON (input auto-fires its relay) until the booth's precondition fix clears it. | + +Extra, PoC-only: `GET /` status text, `POST /poc/factory_reset`. + +## Proxy / watchdog (toward `CLOUD_URL`) + +- Heartbeat every 10 s: IP, booth health, relay/input state, config flags. +- Every input change is mirrored to the cloud (`/event`) with the booth push result. +- Command poll every 2 s: `{"pulse":ch,"ms":500}`, `{"watchdog":false}`, `{"reboot_pc":true}`. +- Watchdog: probes `BOOTH_HEALTH_URL` every 5 s; after 6 failures in a row it pulses relay 2 + for 3 s (meant for an NC contact in series with the PC's mains, with BIOS AC Recovery = On), + then backs off 10 min. The cloud can disable it. + +## Pins (NodeMCU v3) — no wiring needed to start + +| Function | Pin | +| --- | --- | +| Relay 1 (barrier) | D1 / GPIO5, mirrored on the on-board LED | +| Relay 2 (PC power) | D2 / GPIO4 | +| Relay 3, 4 | D5 / GPIO14, D6 / GPIO12 | +| Input 1 (button) | the on-board **FLASH** button (GPIO0), active LOW | +| Input 2 | D7 / GPIO13, short to GND | + +## Build / flash + +``` +cd firmware/relay-proxy +copy include\secrets.h.example include\secrets.h # fill in; gitignored +..\.venv\Scripts\pio run -t upload +..\.venv\Scripts\pio device monitor +``` + +Cloud stand-in (throwaway): `node poc/cloud-standin.mjs` on a host the device can reach. + +## Register it in the booth + +Devices → add **Dingtian relay controller**: host = the NodeMCU's IP (give it a DHCP +reservation or set `STATIC_IP`; the booth only accepts pushes from the registered IP), +channels 4, binary port 60000, string port 60001, HTTP port 80. On save the booth runs the +normal flow: precondition fix (clears `input_link_relay`), `harden()` (random `relay_pw`, +disables udp2, rotates the web login), and `configureInputPush()` (Digest creds + URLs). +The serial log shows each step land. + +## Limits of the PoC + +- Wi-Fi only; the real target has Ethernet. +- HTTP calls block the loop briefly (~100 ms); fine for a demo, not for production. +- The config JSON mirrors the keys the booth driver uses, not the full device schema. +- Plain HTTP to the cloud stand-in; the real cloud link needs TLS. diff --git a/firmware/relay-proxy/include/config_store.h b/firmware/relay-proxy/include/config_store.h new file mode 100644 index 0000000..12a8c1e --- /dev/null +++ b/firmware/relay-proxy/include/config_store.h @@ -0,0 +1,20 @@ +#pragma once +#include + +// The Dingtian-shaped config served by /api/v2/config.cgi, persisted to LittleFS. +// Holds exactly the keys the booth driver reads/writes (relay_connect, input_link_relay, +// input_link_url) — a faithful-enough subset, not a byte copy of the real device. +class ConfigStore { +public: + JsonDocument cfg; + String webUser, webPass; // web-UI login (userset.cgi), kept out of config.cgi + + void begin(); + bool save(); + bool saveWeb(); + void makeDefaults(); + + uint16_t relayPw() const; + bool stringProtoEnabled() const; // udp2.p != 255 + bool linkRelayEnabled() const; // input_link_relay flag (factory: on) +}; diff --git a/firmware/relay-proxy/include/digest.h b/firmware/relay-proxy/include/digest.h new file mode 100644 index 0000000..3fd6d55 --- /dev/null +++ b/firmware/relay-proxy/include/digest.h @@ -0,0 +1,7 @@ +#pragma once +#include + +// HTTP GET with RFC 2617 Digest (MD5, qop=auth) — what the booth's push route +// requires. First GET takes the 401 challenge, second carries the response. +// With an empty user it is a plain GET. Returns the final HTTP status (<0 = no connection). +int digestGet(const String& host, uint16_t port, const String& path, const String& user, const String& pass); diff --git a/firmware/relay-proxy/include/io.h b/firmware/relay-proxy/include/io.h new file mode 100644 index 0000000..7b9860b --- /dev/null +++ b/firmware/relay-proxy/include/io.h @@ -0,0 +1,20 @@ +#pragma once +#include + +constexpr int CHANNELS = 4; + +// Relay/input IO behind one tiny interface. Business code never touches pins, so +// porting to the real Dingtian board (74HC595 relays / 74HC165 inputs) swaps only +// the Io implementation file. +class Io { +public: + void begin(); + void setRelay(int ch, bool on); // 1-based + bool relay(int ch) const; // 1-based + bool inputHigh(int ch); // raw line level, 1-based + uint8_t relayMask() const; // bit0 = relay 1 + uint8_t inputMask(); // bit0 = input 1, bit set = line HIGH + +private: + bool relays_[CHANNELS] = {}; +}; diff --git a/firmware/relay-proxy/include/secrets.h.example b/firmware/relay-proxy/include/secrets.h.example new file mode 100644 index 0000000..19872b4 --- /dev/null +++ b/firmware/relay-proxy/include/secrets.h.example @@ -0,0 +1,12 @@ +// Copy to include/secrets.h (gitignored) and fill in. +#pragma once +#define WIFI_SSID "your-ssid" +#define WIFI_PASS "your-password" +// Ephemeral cloud stand-in (poc/cloud-standin.mjs), plain HTTP for the PoC. +#define CLOUD_URL "http://10.0.10.203:9099" +// Booth server health endpoint the watchdog probes. +#define BOOTH_HEALTH_URL "http://10.0.10.198/health" +// Optional fixed address (the booth only accepts pushes from the registered host IP). +// #define STATIC_IP "10.0.10.240" +// #define STATIC_GW "10.0.10.1" +// #define STATIC_MASK "255.255.255.0" diff --git a/firmware/relay-proxy/platformio.ini b/firmware/relay-proxy/platformio.ini new file mode 100644 index 0000000..210fc42 --- /dev/null +++ b/firmware/relay-proxy/platformio.ini @@ -0,0 +1,16 @@ +; relay-proxy — Dingtian DT-R004 emulator + cloud proxy/watchdog PoC. +; NodeMCU v3 (ESP8266) now; an esp32 env is the port target for the real Dingtian board. +[platformio] +default_envs = nodemcuv2 + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +board_build.filesystem = littlefs +monitor_speed = 115200 +upload_speed = 460800 +upload_port = COM35 +monitor_port = COM35 +lib_deps = bblanchon/ArduinoJson@^7.3.0 +build_flags = -Wall diff --git a/firmware/relay-proxy/poc/cloud-standin.mjs b/firmware/relay-proxy/poc/cloud-standin.mjs new file mode 100644 index 0000000..32cd0ab --- /dev/null +++ b/firmware/relay-proxy/poc/cloud-standin.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +// EPHEMERAL cloud stand-in for the relay-proxy PoC. Not a product component. +// Logs heartbeats/events from the device and lets you queue commands with curl. +// +// node poc/cloud-standin.mjs (listens on 0.0.0.0:9099) +// curl http://localhost:9099/ -> last heartbeat per device +// curl -X POST http://localhost:9099/fire/1 -> pulse relay 1 (500 ms) +// curl -X POST "http://localhost:9099/fire/1?ms=1000" +// curl -X POST http://localhost:9099/watchdog/off -> disable the PC watchdog +// curl -X POST http://localhost:9099/reboot-pc -> power-cycle the PC relay +import { createServer } from "node:http"; + +const PORT = Number(process.env.PORT ?? 9099); +const last = new Map(); // dev -> last heartbeat +const queue = []; // commands, oldest first (dev field optional) +const stamp = () => new Date().toISOString().slice(11, 19); + +function body(req) { + return new Promise((res) => { + let s = ""; + req.on("data", (c) => (s += c)); + req.on("end", () => { + try { res(s ? JSON.parse(s) : {}); } catch { res({ raw: s }); } + }); + }); +} + +const json = (res, code, obj) => { + res.writeHead(code, { "content-type": "application/json" }); + res.end(JSON.stringify(obj)); +}; + +createServer(async (req, res) => { + const url = new URL(req.url, "http://x"); + const p = url.pathname; + + if (req.method === "POST" && p === "/heartbeat") { + const hb = await body(req); + const prev = last.get(hb.dev); + last.set(hb.dev, { ...hb, at: new Date().toISOString() }); + const flip = prev && prev.booth_ok !== hb.booth_ok ? ` <-- booth ${hb.booth_ok ? "RECOVERED" : "DOWN"}` : ""; + console.log(`${stamp()} hb ${hb.dev} ip=${hb.ip} booth=${hb.booth_ok ? "up" : "DOWN"}(${hb.booth_code}) fails=${hb.booth_fails} wd=${hb.watchdog} resets=${hb.pc_resets} relays=${hb.relays} inputs=${hb.inputs} pw=${hb.relay_pw_set} push=${hb.push_en} link=${hb.link_relay} udp2=${hb.string_proto} heap=${hb.heap}${flip}`); + return json(res, 200, { ok: true }); + } + if (req.method === "POST" && p === "/event") { + const ev = await body(req); + console.log(`${stamp()} EVENT ${ev.dev} ${ev.type} input=${ev.input} active=${ev.active} booth_status=${ev.booth_status}`); + return json(res, 200, { ok: true }); + } + if (req.method === "GET" && p === "/command") { + const dev = url.searchParams.get("dev"); + const i = queue.findIndex((c) => !c.dev || c.dev === dev); + if (i < 0) return json(res, 200, {}); + const [cmd] = queue.splice(i, 1); + console.log(`${stamp()} -> ${dev} command ${JSON.stringify(cmd)}`); + return json(res, 200, cmd); + } + if (req.method === "POST" && p.startsWith("/fire/")) { + const ch = Number(p.split("/")[2]); + const ms = Number(url.searchParams.get("ms") ?? 500); + queue.push({ pulse: ch, ms }); + console.log(`${stamp()} queued pulse relay ${ch} ${ms} ms`); + return json(res, 200, { queued: true }); + } + if (req.method === "POST" && p.startsWith("/watchdog/")) { + const on = p.endsWith("/on"); + queue.push({ watchdog: on }); + console.log(`${stamp()} queued watchdog ${on ? "on" : "off"}`); + return json(res, 200, { queued: true }); + } + if (req.method === "POST" && p === "/reboot-pc") { + queue.push({ reboot_pc: true }); + console.log(`${stamp()} queued PC power-cycle`); + return json(res, 200, { queued: true }); + } + if (req.method === "GET" && p === "/") { + return json(res, 200, { devices: Object.fromEntries(last), queued: queue }); + } + json(res, 404, { error: "not found" }); +}).listen(PORT, "0.0.0.0", () => console.log(`cloud stand-in on :${PORT} (PoC only)`)); diff --git a/firmware/relay-proxy/src/config_store.cpp b/firmware/relay-proxy/src/config_store.cpp new file mode 100644 index 0000000..bee8b94 --- /dev/null +++ b/firmware/relay-proxy/src/config_store.cpp @@ -0,0 +1,90 @@ +#include "config_store.h" +#include +#include "io.h" + +static const char* CFG_PATH = "/config.json"; +static const char* WEB_PATH = "/web.json"; + +void ConfigStore::makeDefaults() { + cfg.clear(); + cfg["status"] = 0; + JsonObject rc = cfg["relay_connect"].to(); + rc["relay_pw"] = 0; + // Factory: udp1 = binary, udp2 = string (password-less!), everything else off. + rc["udp1"]["p"] = 1; rc["udp1"]["port"] = 60000; + rc["udp2"]["p"] = 0; rc["udp2"]["port"] = 60001; + rc["rs485"]["p"] = 255; rc["can"]["p"] = 255; + rc["tcpc"]["p"] = 255; rc["tcps"]["p"] = 255; + rc["mqtt"]["p"] = 255; + // Factory: every input auto-fires its matching relay (the UHPPOTE-style gotcha + // the booth's precondition fix turns off). + JsonObject ilr = cfg["input_link_relay"].to(); + ilr["input_link_relay"] = 1; + JsonArray oa = ilr["on_action_on"].to(); + for (int i = 0; i < CHANNELS; i++) oa.add().add(i); + JsonObject ilu = cfg["input_link_url"].to(); + ilu["cnt"] = CHANNELS; + ilu["en"] = 0; + const char* intKeys[] = {"active_level", "tls", "auth", "on_method", "off_method"}; + for (const char* k : intKeys) { + JsonArray a = ilu[k].to(); + for (int i = 0; i < CHANNELS; i++) a.add(0); + } + { + JsonArray a = ilu["port"].to(); + for (int i = 0; i < CHANNELS; i++) a.add(80); + } + const char* strKeys[] = {"server", "user", "pass", "on_path", "off_path", "on_body", "off_body"}; + for (const char* k : strKeys) { + JsonArray a = ilu[k].to(); + for (int i = 0; i < CHANNELS; i++) a.add(""); + } +} + +void ConfigStore::begin() { + LittleFS.begin(); + bool ok = false; + File f = LittleFS.open(CFG_PATH, "r"); + if (f) { + ok = deserializeJson(cfg, f) == DeserializationError::Ok; + f.close(); + } + if (!ok || !cfg["relay_connect"].is()) { + makeDefaults(); + save(); + } + webUser = "admin"; + webPass = "admin"; + File w = LittleFS.open(WEB_PATH, "r"); + if (w) { + JsonDocument d; + if (deserializeJson(d, w) == DeserializationError::Ok) { + webUser = d["user"] | "admin"; + webPass = d["pass"] | "admin"; + } + w.close(); + } +} + +bool ConfigStore::save() { + File f = LittleFS.open(CFG_PATH, "w"); + if (!f) return false; + serializeJson(cfg, f); + f.close(); + return true; +} + +bool ConfigStore::saveWeb() { + JsonDocument d; + d["user"] = webUser; + d["pass"] = webPass; + File f = LittleFS.open(WEB_PATH, "w"); + if (!f) return false; + serializeJson(d, f); + f.close(); + return true; +} + +uint16_t ConfigStore::relayPw() const { return cfg["relay_connect"]["relay_pw"] | 0; } +bool ConfigStore::stringProtoEnabled() const { return (cfg["relay_connect"]["udp2"]["p"] | 255) != 255; } +bool ConfigStore::linkRelayEnabled() const { return (cfg["input_link_relay"]["input_link_relay"] | 0) == 1; } diff --git a/firmware/relay-proxy/src/digest.cpp b/firmware/relay-proxy/src/digest.cpp new file mode 100644 index 0000000..ed53157 --- /dev/null +++ b/firmware/relay-proxy/src/digest.cpp @@ -0,0 +1,62 @@ +#include "digest.h" +#include +#include +#include + +static String md5(const String& s) { + MD5Builder m; + m.begin(); + m.add(s); + m.calculate(); + return m.toString(); +} + +// Pull key="value" or key=value out of a challenge header. +static String param(const String& h, const char* key) { + String k = String(key) + "="; + int i = h.indexOf(k); + if (i < 0) return ""; + i += k.length(); + if (h[i] == '"') { + int j = h.indexOf('"', i + 1); + return j < 0 ? "" : h.substring(i + 1, j); + } + int j = h.indexOf(',', i); + return j < 0 ? h.substring(i) : h.substring(i, j); +} + +int digestGet(const String& host, uint16_t port, const String& path, const String& user, const String& pass) { + WiFiClient client; + HTTPClient http; + http.setTimeout(2000); + if (!http.begin(client, host, port, path)) return -1; + const char* keys[] = {"WWW-Authenticate"}; + http.collectHeaders(keys, 1); + int code = http.GET(); + if (code != 401 || user.isEmpty()) { + http.end(); + return code; + } + String ch = http.header("WWW-Authenticate"); + http.end(); + if (!ch.startsWith("Digest")) return 401; + + String realm = param(ch, "realm"), nonce = param(ch, "nonce"), qop = param(ch, "qop"); + String nc = "00000001"; + String cnonce = String(ESP.random(), HEX); + String ha1 = md5(user + ":" + realm + ":" + pass); + String ha2 = md5("GET:" + path); + String resp = qop.length() ? md5(ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2) + : md5(ha1 + ":" + nonce + ":" + ha2); + String auth = "Digest username=\"" + user + "\", realm=\"" + realm + "\", nonce=\"" + nonce + + "\", uri=\"" + path + "\", algorithm=MD5, response=\"" + resp + "\""; + if (qop.length()) auth += ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\""; + + HTTPClient h2; + h2.setTimeout(2000); + if (!h2.begin(client, host, port, path)) return -1; + h2.addHeader("Authorization", auth); + code = h2.GET(); + h2.end(); + return code; +} diff --git a/firmware/relay-proxy/src/io_nodemcu.cpp b/firmware/relay-proxy/src/io_nodemcu.cpp new file mode 100644 index 0000000..932ae22 --- /dev/null +++ b/firmware/relay-proxy/src/io_nodemcu.cpp @@ -0,0 +1,50 @@ +// NodeMCU v3 pin map. Zero external wiring needed for the PoC: +// relay 1 -> D1 (GPIO5) + mirrored on the on-board LED (GPIO2, active LOW) +// relay 2 -> D2 (GPIO4) (the watchdog's "PC power" relay) +// relay 3 -> D5 (GPIO14) +// relay 4 -> D6 (GPIO12) +// input 1 -> the on-board FLASH button (GPIO0, pulled up, LOW when pressed) +// input 2 -> D7 (GPIO13), INPUT_PULLUP: short to GND to "press" +// inputs 3-4 are virtual and idle HIGH. +#include "io.h" + +static const int8_t RELAY_PIN[CHANNELS] = {5, 4, 14, 12}; +static const int8_t INPUT_PIN[CHANNELS] = {0, 13, -1, -1}; +static const uint8_t LED_PIN = 2; + +void Io::begin() { + for (int i = 0; i < CHANNELS; i++) { + pinMode(RELAY_PIN[i], OUTPUT); + digitalWrite(RELAY_PIN[i], LOW); + if (INPUT_PIN[i] >= 0) pinMode(INPUT_PIN[i], INPUT_PULLUP); + } + pinMode(LED_PIN, OUTPUT); + digitalWrite(LED_PIN, HIGH); // LED off +} + +void Io::setRelay(int ch, bool on) { + if (ch < 1 || ch > CHANNELS) return; + relays_[ch - 1] = on; + digitalWrite(RELAY_PIN[ch - 1], on ? HIGH : LOW); + if (ch == 1) digitalWrite(LED_PIN, on ? LOW : HIGH); +} + +bool Io::relay(int ch) const { return ch >= 1 && ch <= CHANNELS && relays_[ch - 1]; } + +bool Io::inputHigh(int ch) { + if (ch < 1 || ch > CHANNELS) return true; + int8_t pin = INPUT_PIN[ch - 1]; + return pin < 0 ? true : digitalRead(pin) == HIGH; +} + +uint8_t Io::relayMask() const { + uint8_t m = 0; + for (int i = 0; i < CHANNELS; i++) if (relays_[i]) m |= 1 << i; + return m; +} + +uint8_t Io::inputMask() { + uint8_t m = 0; + for (int i = 0; i < CHANNELS; i++) if (inputHigh(i + 1)) m |= 1 << i; + return m; +} diff --git a/firmware/relay-proxy/src/main.cpp b/firmware/relay-proxy/src/main.cpp new file mode 100644 index 0000000..5514982 --- /dev/null +++ b/firmware/relay-proxy/src/main.cpp @@ -0,0 +1,469 @@ +// relay-proxy — a NodeMCU (ESP8266) that IS a Dingtian DT-R004 to the booth server +// (same wire protocol: binary UDP 60000 with relay_pw, string UDP 60001, config CGI, +// userset.cgi, Digest input push), plus a proxy/watchdog toward an ephemeral cloud +// stand-in. The booth's existing `dingtian` driver needs no change. See README.md. +// +// SAFETY (barrier-not-a-door): a jog turns a relay ON and releases it after the +// requested time — the device never times a *close* against a vehicle. The booth +// expresses intent only; physical safety belongs to the barrier operator. +#include +#include +#include +#include +#include +#include +#include +#include "secrets.h" +#include "io.h" +#include "config_store.h" +#include "digest.h" + +// --- tunables -------------------------------------------------------------- +static const uint32_t HEARTBEAT_MS = 10000; // cloud heartbeat period +static const uint32_t COMMAND_POLL_MS = 2000; // cloud command poll period +static const uint32_t WD_PROBE_MS = 5000; // booth /health probe period +static const int WD_FAIL_THRESHOLD = 6; // probes failed in a row before acting (~30 s) +static const int WD_RELAY = 2; // relay wired to the PC's mains (NC contact) +static const uint16_t WD_PULSE_MS = 3000; // mains cut duration (AC Recovery=On reboots the PC) +static const uint32_t WD_BACKOFF_MS = 600000; // 10 min between power-cycles +static const uint32_t DEBOUNCE_MS = 30; + +// --- state ----------------------------------------------------------------- +static Io io; +static ConfigStore store; +static ESP8266WebServer http(80); +static WiFiUDP udpBin; // Dingtian binary protocol (udp1), authenticated by relay_pw +static WiFiUDP udpStr; // Dingtian string protocol (udp2), password-less — harden() disables it +static bool udpStrOpen = false; +static String devId; // MAC-derived id reported to the cloud + +static uint32_t jogOff[CHANNELS + 1] = {}; // millis() at which a jogged relay releases (0 = none) + +static bool wdEnabled = true; +static int wdFails = 0; +static bool boothOk = false; +static int boothCode = 0; +static uint32_t wdResets = 0; +static uint32_t wdNextProbe = 0, wdBackoffUntil = 0; +static uint32_t nextHeartbeat = 0, nextCommandPoll = 0; +static bool cloudOk = false; + +static uint8_t lastStable = 0xFF, lastRaw = 0xFF; +static uint32_t rawSince = 0; + +static void logf(const char* fmt, ...) { + char buf[200]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof buf, fmt, ap); + va_end(ap); + Serial.printf("[%8lu] %s\n", (unsigned long)millis(), buf); +} + +static inline bool due(uint32_t at) { return (int32_t)(millis() - at) >= 0; } + +// --- relays ---------------------------------------------------------------- +static void jog(int ch, uint16_t ms) { + if (ch < 1 || ch > CHANNELS) return; + io.setRelay(ch, true); + uint32_t t = millis() + ms; + jogOff[ch] = t ? t : 1; + logf("relay %d jog %u ms", ch, ms); +} + +static void releaseJogs() { + for (int ch = 1; ch <= CHANNELS; ch++) { + if (jogOff[ch] && due(jogOff[ch])) { + jogOff[ch] = 0; + io.setRelay(ch, false); + logf("relay %d released", ch); + } + } +} + +// --- cloud (ephemeral stand-in, plain HTTP) -------------------------------- +static int cloudPost(const char* path, const String& body) { + WiFiClient c; + HTTPClient h; + h.setTimeout(1500); + if (!h.begin(c, String(CLOUD_URL) + path)) return -1; + h.addHeader("Content-Type", "application/json"); + int code = h.POST(body); + h.end(); + cloudOk = code == 200; + return code; +} + +static void cloudEvent(const char* type, int ch, bool active, int boothStatus) { + JsonDocument d; + d["dev"] = devId; + d["type"] = type; + d["input"] = ch; + d["active"] = active; + d["booth_status"] = boothStatus; + d["uptime_s"] = millis() / 1000; + String body; + serializeJson(d, body); + int code = cloudPost("/event", body); + logf("cloud event %s -> %d", type, code); +} + +static void heartbeat() { + JsonDocument d; + d["dev"] = devId; + d["ip"] = WiFi.localIP().toString(); + d["rssi"] = WiFi.RSSI(); + d["uptime_s"] = millis() / 1000; + d["heap"] = ESP.getFreeHeap(); + d["booth_ok"] = boothOk; + d["booth_code"] = boothCode; + d["booth_fails"] = wdFails; + d["watchdog"] = wdEnabled; + d["pc_resets"] = wdResets; + d["relays"] = io.relayMask(); + d["inputs"] = io.inputMask(); + d["relay_pw_set"] = store.relayPw() != 0; + d["push_en"] = (store.cfg["input_link_url"]["en"] | 0) == 1; + d["link_relay"] = store.linkRelayEnabled(); + d["string_proto"] = udpStrOpen; + String body; + serializeJson(d, body); + int code = cloudPost("/heartbeat", body); + logf("heartbeat -> %d (booth %s, fails %d)", code, boothOk ? "ok" : "DOWN", wdFails); +} + +static void pollCommand() { + WiFiClient c; + HTTPClient h; + h.setTimeout(1500); + if (!h.begin(c, String(CLOUD_URL) + "/command?dev=" + devId)) return; + int code = h.GET(); + if (code != 200) { h.end(); return; } + String body = h.getString(); + h.end(); + JsonDocument d; + if (deserializeJson(d, body) != DeserializationError::Ok) return; + if (d["pulse"].is()) { + int ch = d["pulse"]; + uint16_t ms = d["ms"] | 500; + logf("CLOUD command: pulse relay %d", ch); + jog(ch, ms); + } + if (d["watchdog"].is()) { + wdEnabled = d["watchdog"]; + logf("CLOUD command: watchdog %s", wdEnabled ? "enabled" : "disabled"); + } + if (d["reboot_pc"] | false) { + logf("CLOUD command: power-cycle PC"); + jog(WD_RELAY, WD_PULSE_MS); + wdResets++; + } +} + +// --- watchdog -------------------------------------------------------------- +static void watchdogTick() { + if (!due(wdNextProbe)) return; + wdNextProbe = millis() + WD_PROBE_MS; + WiFiClient c; + HTTPClient h; + h.setTimeout(1500); + int code = -1; + if (h.begin(c, BOOTH_HEALTH_URL)) { + code = h.GET(); + h.end(); + } + boothCode = code; + bool ok = code == 200; + if (ok != boothOk) logf("booth is now %s (HTTP %d)", ok ? "UP" : "DOWN", code); + boothOk = ok; + wdFails = ok ? 0 : wdFails + 1; + if (!ok && wdEnabled && wdFails >= WD_FAIL_THRESHOLD && due(wdBackoffUntil)) { + logf("WATCHDOG: booth down for %d probes -> power-cycling via relay %d", wdFails, WD_RELAY); + jog(WD_RELAY, WD_PULSE_MS); + wdResets++; + wdBackoffUntil = millis() + WD_BACKOFF_MS; + cloudEvent("pc_reset", 0, false, code); + } +} + +// --- inputs ---------------------------------------------------------------- +static bool inputActive(int ch, bool high) { + // Dingtian semantics: input_link_url.active_level[i] 0 = active LOW. + int level = store.cfg["input_link_url"]["active_level"][ch - 1] | 0; + return level == 0 ? !high : high; +} + +// Returns the booth HTTP status, or 0 when push is not configured. +static int pushInput(int ch, bool active) { + JsonObjectConst ilu = store.cfg["input_link_url"].as(); + if (ilu.isNull() || (ilu["en"] | 0) != 1) return 0; + String host = ilu["server"][ch - 1] | ""; + if (host.isEmpty()) return 0; + uint16_t port = ilu["port"][ch - 1] | 80; + String path = active ? (ilu["on_path"][ch - 1] | "") : (ilu["off_path"][ch - 1] | ""); + if (path.isEmpty()) return 0; + int auth = ilu["auth"][ch - 1] | 0; + String user = auth ? (ilu["user"][ch - 1] | "") : ""; + String pass = ilu["pass"][ch - 1] | ""; + int code = digestGet(host, port, path, user, pass); + logf("push input %d %s -> %s:%u%s -> %d", ch, active ? "on" : "off", host.c_str(), port, path.c_str(), code); + return code; +} + +static void onInputChange(int ch, bool high) { + bool active = inputActive(ch, high); + logf("input %d %s (%s)", ch, high ? "HIGH" : "LOW", active ? "active" : "idle"); + // Factory behaviour the booth's precondition fix turns off: input auto-fires its relays. + if (store.linkRelayEnabled()) { + JsonArrayConst acts = store.cfg["input_link_relay"]["on_action_on"][ch - 1].as(); + for (JsonVariantConst v : acts) { + int r = v.as() + 1; + io.setRelay(r, active); + logf("input_link_relay: input %d -> relay %d %s", ch, r, active ? "ON" : "off"); + } + } + // Booth first (the normal path), then the cloud mirror — always, so the cloud + // still sees the button when the booth is dead or not yet configured. + int boothStatus = pushInput(ch, active); + cloudEvent(active ? "input_on" : "input_off", ch, active, boothStatus); +} + +static void inputTick() { + uint8_t raw = io.inputMask(); + if (raw != lastRaw) { + lastRaw = raw; + rawSince = millis(); + return; + } + if (millis() - rawSince < DEBOUNCE_MS || raw == lastStable) return; + uint8_t changed = raw ^ lastStable; + lastStable = raw; + for (int ch = 1; ch <= CHANNELS; ch++) { + if (changed & (1 << (ch - 1))) onInputChange(ch, raw & (1 << (ch - 1))); + } +} + +// --- Dingtian binary protocol (UDP 60000) ---------------------------------- +// Request: FF AA [data...] +// Reply: FF AA (4ch: one byte each) +// cmd 0x00 read status; 0x01 write (mask,set); 0x03 jog (relayByte, units of 100 ms). +// Wrong password -> silently dropped, exactly like the hardware. +static void handleBinary() { + int n = udpBin.parsePacket(); + if (!n) return; + uint8_t b[32]; + int len = udpBin.read(b, sizeof b); + if (len < 6 || b[0] != 0xFF || b[1] != 0xAA) return; + uint16_t pw = b[4] | (b[5] << 8); + uint16_t want = store.relayPw(); + if (want != 0 && pw != want) { + logf("binary: bad relay_pw %u from %s — dropped", pw, udpBin.remoteIP().toString().c_str()); + return; + } + uint8_t session = b[2], cmd = b[3]; + switch (cmd) { + case 0x00: + break; + case 0x01: + if (len >= 8) { + uint8_t mask = b[6], set = b[7]; + for (int ch = 1; ch <= CHANNELS; ch++) { + uint8_t bit = 1 << (ch - 1); + if (mask & bit) { jogOff[ch] = 0; io.setRelay(ch, set & bit); } + } + logf("binary: write mask %02x set %02x", mask, set); + } + break; + case 0x03: + if (len >= 9) { + uint8_t rb = b[6]; + int ch = (rb >> 1) + 1; + uint16_t units = b[7] | (b[8] << 8); + if (rb & 1) jog(ch, units * 100); + else { jogOff[ch] = 0; io.setRelay(ch, false); } + } + break; + default: + logf("binary: unsupported cmd %02x", cmd); + return; + } + uint8_t r[6] = {0xFF, 0xAA, session, cmd, io.relayMask(), io.inputMask()}; + udpBin.beginPacket(udpBin.remoteIP(), udpBin.remotePort()); + udpBin.write(r, sizeof r); + udpBin.endPacket(); +} + +// --- Dingtian string protocol (UDP 60001) — the password-less hole ---------- +// "00" status -> "RRRR:IIII:4"; "1N" relay N on; "2N" off; "1N*" jog 500 ms. +static void handleString() { + if (!udpStrOpen) return; + int n = udpStr.parsePacket(); + if (!n) return; + char b[16]; + int len = udpStr.read(b, sizeof b - 1); + b[len < 0 ? 0 : len] = 0; + String cmd(b); + cmd.trim(); + if (cmd == "00") { + // status only + } else if (cmd.length() >= 2 && (cmd[0] == '1' || cmd[0] == '2') && isDigit(cmd[1])) { + int ch = cmd[1] - '0'; + if (ch < 1 || ch > CHANNELS) return; + logf("string: UNAUTHENTICATED '%s' from %s", cmd.c_str(), udpStr.remoteIP().toString().c_str()); + if (cmd.endsWith("*")) jog(ch, 500); + else { jogOff[ch] = 0; io.setRelay(ch, cmd[0] == '1'); } + } else { + return; + } + String r; + for (int ch = 1; ch <= CHANNELS; ch++) r += io.relay(ch) ? '1' : '0'; + r += ':'; + for (int ch = 1; ch <= CHANNELS; ch++) r += io.inputHigh(ch) ? '1' : '0'; + r += ":" + String(CHANNELS); + udpStr.beginPacket(udpStr.remoteIP(), udpStr.remotePort()); + udpStr.print(r); + udpStr.endPacket(); +} + +static void applyProtocolConfig() { + bool want = store.stringProtoEnabled(); + if (want && !udpStrOpen) { udpStr.begin(60001); udpStrOpen = true; logf("string protocol (udp2) ENABLED on 60001"); } + if (!want && udpStrOpen) { udpStr.stop(); udpStrOpen = false; logf("string protocol (udp2) disabled"); } +} + +// --- Dingtian config CGI (HTTP 80) ------------------------------------------ +static void onConfigGet() { + String out; + serializeJson(store.cfg, out); + http.send(200, "application/json", out); +} + +static void onConfigSet() { + String body = http.arg("plain"); + JsonDocument doc; + if (deserializeJson(doc, body) != DeserializationError::Ok) { + http.send(400, "application/json", "{\"status\":1}"); + return; + } + // Faithful to the hardware gotcha: without "command":"setconfig" the device + // answers OK and silently does nothing. + if (strcmp(doc["command"] | "", "setconfig") != 0) { + logf("config_set without command=setconfig — ignored (as the real device does)"); + http.send(200, "application/json", "{\"status\":0}"); + return; + } + doc.remove("command"); + store.cfg = doc; + store.save(); + applyProtocolConfig(); + logf("config applied: relay_pw=%u link_relay=%d push_en=%d udp2=%s", store.relayPw(), store.linkRelayEnabled(), + (int)(store.cfg["input_link_url"]["en"] | 0), udpStrOpen ? "on" : "off"); + http.send(200, "application/json", "{\"status\":0}"); +} + +// GET /userset.cgi?&&&& -> "&0&/&" ok, "&2&/&" wrong old cred +static void onUserSet() { + if (http.args() < 4) { http.send(200, "text/plain", "&1&/&"); return; } + String u = http.argName(0), oldP = http.argName(1), newU = http.argName(2), newP = http.argName(3); + if (u != store.webUser || oldP != store.webPass) { + logf("userset: rejected (wrong current credentials)"); + http.send(200, "text/plain", "&2&/&"); + return; + } + store.webUser = newU; + store.webPass = newP; + store.saveWeb(); + logf("userset: web login rotated"); + http.send(200, "text/plain", "&0&/&"); +} + +static void onRoot() { + String s = "relay-proxy (Dingtian DT-R004 emulator)\n"; + s += "id " + devId + " ip " + WiFi.localIP().toString() + "\n"; + s += "relays " + String(io.relayMask(), BIN) + " inputs " + String(io.inputMask(), BIN) + "\n"; + s += "relay_pw " + String(store.relayPw() ? "set" : "none") + " link_relay " + String(store.linkRelayEnabled()) + + " push_en " + String((int)(store.cfg["input_link_url"]["en"] | 0)) + " udp2 " + String(udpStrOpen) + "\n"; + s += "booth " + String(boothOk ? "UP" : "DOWN") + " (HTTP " + String(boothCode) + ", fails " + String(wdFails) + ") watchdog " + + String(wdEnabled) + " pc_resets " + String(wdResets) + "\n"; + s += "cloud " + String(cloudOk ? "ok" : "unreachable") + " heap " + String(ESP.getFreeHeap()) + "\n"; + http.send(200, "text/plain", s); +} + +// PoC-only helper: back to factory state so the booth's assign flow can be re-run. +static void onFactoryReset() { + store.makeDefaults(); + store.save(); + store.webUser = "admin"; + store.webPass = "admin"; + store.saveWeb(); + applyProtocolConfig(); + logf("FACTORY RESET"); + http.send(200, "application/json", "{\"status\":0}"); +} + +// --- wifi ------------------------------------------------------------------ +static void connectWifi() { + WiFi.mode(WIFI_STA); + WiFi.setAutoReconnect(true); + WiFi.hostname("relay-proxy"); +#ifdef STATIC_IP + IPAddress ip, gw, mask; + ip.fromString(STATIC_IP); + gw.fromString(STATIC_GW); + mask.fromString(STATIC_MASK); + WiFi.config(ip, gw, mask, gw); +#endif + WiFi.begin(WIFI_SSID, WIFI_PASS); + logf("wifi: connecting to %s", WIFI_SSID); + uint32_t t0 = millis(); + while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(200); + if (WiFi.status() == WL_CONNECTED) logf("wifi: %s rssi %d", WiFi.localIP().toString().c_str(), WiFi.RSSI()); + else logf("wifi: not connected yet (status %d) — will keep retrying", WiFi.status()); +} + +// --- setup / loop ---------------------------------------------------------- +void setup() { + Serial.begin(115200); + delay(100); + Serial.println(); + io.begin(); + store.begin(); + devId = WiFi.macAddress(); + devId.replace(":", ""); + devId.toLowerCase(); + logf("relay-proxy starting, id %s, relay_pw %s, link_relay %d", devId.c_str(), store.relayPw() ? "set" : "none", + store.linkRelayEnabled()); + + connectWifi(); + + udpBin.begin(60000); + applyProtocolConfig(); + + http.on("/", HTTP_GET, onRoot); + http.on("/api/v2/config.cgi", HTTP_GET, onConfigGet); + http.on("/api/v2/config_set.cgi", HTTP_POST, onConfigSet); + http.on("/userset.cgi", HTTP_GET, onUserSet); + http.on("/poc/factory_reset", HTTP_POST, onFactoryReset); + http.onNotFound([] { http.send(404, "text/plain", "not found"); }); + http.begin(); + + lastStable = lastRaw = io.inputMask(); // baseline, no boot events + rawSince = millis(); + wdNextProbe = millis() + 2000; + nextHeartbeat = millis() + 3000; + nextCommandPoll = millis() + 4000; +} + +void loop() { + http.handleClient(); + handleBinary(); + handleString(); + releaseJogs(); + inputTick(); + if (WiFi.status() == WL_CONNECTED) { + watchdogTick(); + if (due(nextHeartbeat)) { nextHeartbeat = millis() + HEARTBEAT_MS; heartbeat(); } + if (due(nextCommandPoll)) { nextCommandPoll = millis() + COMMAND_POLL_MS; pollCommand(); } + } + delay(2); +} diff --git a/wiki/concepts/esp32-flashability-test.md b/wiki/concepts/esp32-flashability-test.md new file mode 100644 index 0000000..809998e --- /dev/null +++ b/wiki/concepts/esp32-flashability-test.md @@ -0,0 +1,101 @@ +--- +type: concept +tags: [parking, hardware, runbook, esp32, dingtian] +sources: [] +updated: 2026-10-22 +--- + +# Runbook — Is this ESP32 board flashable? (Dingtian DT-R0xx lock test) + +A bench test that answers one question in a few minutes: **is the ESP32 on this [[dingtian-relay]] +locked (standard SKU) or open (Development Board Version)?** Run it before ordering more units or +planning any custom-firmware work (see [[dingtian-relay]] "Can we flash our own firmware?"). + +The test is read-only. Nothing is written to the chip, no eFuse is burned, and the stock firmware +boots normally afterwards. + +## What "locked" means on an ESP32 + +The vendor burns one-time eFuse bits at the factory; they can never be cleared. Any one of these +blocks custom firmware: + +| eFuse | Effect | How the test shows it | +| --- | --- | --- | +| `DISABLE_DL_ENCRYPT` / `DISABLE_DL_DECRYPT` / UART download disabled | ROM bootloader refuses serial flashing | `esptool chip_id` never connects | +| `FLASH_CRYPT_CNT` (flash encryption) | flash contents unreadable/unwritable from outside | `espefuse summary` shows it odd/enabled | +| `ABS_DONE_0` / `ABS_DONE_1` (secure boot) | ROM only runs a vendor-signed bootloader | `espefuse summary` shows it set | + +The 74HC595 / 74HC165 shift registers on the board are **not** a blocker; community firmware drives +them already. + +## Equipment + +- USB-to-UART adapter, **3.3 V logic** (CP2102 / CH340 / FT232). Set its jumper to 3.3 V. +- Dupont leads. Do **not** connect the 12 V supply; the adapter's 3.3 V powers the ESP32 for this test. +- A PC with Python: `pip install esptool` (gives both `esptool.py` and `espefuse.py`). + +## Wiring (DT-R0xx programming header) + +| Adapter | Board | +| --- | --- | +| GND | GND | +| 3V3 | 3V3 | +| TXD | RXD (ESP32 GPIO3) | +| RXD | TXD (ESP32 GPIO1) | +| DTR | NRST (optional; lets esptool reset the board itself) | + +Header labelling varies by revision; confirm against the silkscreen. GPIO1/3 are also the board's +Modbus UART, so expect the stock firmware to chatter on them when it boots. + +## Procedure + +1. Wire as above, adapter unplugged. +2. **Hold the board's boot switch** while plugging the adapter into USB. Keep holding ~1 s, release. + (Without DTR wired, this is the only way into download mode.) +3. Identify the port: `COMx` on Windows, `/dev/ttyUSB0` on Linux. On WSL, pass the device through + or run from Windows. +4. Run: + +``` +esptool.py --port COM5 --baud 115200 chip_id +``` + +5. If it connects, read the eFuses: + +``` +espefuse.py --port COM5 summary +``` + +## Reading the result + +**Open (Development SKU):** +``` +Chip is ESP32-D0WD-V3 (revision v3.x) +Features: WiFi, BT, Dual Core, 240MHz, ... +Chip ID: 0x... +``` +and in the summary `FLASH_CRYPT_CNT = 0`, `ABS_DONE_0 = False`, `ABS_DONE_1 = False`, +`DISABLE_DL_* = False`. Custom firmware (ESPHome `dtr0xx_io`, Tasmota, ESP-IDF) is possible. + +**Locked (Standard SKU), either of:** +- `A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header` + after the boot-switch step was done correctly → UART download is disabled. +- It connects but the summary shows flash encryption and/or secure boot enabled → you can reach the + ROM but cannot run your own image. Treat as locked. + +**Inconclusive:** garbled output or "Connecting....." forever on the *first* try is usually a wiring +or boot-mode slip (TX/RX swapped, 5 V jumper, switch released too early). Retry twice before calling +it locked. One forum report of exactly this symptom was never resolved. + +## Record the outcome + +Add a line to the "Status" list on [[dingtian-relay]] with the unit's serial, SKU, firmware version +and the verdict, and a `## [date] query` entry in `log.md`. A locked verdict closes the custom-firmware +question for that unit; the only route is ordering the Development Board Version +([[esp32-custom-controller]] remains deferred, [[open-questions]] #6). + +## Related + +- [[dingtian-relay]] — hardening gaps that custom firmware would close. +- [[esp32-custom-controller]] — the prevention-grade device this would approximate. +- [[site-device-installation]] — field runbook; this test is a bench task, not a site task. diff --git a/wiki/concepts/site-device-installation.md b/wiki/concepts/site-device-installation.md index 1108396..5180c1f 100644 --- a/wiki/concepts/site-device-installation.md +++ b/wiki/concepts/site-device-installation.md @@ -345,3 +345,18 @@ Related: [[appliance-provisioning]] · [[first-run-setup]] · [[device-registry] [[network-isolation]] · [[entry-exit-points]] · [[dingtian-relay]] · [[dingtian-dt008-reader]] · [[lpr-camera]] · [[hikvision-radar]] · [[k200l-printer]] · [[rongta-printer]] · [[printer-usb-transport]] · [[wsl-dev-networking]] + +## Booth host firewall: what the device net must reach (2026-10-22) + +Found at park-lab (ufw active, rules root-only): the device VLAN could reach ssh but **not** the +app. Devices need, from the device subnet to the booth: + +| Port | Who | Why | +| --- | --- | --- | +| **3000/tcp** (`PORT`) | [[dingtian-relay]] input push, any device push | `backendPort()` advertises the server's own port, **not** Caddy's 80 — the push bypasses the proxy. | +| 80/tcp | admins on the LAN | Caddy → operator UI (and `/health`). | + +`sudo ufw allow from 10.0.10.0/24 to any port 3000 proto tcp` (and 80). Without 3000 the booth's +assign flow *succeeds* (it configures the device outbound) but every button push then dies with a +timeout — a silent failure. The booth's ufw rule set is not yet captured in +[[appliance-provisioning]]; it should be. diff --git a/wiki/decisions/open-questions.md b/wiki/decisions/open-questions.md index 49afecb..1ebe47a 100644 --- a/wiki/decisions/open-questions.md +++ b/wiki/decisions/open-questions.md @@ -178,3 +178,12 @@ procurement. (See [[parking-system-architecture]] §10.) reply unknown) and Dahua (37810, uncaptured) do not. Plan, rules and order of work: [[device-discovery-roadmap]]. Settles when cameras and printers scan from the wizard and the relay's search reply has been captured on the bench. + +## Cloud takeover mode vs. the signed ledger (2026-10-22, parked) + +If the cloud commands the barrier while the booth PC is dead ([[relay-proxy-firmware]]), entry/exit +events happen that the site's [[atecc608]] signer never saw. Unresolved by design for now: a +cloud-authored, separately signed segment the booth ingests and countersigns on return, with the +gap recorded rather than hidden. Without it, takeover is a fraud lever (pull the PC's power). +Also: exit must still fail open by hardware when the uplink is down too ([[fail-state-safety]]). + diff --git a/wiki/entities/dingtian-relay.md b/wiki/entities/dingtian-relay.md index 81186c7..b8b2f44 100644 --- a/wiki/entities/dingtian-relay.md +++ b/wiki/entities/dingtian-relay.md @@ -2,7 +2,7 @@ type: entity tags: [parking, hardware, access-control, relay] sources: [] -updated: 2026-06-14 +updated: 2026-10-22 --- # Dingtian Relay Controller @@ -170,6 +170,33 @@ On assign the driver runs `harden()` (the [[device-registry|HardenableDevice]] c > drop connections (ECONNRESET), locking out the API the driver depends on — recoverable only by > factory reset. `harden()` deliberately never touches it. +## Can we flash our own firmware? (2026-10-22) + +The DT-R0xx boards are **ESP32-WROOM-32D** designs (the module is visible in product photos; the +community ESPHome/Tasmota configs target ESP32). Relays/inputs are behind **74HC595 / 74HC165 +shift registers** (SDI GPIO13, CLK GPIO14, RCK GPIO15, PL GPIO32, Q7 GPIO16); Ethernet is a +**JL1101 PHY** (MDC 23, MDIO 18, clock out 17, power 0). Community firmware exists: Tasmota +templates (Dingtian ships them in its own download centre) and an ESPHome external component +`dtr0xx_io`. + +**But the vendor sells two SKUs.** The *Standard Firmware Version* (default shipment) is locked — +dtwonder: "The standard finished firmware version is not intended for user firmware flashing"; +ESPHome devices page: "ask for relay board with test firmware, otherwise the ESP32 will be locked". +The *Development Board Version* ships with a bare "GPIO test firmware" and is meant for ESPHome / +Tasmota / ESP-IDF. The lock mechanism is not documented publicly (flash encryption, secure boot, +or UART-download-disable eFuses are all plausible on an ESP32 — eFuses are irreversible). No +forum post reports successfully unlocking a standard unit. Flashing a dev unit is plain ESP32 +serial flashing (NRST↔DTR, 3.3 V USB-UART, hold the boot switch while powering). + +**Implication for us:** our bench unit (DT-R004, V3.1.5461A, standard SKU) should be assumed +**not flashable** until tested — runbook: [[esp32-flashability-test]]; a dev-SKU unit would be. Custom firmware would let us close the open CGI/UDP +control plane (the hardening gaps above) by putting [[challenge-response-auth]] on the device — +effectively the [[esp32-custom-controller]] path on vendor hardware (no [[atecc608]] footprint, +so the key would live in ESP32 eFuse/NVS under flash encryption). That remains **deferred** +([[open-questions]] #6); if revisited, order the dev SKU and note the relay-GPIO pull-down +"relays blip on at boot" report on Tasmota — a boot-time relay pulse on a barrier is unacceptable +([[barrier-not-a-door]]) and must be verified before any field use. + ## `relayPassword` field + the "offline despite ping" gotcha (2026-06-24) `relay_pw` is in **every** binary frame — control AND the status read `healthCheck()` uses. With a diff --git a/wiki/entities/relay-proxy-firmware.md b/wiki/entities/relay-proxy-firmware.md new file mode 100644 index 0000000..920a086 --- /dev/null +++ b/wiki/entities/relay-proxy-firmware.md @@ -0,0 +1,73 @@ +--- +type: entity +tags: [parking, hardware, firmware, esp8266, dingtian, cloud, watchdog, poc] +sources: [] +updated: 2026-10-22 +status: poc +--- + +# relay-proxy — Dingtian emulator + cloud proxy/watchdog firmware (PoC) + +Code: `firmware/relay-proxy/` (PlatformIO, Arduino framework; NodeMCU v3 / ESP8266 now, ESP32 +env planned for the real [[dingtian-relay]]). Throwaway cloud stand-in: `poc/cloud-standin.mjs`. + +## Why + +park-2's booth PC died twice unnoticed ([[appliance-provisioning]] incident 2026-10-17). The +idea (2026-10-22): the device that already owns the barrier relay and the button inputs becomes +the resilient core — it reports to a multi-tenant cloud independently of the PC, can +power-cycle the PC, and keeps taking relay commands from the cloud when the PC is dead. Custom +firmware on the Dingtian is the natural home ([[esp32-flashability-test]] gates that); the +NodeMCU is the stand-in while no flashable Dingtian is on hand. Ledger implications of a cloud +takeover mode are **deliberately parked** (see [[open-questions]]). + +## What it is to the booth: a DT-R004 + +The firmware speaks the Dingtian wire contract so the booth's `dingtian` driver is unchanged: +binary UDP 60000 (`00` status / `01` write / `03` jog, `relay_pw` checked, wrong password +dropped silently), string UDP 60001 (password-less; disabled when `udp2.p=255`), +`GET /api/v2/config.cgi`, `POST /api/v2/config_set.cgi` (requires `"command":"setconfig"`, +exactly like the hardware gotcha), `GET /userset.cgi` (`&0&` / `&2&`), and Digest-authenticated +input push to `on_path`/`off_path`. Config persists in LittleFS; factory state has +`input_link_relay` ON so the booth's precondition fix is exercised. + +**Verified 2026-10-22 from the dev PC** (board at 10.0.10.101 on the ArtServis Wi-Fi, which lands +on the park-lab device net): status reply `ff aa s 00 `, jog/write/release, string +`00`→`0000:1111:4`, setconfig-only writes, login rotation codes, cloud → relay pulse. + +## What it adds: proxy + watchdog + +Heartbeat to the cloud every 10 s (IP, booth health, relay/input state, config flags); every input +change mirrored to the cloud regardless of booth push config; cloud command poll (`pulse`, +`watchdog`, `reboot_pc`); watchdog probes the booth `/health` every 5 s and after 6 misses pulses +relay 2 for 3 s (NC contact in series with the PC mains + BIOS AC Recovery=On = reboot), 10-min +backoff, cloud can disable. This is the detect+remediate layer park-2 lacked. + +## Booth integration — VERIFIED end to end (2026-10-22, park-lab) + +After `ufw allow from 10.0.10.0/24 to any port 80,3000 proto tcp` on park-lab (see +[[site-device-installation]] "Booth host firewall"): the admin added the board in park-lab's setup +as a Dingtian controller (host 10.0.10.101). The booth's assign flow landed on the board exactly as +on hardware — `input_link_relay` cleared, random `relay_pw`, every channel but UDP1 set to 255 +(udp2 really off: `00` on 60001 times out), web login rotated (`admin/admin` → `&2&`), Digest push +to `10.0.10.198:3000/api/devices/dingtian//input/N/{on,off}`. A FLASH-button press then +produced: board → booth `401` challenge → Digest retry → `200`, booth log +`[dingtian:] input 1 on (push)` + `off`, and the cloud stand-in received `input_on` / +`input_off` with `booth_status=200` — the same event seen by booth and cloud independently. The +watchdog flipped to `booth UP` the moment port 80 opened. + +## Open + +- The booth's ufw rule set is root-only and undocumented — belongs in [[appliance-provisioning]]. +- The booth accepts pushes only from the registered host IP → the board needs a DHCP reservation + or `STATIC_IP`. +- ESP8266 limits (Wi-Fi only, ~40 KB heap, blocking HTTP) are PoC-only; the target is the ESP32 + on the Dingtian with Ethernet. Camera traffic is never proxied by the microcontroller. + +## Bench note: NodeMCU v3 clone CH340 vs WCH driver + +The board's USB-serial reports `USB\VID_1A86&PID_7523&REV_0254` and WCH drivers 3.9/4.0 refuse it +("A device attached to the system is not functioning" on every open). Fix applied 2026-10-22: +WCH driver **3.4.2014.08** (SparkFun mirror, WHQL catalog + Qinheng-signed setup verified), +staged with `pnputil /add-driver`, newer package exported to scratch then deleted from the store +so the port rebinds. Windows Update may push 4.0 back; repeat if the port fails again. diff --git a/wiki/index.md b/wiki/index.md index eea219e..97bab77 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -46,6 +46,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records. - [[dingtian-dt008-reader]] — Dingtian DT-008 QR/RFID reader on hand; HTTP-GET push, server replies the verdict; ⚠️ our two units read disjoint card sets (125 kHz vs 13.56 MHz) — unresolved, see open question #18. - [[zkteco-controller]] — ❌ rejected/historical; aux-input path was a contender, not pursued. - [[dingtian-relay]] — ✅ CHOSEN access controller; decoupled inputs solve the button blocker (driver verified on hardware); spare relays drive aux outputs (`setAux`). +- [[relay-proxy-firmware]] — PoC (2026-10-22): NodeMCU firmware that IS a DT-R004 to the booth (binary/string UDP, config CGI, userset, Digest push) + cloud heartbeat/command/watchdog (power-cycles the PC). Verified against the emulator; booth integration blocked on park-lab ufw. - [[dahua-ipc-hfw2549t]] — first Dahua on the bench (IPC-HFW2549T-AS-IL, fw 2.880, 2026-09-17): the driver's channel decrement gave HTTP 400 (channels are 1-based — fixed + verified live); Dahua clock-sync built (`global.cgi`, naive wall time); events = held `eventManager attach` multipart stream, verbatim `VideoMotion Start/Stop` + `TimeChange` parts captured, subscriber not built; `RealUTC` is the camera's belief of UTC; 5-strike login lockout. - [[hikvision-radar]] — vehicle-presence radar on a Dingtian input; the entry presence gate (per-input active-level caveat). - [[rongta-printer]] — ✅ CHOSEN 80mm thermal printer; ESC/POS over raw TCP 9100 (or local USB, see [[printer-usb-transport]]); driver written, one unit reachable at 10.0.10.6. @@ -70,6 +71,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records. - [[device-registry]] — catalog of selectable drivers per category (admin-configurable). - [[first-run-setup]] — admin adds controllers + binds readers/cameras to relays from the catalog at install. - [[site-device-installation]] — FIELD RUNBOOK (2026-09-09): per device — factory address + credentials, the tool needed, what the wizard configures itself vs what is done by hand on the device, known traps; address plan, order of work on site, gaps to fill. Dingtian relay, DT-008 readers, Hikvision camera, radar, K200L / Rongta / Cashino printers. +- [[esp32-flashability-test]] — BENCH RUNBOOK (2026-10-22): is this ESP32 board locked? `esptool chip_id` + `espefuse summary` on the Dingtian DT-R0xx programming header; read-only; locked = standard SKU, open = Development Board Version. - [[device-input-flow]] — button → device push → backend decides → relay; backend is source of truth. - [[device-discovery]] — optional driver capability to scan the LAN; implemented by the DT-008 reader (2026-10-08), UHPPOTE was the historical example. - [[barrier-not-a-door]] — never timed-close a barrier; safety lives in barrier firmware. diff --git a/wiki/log.md b/wiki/log.md index b02322d..1a6dd8d 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -3547,3 +3547,35 @@ set via dell-wmi-sysman; no BIOS admin password on the replacement yet. Ledger c after two unclean stops. [[appliance-provisioning]] §1/§8 + gotchas 7–8. ## [2026-10-20] ingest | park-lab back on a dedicated 7070 (server = park-lab, all modules entitled); GRUB CLASS line clarified in appliance-provisioning §5 + +## [2026-10-22] query | Dingtian DT-R0xx: can we flash our own firmware? + +ESP32-WROOM-32D board; community ESPHome (`dtr0xx_io`) / Tasmota support exists, but the vendor +locks the standard SKU — only the "Development Board Version" (GPIO test firmware) is flashable. +Our bench DT-R004 is the standard SKU → assume not flashable. Filed under [[dingtian-relay]] +"Can we flash our own firmware?"; custom firmware stays deferred ([[esp32-custom-controller]]). + +## [2026-10-22] built | Runbook: ESP32 flashability test for the Dingtian DT-R0xx + +New [[esp32-flashability-test]] (concepts/): wiring, boot-mode entry, `esptool chip_id` + +`espefuse summary`, how to read locked vs open vs inconclusive. Linked from [[dingtian-relay]] and index. + +## [2026-10-22] built | relay-proxy PoC firmware (NodeMCU as a Dingtian DT-R004 + cloud proxy/watchdog) + +New [[relay-proxy-firmware]]: flashed, on Wi-Fi at 10.0.10.101, every Dingtian surface verified +from the dev PC, cloud→relay command verified. Blocked: park-lab ufw drops 80/3000 from the device +net (also blocks a real Dingtian push) — needs root. Bench fix: clone CH340 needs WCH driver 3.4. +Parked the ledger question in [[open-questions]]. + +## [2026-10-22] query | Booth firewall vs device push: the push targets PORT 3000, not Caddy's 80 + +park-lab ufw let the NodeMCU reach /health on 80 after the first rule, and the booth assign flow +configured the board (relay_pw, udp2 off, login rotated, Digest push to 10.0.10.198:3000) — but +3000 is still dropped from the device net, so pushes would time out. Documented in +[[site-device-installation]] "Booth host firewall"; rule set belongs in [[appliance-provisioning]]. + +## [2026-10-22] built | relay-proxy: booth integration verified end to end at park-lab + +Board registered through park-lab setup; assign flow applied every step; FLASH press → Digest push +accepted by the booth (401→200, "input 1 on (push)") and mirrored to the cloud stand-in with +booth_status 200. See [[relay-proxy-firmware]].