feat(firmware): relay-proxy PoC — NodeMCU as a Dingtian DT-R004 + cloud proxy/watchdog

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.
This commit is contained in:
2026-10-22 12:08:20 +02:00
parent e842f036e2
commit c08e232339
19 changed files with 1162 additions and 1 deletions
+71
View File
@@ -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.
@@ -0,0 +1,20 @@
#pragma once
#include <ArduinoJson.h>
// 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)
};
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <Arduino.h>
// 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);
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <Arduino.h>
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] = {};
};
@@ -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"
+16
View File
@@ -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
@@ -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)`));
+90
View File
@@ -0,0 +1,90 @@
#include "config_store.h"
#include <LittleFS.h>
#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<JsonObject>();
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<JsonObject>();
ilr["input_link_relay"] = 1;
JsonArray oa = ilr["on_action_on"].to<JsonArray>();
for (int i = 0; i < CHANNELS; i++) oa.add<JsonArray>().add(i);
JsonObject ilu = cfg["input_link_url"].to<JsonObject>();
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<JsonArray>();
for (int i = 0; i < CHANNELS; i++) a.add(0);
}
{
JsonArray a = ilu["port"].to<JsonArray>();
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<JsonArray>();
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<JsonObject>()) {
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; }
+62
View File
@@ -0,0 +1,62 @@
#include "digest.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <MD5Builder.h>
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;
}
+50
View File
@@ -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;
}
+469
View File
@@ -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 <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>
#include <stdarg.h>
#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>()) {
int ch = d["pulse"];
uint16_t ms = d["ms"] | 500;
logf("CLOUD command: pulse relay %d", ch);
jog(ch, ms);
}
if (d["watchdog"].is<bool>()) {
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<JsonObjectConst>();
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<JsonArrayConst>();
for (JsonVariantConst v : acts) {
int r = v.as<int>() + 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 <session> <cmd> <pwLo> <pwHi> [data...]
// Reply: FF AA <session> <cmd> <relayByte> <inputByte> (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?<user>&<old>&<user>&<new>& -> "&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);
}