// 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); }