/* * Link Peer Module Implementation (Main CTRL) * * Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into * g_peer under a mutex. Everything else (NVS, sending, console) is the loop task. */ #include "link_peer.h" #include "espnow_link.h" #include "uart_manager.h" #include "wifi_manager.h" #include "ota_update.h" #include "serial_lock.h" #include "protocol/link_secure.h" #include #include #include #include namespace LinkPeer { static const char* NVS_LINK = "linkpeer"; // key (32 B) #define CREDS_PUSH_MIN_MS 15000 // never push credentials more often than this #define PAIR_REPEATS 3 // PAIR is sent this many times over the wire static bool g_paired = false; static uint8_t g_key[LINK_KEY_LEN]; static uint16_t g_key_fp = 0; // last STATUS from B (written by the Wi-Fi task) static SemaphoreHandle_t g_mutex = NULL; static link_status_t g_st = {}; static uint8_t g_b_mac[6] = {0}; static uint32_t g_last_status_ms = 0; static bool g_ever_heard = false; static uint32_t g_status_count = 0, g_secure_sent = 0, g_secure_fail = 0; // credential sync static uint32_t g_pushed_hash = 0; static uint32_t g_last_push_ms = 0; static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); } static void unlock() { xSemaphoreGive(g_mutex); } static void print(const char* fmt, ...) { char buf[200]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); SerialLock::lock(); Serial.println(buf); SerialLock::unlock(); } static const char* phaseName(uint8_t p) { switch (p) { case LINK_OTA_CHECKING: return "checking"; case LINK_OTA_UP_TO_DATE: return "up to date"; case LINK_OTA_AVAILABLE: return "update available"; case LINK_OTA_INSTALLING: return "installing"; case LINK_OTA_FAILED: return "failed"; default: return "idle"; } } // ---- NVS -------------------------------------------------------------------- static void loadKey() { Preferences p; p.begin(NVS_LINK, true); g_paired = p.getBytesLength("key") == LINK_KEY_LEN; if (g_paired) p.getBytes("key", g_key, LINK_KEY_LEN); p.end(); g_key_fp = g_paired ? link_key_fingerprint(g_key) : 0; } static void storeKey() { Preferences p; p.begin(NVS_LINK, false); p.putBytes("key", g_key, LINK_KEY_LEN); p.end(); } static void clearKey() { Preferences p; p.begin(NVS_LINK, false); p.clear(); p.end(); g_paired = false; g_key_fp = 0; memset(g_key, 0, sizeof(g_key)); } // ---- inbound (Wi-Fi task) --------------------------------------------------- static void onFrame(const uint8_t mac[6], const uint8_t* frame, size_t len) { uint8_t type = 0, plen = 0; const uint8_t* payload = NULL; if (frame_parse(frame, len, &type, &payload, &plen) != FRAME_OK) return; if (type != PACKET_TYPE_STATUS) return; if (xSemaphoreTake(g_mutex, pdMS_TO_TICKS(10)) != pdTRUE) return; memcpy(&g_st, payload, sizeof(g_st)); g_st.version[sizeof(g_st.version) - 1] = 0; g_st.latest[sizeof(g_st.latest) - 1] = 0; g_st.message[sizeof(g_st.message) - 1] = 0; memcpy(g_b_mac, mac, 6); g_last_status_ms = millis(); g_ever_heard = true; g_status_count++; xSemaphoreGive(g_mutex); } // ---- public: status --------------------------------------------------------- peer_status_t getStatus() { peer_status_t p = {}; lock(); p.st = g_st; memcpy(p.mac, g_b_mac, 6); uint32_t last = g_last_status_ms; bool ever = g_ever_heard; unlock(); p.age_ms = ever ? millis() - last : 0xFFFFFFFF; p.heard = ever && p.age_ms < LINK_STATUS_TIMEOUT_MS; p.paired = g_paired; p.key_fp = g_key_fp; p.key_match = g_paired && p.st.key_fp == g_key_fp; return p; } // ---- outbound --------------------------------------------------------------- static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) { peer_status_t p = getStatus(); if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard"); return false; } if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; } if (!p.key_match) { snprintf(why, n, "Inst. Cluster holds a different key - run `link pair` again"); return false; } uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE]; size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload); if (!plen) { snprintf(why, n, "encryption failed"); return false; } size_t flen = frame_build(PACKET_TYPE_SECURE, payload, (uint8_t)plen, frame); if (!flen || !EspNowLink::sendTo(p.mac, frame, flen)) { g_secure_fail++; snprintf(why, n, "ESP-NOW send failed"); return false; } g_secure_sent++; return true; } static bool sendOtaCmd(uint8_t cmd, uint8_t flags, char* why, size_t n) { link_ota_cmd_t c = {}; c.cmd = cmd; c.flags = flags; c.nonce = esp_random(); return sendSecure(LINK_INNER_OTA_CMD, &c, sizeof(c), why, n); } static uint32_t hashStr(uint32_t h, const char* s) { for (; *s; s++) h = (h ^ (uint8_t)*s) * 16777619u; // FNV-1a return h; } /** Push A's remembered network (or a FORGET) to B. */ static bool pushCredentials(char* why, size_t n, bool log) { link_wifi_creds_t c = {}; char pass[65]; bool have = WiFiManager::getSavedCredentials(c.ssid, sizeof(c.ssid), pass, sizeof(pass)); if (have) { c.action = LINK_WIFI_SET; strlcpy(c.pass, pass, sizeof(c.pass)); } else { c.action = LINK_WIFI_FORGET; } bool ok = sendSecure(LINK_INNER_WIFI_CREDS, &c, sizeof(c), why, n); memset(pass, 0, sizeof(pass)); if (ok) { g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1; g_last_push_ms = millis(); if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Inst. Cluster (encrypted)" : "[link] told Inst. Cluster to forget its Wi-Fi credentials", c.ssid); } memset(&c, 0, sizeof(c)); return ok; } // B lacks credentials A has, or A's changed, or A forgot them while B still has them. static void syncCredentials() { peer_status_t p = getStatus(); if (!p.heard || !p.paired || !p.key_match) return; if (millis() - g_last_push_ms < CREDS_PUSH_MIN_MS && g_last_push_ms != 0) return; char ssid[33], pass[65]; bool have = WiFiManager::getSavedCredentials(ssid, sizeof(ssid), pass, sizeof(pass)); uint32_t h = have ? hashStr(hashStr(2166136261u, ssid), pass) : 1; memset(pass, 0, sizeof(pass)); bool b_has = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0; bool need = have ? (!b_has || h != g_pushed_hash) : (b_has && g_pushed_hash != 1); if (!need) return; char why[64]; pushCredentials(why, sizeof(why), true); } // ---- pairing ---------------------------------------------------------------- static bool pair(char* why, size_t n) { if (UARTManager::getState() == UARTManager::UART_STATE_OFF) { snprintf(why, n, "link is off - enable 'Send to Inst. Cluster' in Settings first"); return false; } link_pair_t pk = {}; pk.magic = LINK_PAIR_MAGIC; esp_fill_random(pk.key, LINK_KEY_LEN); esp_wifi_get_mac(WIFI_IF_STA, pk.a_mac); uint8_t frame[PACKET_MAX_SIZE]; size_t flen = frame_build(PACKET_TYPE_PAIR, &pk, sizeof(pk), frame); int sent = 0; for (int i = 0; i < PAIR_REPEATS; i++) { if (UARTManager::sendWire(frame, flen)) sent++; delay(40); } if (!sent) { snprintf(why, n, "UART write failed"); memset(&pk, 0, sizeof(pk)); return false; } memcpy(g_key, pk.key, LINK_KEY_LEN); memset(&pk, 0, sizeof(pk)); g_paired = true; g_key_fp = link_key_fingerprint(g_key); storeKey(); g_pushed_hash = 0; // re-send the credentials under the new key g_last_push_ms = 0; print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. " "Inst. Cluster confirms in its next STATUS (`link status`).", sent, g_key_fp); return true; } // ---- public: requests (UI) -------------------------------------------------- static bool bReady(char* why, size_t n, bool need_parked) { peer_status_t p = getStatus(); if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard - is it powered?"); return false; } if (!p.paired || !p.key_match) { snprintf(why, n, "Inst. Cluster is not paired with this controller (console: link pair, wire connected)"); return false; } if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) { snprintf(why, n, "Inst. Cluster has no Wi-Fi credentials yet - join a network on this screen first"); return false; } if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) { snprintf(why, n, "Inst. Cluster is busy (%s)", phaseName(p.st.ota_phase)); return false; } if (need_parked && !Ota::isParked(why, n)) return false; // Same network as B => same radio channel, so B's STATUS frames (progress) // keep reaching this screen while B is joined. if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) { snprintf(why, n, "join Wi-Fi on this controller first, so Inst. Cluster's progress can be followed"); return false; } return true; } bool requestCheck(char* why, size_t n) { if (!bReady(why, n, false)) { print("[link] check refused: %s", why); return false; } return sendOtaCmd(LINK_OTA_CMD_CHECK, 0, why, n); } bool requestInstall(char* why, size_t n) { if (!bReady(why, n, true)) { print("[link] install refused: %s", why); return false; } return sendOtaCmd(LINK_OTA_CMD_INSTALL, 0, why, n); } // ---- lifecycle -------------------------------------------------------------- void init() { if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex(); loadKey(); EspNowLink::setReceiveHandler(onFrame); print("[link] Inst. Cluster: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected"); } void tick() { static uint32_t last = 0; static bool was_heard = false; static uint8_t last_phase = 0xFF; static bool was_match = false; if (millis() - last < 1000) return; last = millis(); peer_status_t p = getStatus(); if (p.heard != was_heard) { was_heard = p.heard; if (p.heard) print("[link] Inst. Cluster heard: %s, %s, %lu s up", p.st.version, p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"), (unsigned long)p.st.uptime_s); else print("[link] Inst. Cluster silent for %lu s", (unsigned long)(p.age_ms / 1000)); } if (p.heard && p.key_match && !was_match) { print("[link] Inst. Cluster confirmed pairing (fingerprint %04X)", p.st.key_fp); } was_match = p.heard && p.key_match; if (p.heard && p.st.ota_phase != last_phase) { if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE) print("[link] Inst. Cluster update: %s%s%s%s%s", phaseName(p.st.ota_phase), p.st.latest[0] ? ", latest " : "", p.st.latest, p.st.ota_phase == LINK_OTA_FAILED ? " - " : "", p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : ""); last_phase = p.st.ota_phase; } syncCredentials(); } // ---- console ---------------------------------------------------------------- static void help() { print("link status Inst. Cluster: version, pairing, update phase"); print("link pair new shared key -> B over the UART wire (bench, wire connected)"); print("link unpair forget the key here (B keeps its own until re-paired)"); print("link creds send the remembered Wi-Fi network to B now"); print("link ota check|install [force]|rollback drive B's updater"); } bool handleCommand(const char* line) { if (strncmp(line, "link", 4) != 0 || (line[4] != 0 && line[4] != ' ')) return false; const char* a = line + 4; while (*a == ' ') a++; char why[96] = ""; if (!*a || !strcmp(a, "help")) { help(); return true; } if (!strcmp(a, "status")) { peer_status_t p = getStatus(); print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu", p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count, (unsigned long)g_secure_sent, (unsigned long)g_secure_fail); if (!g_ever_heard) { print("[link] Inst. Cluster never heard"); return true; } print("[link] Inst. Cluster %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)", p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5], p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000)); print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s", p.st.version, p.st.key_fp, p.key_match ? "matches" : p.st.key_fp ? "DIFFERENT" : "none", (p.st.flags & LINK_STATUS_HAVE_WIFI) ? "yes" : "no", (p.st.flags & LINK_STATUS_WIFI_JOINED) ? ", joined" : "", (p.st.flags & LINK_STATUS_PENDING_VERIFY) ? " | fresh image, unconfirmed" : ""); print("[link] update: %s%s%s%s%s | up %lu s | heap %lu", phaseName(p.st.ota_phase), p.st.latest[0] ? ", latest " : "", p.st.latest, p.st.message[0] ? " - " : "", p.st.message, (unsigned long)p.st.uptime_s, (unsigned long)p.st.free_heap); return true; } if (!strcmp(a, "pair")) { if (!pair(why, sizeof(why))) print("[link] pair refused: %s", why); return true; } if (!strcmp(a, "unpair")) { clearKey(); print("[link] pairing key removed here"); return true; } if (!strcmp(a, "creds")) { if (!pushCredentials(why, sizeof(why), true)) print("[link] creds refused: %s", why); return true; } if (!strncmp(a, "ota", 3)) { const char* b = a + 3; while (*b == ' ') b++; bool ok = false; if (!strcmp(b, "check")) ok = requestCheck(why, sizeof(why)); else if (!strcmp(b, "install")) ok = requestInstall(why, sizeof(why)); else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why)); else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why)); else { help(); return true; } print(ok ? "[link] command sent to Inst. Cluster - watch `link status`" : "[link] refused: %s", why); return true; } help(); return true; } } // namespace LinkPeer