Controller B OTA: link_peer (STATUS to A, PAIR from the wire, AES-GCM SECURE frames), updater ported from A, console, CI workflow, shared header v2 maintenance frames; wiki + docs
Firmware / build (push) Successful in 2m57s

This commit is contained in:
2026-09-27 20:26:40 +02:00
parent 30ab113218
commit e6773c73ba
24 changed files with 1805 additions and 57 deletions
+15 -1
View File
@@ -14,6 +14,10 @@
#include "modules/gauge_outputs.h"
#include "modules/debug_monitor.h"
#include "modules/gauge_screen.h"
#include "modules/link_peer.h"
#include "modules/console.h"
#include "modules/ota_update.h"
#include "config/ota_config.h"
// FreeRTOS task handles
TaskHandle_t lvglTaskHandle = NULL;
@@ -47,7 +51,7 @@ void setup() {
Serial.println("[BOOT] Serial communication ready!");
Serial.println("\n\n=================================");
Serial.println("ESP32-S3-LCD-1.3 - Controller B");
Serial.printf("Link protocol v%u | UART + ESP-NOW | gauge outputs\n", PACKET_VERSION);
Serial.printf("Firmware %s | Link protocol v%u | UART + ESP-NOW | gauge outputs\n", FW_VERSION, PACKET_VERSION);
Serial.println("=================================\n");
Serial.printf("CPU Frequency: %d MHz\n", getCpuFrequencyMhz());
@@ -74,6 +78,12 @@ void setup() {
Serial.println("\n[Gauges] Initializing Patrol gauge outputs...");
GaugeOutputs::init();
// Pairing key + Wi-Fi credentials from NVS, before any frame can arrive
LinkPeer::init();
Ota::init(); // version + slot; hooks A's OTA commands
Console::addHandler(LinkPeer::handleCommand);
Console::addHandler(Ota::handleCommand);
Serial.println("\n[UART] Initializing link receiver...");
if (!UARTReceiver::init()) {
Serial.println("[ERROR] Link receiver initialization failed!");
@@ -100,6 +110,10 @@ void loop() {
// Wireless leg housekeeping (channel hopping while silent)
EspNowReceiver::tick();
// STATUS to A, PAIR/SECURE frames from A, serial console
LinkPeer::tick();
Ota::tick(); // runs a queued check/install (blocks the loop while it does)
Console::tick();
// Apply a new CONFIG from A. Overrides are a bench tool: applied but not
// persisted, so a reboot never leaves the gauges pinned to a test value.
+46
View File
@@ -0,0 +1,46 @@
/**
* Serial console implementation (Controller B)
*/
#include "modules/console.h"
namespace Console {
static handler_t g_handlers[8];
static int g_count = 0;
static char g_line[96];
static size_t g_len = 0;
void addHandler(handler_t h) {
if (g_count < 8) g_handlers[g_count++] = h;
}
static void dispatch(const char* line) {
if (line[0] == 0) return;
if (strcmp(line, "help") == 0) {
Serial.println("[console] commands:");
for (int i = 0; i < g_count; i++) g_handlers[i](line); // each prints its own lines
return;
}
for (int i = 0; i < g_count; i++) {
if (g_handlers[i](line)) return;
}
Serial.printf("[console] unknown command '%s' (try 'help')\n", line);
}
void tick() {
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\r' || c == '\n') {
g_line[g_len] = 0;
// trim trailing spaces
while (g_len && g_line[g_len - 1] == ' ') g_line[--g_len] = 0;
dispatch(g_line);
g_len = 0;
} else if (g_len < sizeof(g_line) - 1 && c >= ' ') {
g_line[g_len++] = c;
}
}
}
} // namespace Console
+39 -4
View File
@@ -4,6 +4,7 @@
#include "modules/espnow_receiver.h"
#include "modules/uart_receiver.h"
#include "modules/link_peer.h"
#include "protocol/automotive_data.h"
#include <WiFi.h>
#include <esp_wifi.h>
@@ -22,12 +23,24 @@ static uint8_t g_channel = ESPNOW_CHANNEL;
static uint32_t g_last_hop_ms = 0;
static bool g_locked = false;
// A's STA MAC as seen on the last DATA/CONFIG frame: where STATUS frames go.
static uint8_t g_peer_mac[6] = {0};
static volatile bool g_have_peer = false;
static void onReceive(const uint8_t* mac, const uint8_t* data, int len) {
(void)mac;
if (len <= 0) return;
g_frames++;
g_last_frame_ms = millis();
UARTReceiver::processFrame(data, (size_t)len, LINK_SOURCE_ESPNOW);
// Byte 2 is the type; the data path only wants DATA/CONFIG, everything
// else (SECURE from A) is the link peer's. Both validate the frame themselves.
uint8_t type = len > 2 ? data[2] : 0;
if (type == PACKET_TYPE_DATA || type == PACKET_TYPE_CONFIG) {
g_frames++;
g_last_frame_ms = millis();
memcpy(g_peer_mac, mac, 6);
g_have_peer = true;
UARTReceiver::processFrame(data, (size_t)len, LINK_SOURCE_ESPNOW);
} else {
LinkPeer::onRadioFrame(mac, data, (size_t)len);
}
}
static void setChannel(uint8_t ch) {
@@ -87,4 +100,26 @@ bool isReady() { return g_ready; }
uint8_t currentChannel() { return g_channel; }
uint32_t framesReceived() { return g_frames; }
bool peerMac(uint8_t out[6]) {
if (!g_have_peer) return false;
memcpy(out, g_peer_mac, 6);
return true;
}
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) {
if (!g_ready || len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
if (!esp_now_is_peer_exist(mac)) {
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, mac, 6);
peer.channel = 0; // whatever channel we are locked on
peer.encrypt = false; // SECURE frames carry their own encryption
peer.ifidx = WIFI_IF_STA;
if (esp_now_add_peer(&peer) != ESP_OK) {
Serial.println("[EspNow] esp_now_add_peer(A) failed");
return false;
}
}
return esp_now_send(mac, frame, len) == ESP_OK;
}
} // namespace EspNowReceiver
+26
View File
@@ -25,6 +25,7 @@ struct Cell {
};
static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_notice = NULL; // on lv_layer_top(): update progress line
static Cell g_coolant = {0};
static Cell g_gearbox = {0};
static Cell g_battery = {0};
@@ -196,11 +197,36 @@ void init() {
lv_obj_t* bottom = makeContainer(g_screen, 230, 85, LV_FLEX_FLOW_ROW, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END);
makeCell(g_battery, bottom, &ui_img_batteryvoltage_png, &ui_img_batteryvoltagered_png, LV_FLEX_ALIGN_CENTER, true);
// Notice line for the updater: a dark pill low on the round panel, hidden until used.
g_notice = lv_label_create(lv_layer_top());
lv_obj_set_style_text_font(g_notice, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_notice, lv_color_white(), 0);
lv_obj_set_style_bg_color(g_notice, lv_color_hex(0x1B2128), 0);
lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0);
lv_obj_set_style_pad_hor(g_notice, 10, 0);
lv_obj_set_style_pad_ver(g_notice, 4, 0);
lv_obj_set_style_radius(g_notice, 8, 0);
lv_obj_align(g_notice, LV_ALIGN_CENTER, 0, 62);
lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
lv_scr_load(g_screen);
DisplayInit::unlock();
Serial.println("[GaugeScreen] built (coolant, gearbox oil, gear, battery)");
}
void setNotice(const char* text) {
if (g_notice == NULL) return;
DisplayInit::lock(-1);
if (text == NULL || text[0] == 0) {
lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
} else {
setText(g_notice, text);
lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
lv_obj_align(g_notice, LV_ALIGN_CENTER, 0, 62);
}
DisplayInit::unlock();
}
void update(const automotive_data_t& d, bool link_ok) {
if (g_screen == NULL) return;
if (!DisplayInit::lock(50)) return; // never stall the loop on a busy renderer
+6
View File
@@ -35,4 +35,10 @@ void init();
*/
void update(const automotive_data_t& d, bool link_ok);
/**
* One line of text over the gauges (firmware update progress). NULL hides it.
* Takes the LVGL lock itself; safe from the loop task.
*/
void setNotice(const char* text);
} // namespace GaugeScreen
+359
View File
@@ -0,0 +1,359 @@
/**
* Link Peer Module Implementation (Controller B)
*
* Threading: onRadioFrame() runs in the Wi-Fi task, onPairFrame() in the UART
* task. Both only drop a copy into a one-slot mailbox; tick() (loop task) does
* the decrypting, the NVS writes and the STATUS transmit.
*/
#include "modules/link_peer.h"
#include "modules/espnow_receiver.h"
#include "protocol/link_secure.h"
#include "config/ota_config.h"
#include <Preferences.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace LinkPeer {
static const char* NVS_LINK = "linkpeer"; // key (32 B), amac (6 B)
static const char* NVS_WIFI = "wifi"; // ssid, pass - same layout as Controller A's
// ---- state (loop task only, except where noted) ----------------------------
static bool g_paired = false;
static uint8_t g_key[LINK_KEY_LEN];
static uint8_t g_a_mac[6];
static uint16_t g_key_fp = 0;
static char g_ssid[33] = "";
static char g_pass[65] = "";
static uint8_t g_ota_phase = LINK_OTA_IDLE, g_ota_progress = 0;
static char g_latest[16] = "", g_message[32] = "";
static bool g_wifi_joined = false, g_pending_verify = false;
static ota_cmd_handler_t g_ota_handler = NULL;
static uint32_t g_recent_nonce[4] = {0};
static uint8_t g_nonce_idx = 0;
static uint32_t g_status_sent = 0, g_status_fail = 0;
static uint32_t g_secure_ok = 0, g_secure_bad = 0, g_secure_stranger = 0, g_mailbox_drops = 0;
static uint32_t g_last_status_ms = 0;
static bool g_status_now = false;
static bool g_ota_cmd_seen_unhandled = false;
// ---- mailboxes filled from other tasks --------------------------------------
static SemaphoreHandle_t g_mbox_mutex = NULL;
static struct {
bool full;
uint8_t mac[6];
uint8_t frame[PACKET_MAX_SIZE];
size_t len;
} g_radio_mbox = {0};
static struct {
bool full;
link_pair_t pair;
} g_pair_mbox = {0};
static bool mboxLock() { return xSemaphoreTake(g_mbox_mutex, pdMS_TO_TICKS(20)) == pdTRUE; }
static void mboxUnlock() { xSemaphoreGive(g_mbox_mutex); }
// ---- NVS --------------------------------------------------------------------
static void loadPairing() {
Preferences p;
p.begin(NVS_LINK, true);
bool ok = p.getBytesLength("key") == LINK_KEY_LEN && p.getBytesLength("amac") == 6;
if (ok) {
p.getBytes("key", g_key, LINK_KEY_LEN);
p.getBytes("amac", g_a_mac, 6);
}
p.end();
g_paired = ok;
g_key_fp = ok ? link_key_fingerprint(g_key) : 0;
}
static void storePairing() {
Preferences p;
p.begin(NVS_LINK, false);
p.putBytes("key", g_key, LINK_KEY_LEN);
p.putBytes("amac", g_a_mac, 6);
p.end();
}
static void loadWifi() {
Preferences p;
p.begin(NVS_WIFI, true);
String s = p.getString("ssid", ""), w = p.getString("pass", "");
p.end();
strlcpy(g_ssid, s.c_str(), sizeof(g_ssid));
strlcpy(g_pass, w.c_str(), sizeof(g_pass));
}
static void storeWifi(const char* ssid, const char* pass) {
Preferences p;
p.begin(NVS_WIFI, false);
p.putString("ssid", ssid);
p.putString("pass", pass);
p.end();
strlcpy(g_ssid, ssid, sizeof(g_ssid));
strlcpy(g_pass, pass, sizeof(g_pass));
}
static void clearNamespace(const char* ns) {
Preferences p;
p.begin(ns, false);
p.clear();
p.end();
}
// ---- public: state ----------------------------------------------------------
void init() {
if (g_mbox_mutex == NULL) g_mbox_mutex = xSemaphoreCreateMutex();
loadPairing();
loadWifi();
Serial.printf("[LinkPeer] %s | Wi-Fi credentials %s | reporting as %s\n",
g_paired ? "paired with A" : "NOT paired (run `link pair` on A over the wire)",
g_ssid[0] ? "stored" : "none", FW_VERSION);
if (g_paired) {
Serial.printf("[LinkPeer] key fingerprint %04X, A = %02X:%02X:%02X:%02X:%02X:%02X\n", g_key_fp,
g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]);
}
}
bool isPaired() { return g_paired; }
uint16_t keyFingerprint(){ return g_key_fp; }
bool hasWifiCredentials(){ return g_ssid[0] != 0; }
bool getWifiCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) {
if (!g_ssid[0]) return false;
strlcpy(ssid, g_ssid, ssid_n);
strlcpy(pass, g_pass, pass_n);
return true;
}
void forgetWifi() {
clearNamespace(NVS_WIFI);
g_ssid[0] = 0;
memset(g_pass, 0, sizeof(g_pass));
g_status_now = true;
Serial.println("[LinkPeer] Wi-Fi credentials forgotten");
}
void unpair() {
clearNamespace(NVS_LINK);
g_paired = false;
g_key_fp = 0;
memset(g_key, 0, sizeof(g_key));
g_status_now = true;
Serial.println("[LinkPeer] Pairing removed - A must `link pair` again over the wire");
}
void setOtaCommandHandler(ota_cmd_handler_t handler) { g_ota_handler = handler; }
void setOtaStatus(uint8_t phase, uint8_t progress, const char* latest, const char* message,
bool wifi_joined, bool pending_verify) {
bool changed = phase != g_ota_phase || wifi_joined != g_wifi_joined ||
strcmp(latest ? latest : "", g_latest) != 0;
g_ota_phase = phase;
g_ota_progress = progress;
strlcpy(g_latest, latest ? latest : "", sizeof(g_latest));
strlcpy(g_message, message ? message : "", sizeof(g_message));
g_wifi_joined = wifi_joined;
g_pending_verify = pending_verify;
if (changed) g_status_now = true; // A sees phase changes without waiting for the period
}
// ---- inbound (other tasks) --------------------------------------------------
void onRadioFrame(const uint8_t* mac, const uint8_t* frame, size_t len) {
if (len == 0 || len > PACKET_MAX_SIZE || g_mbox_mutex == NULL) return;
if (!mboxLock()) { g_mailbox_drops++; return; }
if (g_radio_mbox.full) g_mailbox_drops++; // loop hasn't consumed the last one; newest wins
memcpy(g_radio_mbox.mac, mac, 6);
memcpy(g_radio_mbox.frame, frame, len);
g_radio_mbox.len = len;
g_radio_mbox.full = true;
mboxUnlock();
}
void onPairFrame(const link_pair_t* p) {
if (g_mbox_mutex == NULL) return;
if (!mboxLock()) { g_mailbox_drops++; return; }
g_pair_mbox.pair = *p;
g_pair_mbox.full = true;
mboxUnlock();
}
// ---- loop-side processing ---------------------------------------------------
static void applyPair(const link_pair_t& p) {
if (p.magic != LINK_PAIR_MAGIC) {
Serial.println("[LinkPeer] PAIR frame with bad magic ignored");
return;
}
bool same = g_paired && memcmp(p.key, g_key, LINK_KEY_LEN) == 0 && memcmp(p.a_mac, g_a_mac, 6) == 0;
memcpy(g_key, p.key, LINK_KEY_LEN);
memcpy(g_a_mac, p.a_mac, 6);
g_paired = true;
g_key_fp = link_key_fingerprint(g_key);
if (!same) storePairing(); // A sends PAIR a few times for robustness; write NVS once
g_status_now = true;
Serial.printf("[LinkPeer] %s over the wire: key fingerprint %04X, A = %02X:%02X:%02X:%02X:%02X:%02X\n",
same ? "Pairing re-confirmed" : "PAIRED", g_key_fp,
g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]);
}
static bool nonceSeen(uint32_t n) {
for (int i = 0; i < 4; i++) if (g_recent_nonce[i] == n) return true;
g_recent_nonce[g_nonce_idx] = n;
g_nonce_idx = (uint8_t)((g_nonce_idx + 1) % 4);
return false;
}
static void applySecure(const uint8_t* mac, 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) { g_secure_bad++; return; }
if (type != PACKET_TYPE_SECURE) return; // STATUS is ours to send, not to receive
if (!g_paired) {
g_secure_bad++;
Serial.println("[LinkPeer] SECURE frame but not paired - ignored");
return;
}
if (memcmp(mac, g_a_mac, 6) != 0) { g_secure_stranger++; return; }
uint8_t inner_type = 0, inner[LINK_SECURE_MAX_INNER];
size_t inner_len = 0;
if (!link_secure_open(g_key, payload, plen, &inner_type, inner, &inner_len)) {
g_secure_bad++;
if (g_secure_bad <= 3 || g_secure_bad % 20 == 0)
Serial.printf("[LinkPeer] SECURE frame failed to authenticate (%lu so far) - keys differ? re-pair\n",
(unsigned long)g_secure_bad);
return;
}
g_secure_ok++;
if (inner_type == LINK_INNER_WIFI_CREDS && inner_len == sizeof(link_wifi_creds_t)) {
link_wifi_creds_t c;
memcpy(&c, inner, sizeof(c));
c.ssid[sizeof(c.ssid) - 1] = 0;
c.pass[sizeof(c.pass) - 1] = 0;
if (c.action == LINK_WIFI_SET && c.ssid[0]) {
bool same = strcmp(c.ssid, g_ssid) == 0 && strcmp(c.pass, g_pass) == 0;
if (!same) storeWifi(c.ssid, c.pass);
g_status_now = true;
Serial.printf("[LinkPeer] Wi-Fi credentials for '%s' %s\n", c.ssid, same ? "re-confirmed" : "stored");
} else if (c.action == LINK_WIFI_FORGET) {
if (g_ssid[0]) forgetWifi();
}
return;
}
if (inner_type == LINK_INNER_OTA_CMD && inner_len == sizeof(link_ota_cmd_t)) {
link_ota_cmd_t cmd;
memcpy(&cmd, inner, sizeof(cmd));
if (nonceSeen(cmd.nonce)) { Serial.println("[LinkPeer] OTA command replayed - ignored"); return; }
const char* name = cmd.cmd == LINK_OTA_CMD_CHECK ? "check" : cmd.cmd == LINK_OTA_CMD_INSTALL ? "install"
: cmd.cmd == LINK_OTA_CMD_ROLLBACK ? "rollback" : "?";
Serial.printf("[LinkPeer] OTA command from A: %s%s\n", name, (cmd.flags & LINK_OTA_FORCE) ? " (force)" : "");
if (g_ota_handler) g_ota_handler(cmd.cmd, cmd.flags);
else g_ota_cmd_seen_unhandled = true;
return;
}
Serial.printf("[LinkPeer] SECURE inner type 0x%02X len %u not understood\n", inner_type, (unsigned)inner_len);
}
static void sendStatus() {
uint8_t mac[6];
bool have = EspNowReceiver::peerMac(mac); // A as heard on the radio
if (!have && g_paired) { memcpy(mac, g_a_mac, 6); have = true; }
if (!have) return; // never heard A on the radio, nothing to aim at
link_status_t st = {};
strlcpy(st.version, FW_VERSION, sizeof(st.version));
st.ota_phase = g_ota_phase;
st.ota_progress = g_ota_progress;
st.flags = (g_paired ? LINK_STATUS_PAIRED : 0) |
(g_ssid[0] ? LINK_STATUS_HAVE_WIFI : 0) |
(g_wifi_joined ? LINK_STATUS_WIFI_JOINED : 0) |
(g_pending_verify ? LINK_STATUS_PENDING_VERIFY : 0);
st.key_fp = g_key_fp;
st.uptime_s = millis() / 1000;
st.free_heap = ESP.getFreeHeap();
strlcpy(st.latest, g_latest, sizeof(st.latest));
strlcpy(st.message, g_message, sizeof(st.message));
uint8_t frame[PACKET_MAX_SIZE];
size_t n = frame_build(PACKET_TYPE_STATUS, &st, sizeof(st), frame);
if (n && EspNowReceiver::sendTo(mac, frame, n)) g_status_sent++;
else g_status_fail++;
}
void tick() {
if (g_mbox_mutex == NULL) return;
// Drain the mailboxes (copy out under the lock, work outside it)
bool have_pair = false, have_radio = false;
link_pair_t pair;
uint8_t mac[6], frame[PACKET_MAX_SIZE];
size_t len = 0;
if (mboxLock()) {
if (g_pair_mbox.full) { pair = g_pair_mbox.pair; g_pair_mbox.full = false; have_pair = true; }
if (g_radio_mbox.full) {
memcpy(mac, g_radio_mbox.mac, 6);
len = g_radio_mbox.len;
memcpy(frame, g_radio_mbox.frame, len);
g_radio_mbox.full = false;
have_radio = true;
}
mboxUnlock();
}
if (have_pair) applyPair(pair);
if (have_radio) applySecure(mac, frame, len);
uint32_t now = millis();
if (g_status_now || now - g_last_status_ms >= LINK_STATUS_PERIOD_MS) {
g_status_now = false;
g_last_status_ms = now;
sendStatus();
}
}
// ---- console ----------------------------------------------------------------
static void help() {
Serial.println("link status pairing, credentials, STATUS/SECURE counters");
Serial.println("link unpair forget the pairing key (re-pair from A over the wire)");
Serial.println("wifi status stored network name (password never shown)");
Serial.println("wifi forget drop the stored credentials");
}
bool handleCommand(const char* line) {
if (strcmp(line, "help") == 0) { help(); return false; } // let the others print theirs too
if (strcmp(line, "link status") == 0) {
uint8_t mac[6];
bool heard = EspNowReceiver::peerMac(mac);
Serial.printf("[link] %s (fingerprint %04X)\n", g_paired ? "paired" : "NOT paired", g_key_fp);
if (g_paired)
Serial.printf("[link] A (from pairing) %02X:%02X:%02X:%02X:%02X:%02X\n",
g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]);
if (heard)
Serial.printf("[link] A (on the radio) %02X:%02X:%02X:%02X:%02X:%02X, channel %u\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], EspNowReceiver::currentChannel());
else
Serial.println("[link] A not heard on the radio yet (STATUS cannot be sent)");
Serial.printf("[link] STATUS sent %lu, failed %lu | SECURE ok %lu, bad %lu, from strangers %lu | mailbox drops %lu\n",
(unsigned long)g_status_sent, (unsigned long)g_status_fail,
(unsigned long)g_secure_ok, (unsigned long)g_secure_bad,
(unsigned long)g_secure_stranger, (unsigned long)g_mailbox_drops);
Serial.printf("[link] Wi-Fi credentials: %s | OTA phase %u%s\n", g_ssid[0] ? g_ssid : "none",
g_ota_phase, g_ota_handler ? "" : " (no updater module linked in)");
return true;
}
if (strcmp(line, "link unpair") == 0) { unpair(); return true; }
if (strcmp(line, "wifi status") == 0) {
Serial.printf("[wifi] stored network: %s\n", g_ssid[0] ? g_ssid : "none (A sends it once paired)");
return true;
}
if (strcmp(line, "wifi forget") == 0) { forgetWifi(); return true; }
if (strncmp(line, "link", 4) == 0 || strncmp(line, "wifi", 4) == 0) { help(); return true; }
return false;
}
} // namespace LinkPeer
+607
View File
@@ -0,0 +1,607 @@
/**
* ota_update.cpp (Controller B) - see ota_update.h.
*
* Flow of an install:
* 1. gate: parked (link data), credentials present
* 2. join Wi-Fi with the credentials A handed over
* 3. GET /api/v1/repos/<repo>/releases/latest -> tag_name
* 4. GET manifest.txt; verify ECDSA P-256 over "target|version|sha256"
* 5. GET firmware.bin -> idle OTA slot, hashing as it streams
* 6. esp_ota_end(), gate again, switch boot slot, reboot
* 7. next boot: PENDING_VERIFY until tick() confirms after OTA_CONFIRM_MS
*
* Jobs run inside the Arduino loop task, like on A: the gauges freeze (parked
* anyway) and STATUS frames to A are pumped from the download loop so A's
* Updates screen shows the progress.
*
* Differences from A's module: no CAN gate (link data instead), no Tunables,
* a one-line notice on the 240x240 screen instead of a full-screen panel,
* mbedtls 2.28 names (IDF 4.4), and mbedtls may use internal RAM (235 KB free).
*/
#include "modules/ota_update.h"
#include "modules/link_peer.h"
#include "modules/uart_receiver.h"
#include "modules/gauge_screen.h"
#include "modules/gauge_outputs.h"
#include "modules/espnow_receiver.h"
#include "protocol/automotive_data.h"
#include "config/ota_config.h"
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#include <mbedtls/sha256.h>
#include <mbedtls/pk.h>
#include <mbedtls/version.h>
#include <stdarg.h>
// Arduino marks a new image valid before setup() runs unless this says no.
extern "C" bool verifyRollbackLater() { return true; }
#if MBEDTLS_VERSION_MAJOR >= 3
#define SHA256_ONESHOT(in, n, out) mbedtls_sha256((in), (n), (out), 0)
#define SHA256_STARTS(c) mbedtls_sha256_starts((c), 0)
#define SHA256_UPDATE(c, d, n) mbedtls_sha256_update((c), (d), (n))
#define SHA256_FINISH(c, o) mbedtls_sha256_finish((c), (o))
#else
#define SHA256_ONESHOT(in, n, out) mbedtls_sha256_ret((in), (n), (out), 0)
#define SHA256_STARTS(c) mbedtls_sha256_starts_ret((c), 0)
#define SHA256_UPDATE(c, d, n) mbedtls_sha256_update_ret((c), (d), (n))
#define SHA256_FINISH(c, o) mbedtls_sha256_finish_ret((c), (o))
#endif
namespace Ota {
static const uint32_t LINK_SILENT_MS = 2000; // no DATA for this long = A off / bench
static const uint32_t WIFI_JOIN_MS = 25000;
static const uint32_t STALL_TIMEOUT_MS = 15000;
static const size_t CHUNK = 4096;
typedef struct {
char tag[32];
char target[16];
char version[32];
uint32_t size;
char sha256[65];
uint8_t sig[80];
size_t sig_len;
} manifest_t;
enum job_t { JOB_NONE, JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE, JOB_ROLLBACK };
static job_t g_job = JOB_NONE;
static bool g_pending_verify = false;
static bool g_wifi_joined = false;
static uint8_t g_phase = LINK_OTA_IDLE, g_progress = 0;
static char g_latest[16] = "", g_message[32] = "", g_last_msg[96] = "";
static uint32_t g_last_pump_ms = 0;
// ---- logging / status reported to A ----------------------------------------
static void report() {
LinkPeer::setOtaStatus(g_phase, g_progress, g_latest, g_message, g_wifi_joined, g_pending_verify);
}
static void setPhase(uint8_t p, const char* latest = NULL, const char* msg = NULL) {
g_phase = p;
if (latest) strlcpy(g_latest, latest, sizeof(g_latest));
strlcpy(g_message, msg ? msg : "", sizeof(g_message));
if (p != LINK_OTA_INSTALLING) g_progress = 0;
report();
}
static void print(const char* fmt, ...) {
char buf[220];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
Serial.println(buf);
const char* m = strncmp(buf, "[ota] ", 6) == 0 ? buf + 6 : buf;
strlcpy(g_last_msg, m, sizeof(g_last_msg));
}
static void failPhase() { setPhase(LINK_OTA_FAILED, NULL, g_last_msg); }
/** Keep A informed while the loop is blocked in a job (rate-limited to 1/s). */
static void pump(bool force = false) {
if (!force && millis() - g_last_pump_ms < 1000) return;
g_last_pump_ms = millis();
report();
LinkPeer::tick();
}
static const char* stateName(esp_ota_img_states_t s) {
switch (s) {
case ESP_OTA_IMG_NEW: return "new";
case ESP_OTA_IMG_PENDING_VERIFY: return "pending-verify";
case ESP_OTA_IMG_VALID: return "valid";
case ESP_OTA_IMG_INVALID: return "invalid";
case ESP_OTA_IMG_ABORTED: return "aborted";
default: return "undefined";
}
}
// ---- gates -----------------------------------------------------------------
/** Parked according to the link data; a silent link (A off) counts as parked. */
static bool parked(char* why, size_t n) {
if (!UARTReceiver::isConnected(LINK_SILENT_MS)) return true;
automotive_data_t d = UARTReceiver::getLatestData();
if ((d.valid_flags & VALID_FLAG_RPM) && d.engine_rpm > 0) {
snprintf(why, n, "engine running (%u rpm)", d.engine_rpm);
return false;
}
if (d.valid_flags & VALID_FLAG_GEAR_POS) {
if (d.gear_lever != LEVER_PARK && d.gear_lever != LEVER_NEUTRAL && d.gear_lever != LEVER_UNKNOWN) {
snprintf(why, n, "lever in a drive gear");
return false;
}
}
return true;
}
static bool gate(bool need_parked, char* why_out = NULL, size_t why_n = 0) {
char why[96];
bool ok = true;
if (need_parked && !parked(why, sizeof(why))) ok = false;
else if (!LinkPeer::hasWifiCredentials()) { snprintf(why, sizeof(why), "no Wi-Fi credentials from A yet"); ok = false; }
if (!ok) {
print("[ota] refused: %s", why);
if (why_out) snprintf(why_out, why_n, "%s", why);
}
return ok;
}
// ---- Wi-Fi for the duration of a job ---------------------------------------
static bool joinWifi() {
char ssid[33], pass[65];
if (!LinkPeer::getWifiCredentials(ssid, sizeof(ssid), pass, sizeof(pass))) {
print("[ota] no Wi-Fi credentials");
return false;
}
print("[ota] joining '%s'...", ssid);
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.begin(ssid, pass);
memset(pass, 0, sizeof(pass));
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < WIFI_JOIN_MS) {
delay(100);
pump();
}
if (WiFi.status() != WL_CONNECTED) {
print("[ota] could not join '%s' (status %d)", ssid, (int)WiFi.status());
WiFi.disconnect(false);
return false;
}
g_wifi_joined = true;
print("[ota] joined, IP %s, channel %d", WiFi.localIP().toString().c_str(), WiFi.channel());
pump(true);
return true;
}
static void leaveWifi() {
if (!g_wifi_joined) return;
WiFi.disconnect(false); // back to a bare STA; the ESP-NOW receiver re-locks on A's channel
g_wifi_joined = false;
print("[ota] left Wi-Fi; ESP-NOW receiver hops back to A");
pump(true);
}
// ---- helpers (as on A) -----------------------------------------------------
static void toHex(const uint8_t* in, size_t n, char* out) {
static const char* d = "0123456789abcdef";
for (size_t i = 0; i < n; i++) { out[2 * i] = d[in[i] >> 4]; out[2 * i + 1] = d[in[i] & 0x0F]; }
out[2 * n] = 0;
}
static int hexNibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
static bool fromHex(const char* s, uint8_t* out, size_t cap, size_t* len) {
size_t n = strlen(s);
if (n == 0 || (n % 2) || n / 2 > cap) return false;
for (size_t i = 0; i < n; i += 2) {
int hi = hexNibble(s[i]), lo = hexNibble(s[i + 1]);
if (hi < 0 || lo < 0) return false;
out[i / 2] = (uint8_t)((hi << 4) | lo);
}
*len = n / 2;
return true;
}
static bool safeToken(const char* s) {
if (!*s) return false;
for (; *s; s++) if (!isalnum((unsigned char)*s) && *s != '.' && *s != '_' && *s != '-') return false;
return true;
}
static bool httpsGetText(const char* url, String& body, int& code) {
WiFiClientSecure client;
client.setCACert(OTA_CA_PEM);
HTTPClient http;
http.setConnectTimeout(10000);
http.setTimeout(15000);
if (!http.begin(client, url)) { code = -1; return false; }
http.setUserAgent("patrol-b-ota/" FW_VERSION);
code = http.GET();
bool ok = (code == HTTP_CODE_OK);
if (ok) body = http.getString();
http.end();
return ok;
}
static bool jsonString(const String& s, const char* key, char* out, size_t n) {
String k = String("\"") + key + "\"";
int i = s.indexOf(k);
if (i < 0) return false;
i = s.indexOf(':', i + k.length());
if (i < 0) return false;
i = s.indexOf('"', i);
if (i < 0) return false;
int j = s.indexOf('"', i + 1);
if (j < 0 || (size_t)(j - i - 1) >= n) return false;
s.substring(i + 1, j).toCharArray(out, n);
return true;
}
static bool fetchManifest(manifest_t& m) {
memset(&m, 0, sizeof(m));
String body;
int code;
if (!httpsGetText(OTA_LATEST_API_URL, body, code)) {
if (code == 404) print("[ota] no release published yet (push a v* tag)");
else print("[ota] release lookup failed (HTTP %d)", code);
return false;
}
if (!jsonString(body, "tag_name", m.tag, sizeof(m.tag)) || !safeToken(m.tag)) {
print("[ota] could not read tag_name from the release reply");
return false;
}
pump();
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/manifest.txt";
if (!httpsGetText(url.c_str(), body, code)) {
print("[ota] release %s has no manifest.txt (HTTP %d)", m.tag, code);
return false;
}
char sig_hex[2 * sizeof(m.sig) + 1] = {0};
int start = 0;
while (start < (int)body.length()) {
int nl = body.indexOf('\n', start);
if (nl < 0) nl = body.length();
String line = body.substring(start, nl);
line.trim();
start = nl + 1;
int eq = line.indexOf('=');
if (eq <= 0) continue;
String k = line.substring(0, eq), v = line.substring(eq + 1);
if (k == "target") v.toCharArray(m.target, sizeof(m.target));
else if (k == "version") v.toCharArray(m.version, sizeof(m.version));
else if (k == "size") m.size = (uint32_t)v.toInt();
else if (k == "sha256") v.toCharArray(m.sha256, sizeof(m.sha256));
else if (k == "sig" && v.length() < sizeof(sig_hex)) v.toCharArray(sig_hex, sizeof(sig_hex));
}
if (strcmp(m.target, OTA_TARGET) != 0) {
print("[ota] manifest is for '%s', not '%s' - refusing", m.target, OTA_TARGET);
return false;
}
if (strcmp(m.version, m.tag) != 0 || m.size == 0 || strlen(m.sha256) != 64 ||
!fromHex(sig_hex, m.sig, sizeof(m.sig), &m.sig_len)) {
print("[ota] manifest for %s is malformed", m.tag);
return false;
}
for (char* c = m.sha256; *c; c++) *c = tolower(*c);
return true;
}
static bool verifySignature(const manifest_t& m) {
char stmt[160];
int n = snprintf(stmt, sizeof(stmt), "%s|%s|%s", m.target, m.version, m.sha256);
uint8_t h[32];
SHA256_ONESHOT((const unsigned char*)stmt, n, h);
mbedtls_pk_context pk;
mbedtls_pk_init(&pk);
int rc = mbedtls_pk_parse_public_key(&pk, (const unsigned char*)OTA_SIGNING_PUBKEY_PEM, sizeof(OTA_SIGNING_PUBKEY_PEM));
if (rc == 0) rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, h, sizeof(h), m.sig, m.sig_len);
mbedtls_pk_free(&pk);
if (rc != 0) print("[ota] SIGNATURE INVALID for %s (mbedtls -0x%04X) - refusing", m.tag, -rc);
return rc == 0;
}
// ---- install ---------------------------------------------------------------
static void notice(const char* fmt, ...) {
char buf[64];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
GaugeScreen::setNotice(buf);
}
static bool writeImage(const manifest_t& m, const esp_partition_t* part) {
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin";
WiFiClientSecure client;
client.setCACert(OTA_CA_PEM);
HTTPClient http;
http.setConnectTimeout(10000);
http.setTimeout(15000);
if (!http.begin(client, url)) { print("[ota] bad download URL"); return false; }
http.setUserAgent("patrol-b-ota/" FW_VERSION);
int code = http.GET();
if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return false; }
if (http.getSize() != (int)m.size) {
print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size);
http.end();
return false;
}
esp_ota_handle_t h = 0;
esp_err_t err = esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &h);
if (err != ESP_OK) { print("[ota] esp_ota_begin: %s", esp_err_to_name(err)); http.end(); return false; }
uint8_t* buf = (uint8_t*)malloc(CHUNK);
mbedtls_sha256_context sc;
mbedtls_sha256_init(&sc);
SHA256_STARTS(&sc);
WiFiClient* stream = http.getStreamPtr();
uint32_t got = 0, last_rx = millis();
int last_decile = -1, last_pct = -1;
bool ok = (buf != NULL);
while (ok && got < m.size) {
size_t avail = stream->available();
if (avail == 0) {
uint32_t idle = millis() - last_rx;
if ((!http.connected() && idle > 2000) || idle > STALL_TIMEOUT_MS) {
print("[ota] download stalled at %lu/%lu bytes", (unsigned long)got, (unsigned long)m.size);
ok = false;
break;
}
vTaskDelay(pdMS_TO_TICKS(5));
pump();
continue;
}
size_t want = min(min(avail, CHUNK), (size_t)(m.size - got));
int r = stream->read(buf, want);
if (r <= 0) continue;
last_rx = millis();
SHA256_UPDATE(&sc, buf, r);
err = esp_ota_write(h, buf, r);
if (err != ESP_OK) { print("[ota] flash write: %s", esp_err_to_name(err)); ok = false; break; }
got += r;
int pct = (int)((uint64_t)got * 100 / m.size);
if (pct != last_pct) {
last_pct = pct;
g_progress = (uint8_t)pct;
notice("Updating %s %d%%", m.version, pct);
pump();
}
int decile = pct / 10;
if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; }
}
http.end();
free(buf);
uint8_t digest[32];
char digest_hex[65];
SHA256_FINISH(&sc, digest);
mbedtls_sha256_free(&sc);
toHex(digest, sizeof(digest), digest_hex);
if (ok && strcmp(digest_hex, m.sha256) != 0) {
print("[ota] SHA-256 MISMATCH - image does not match the signed manifest");
ok = false;
}
if (!ok) { esp_ota_abort(h); print("[ota] aborted; still running %s", FW_VERSION); return false; }
err = esp_ota_end(h);
if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; }
return true;
}
static void install(bool force) {
manifest_t m;
if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; }
if (!force && strcmp(m.version, FW_VERSION) == 0) {
print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION);
setPhase(LINK_OTA_UP_TO_DATE, m.version);
return;
}
const esp_partition_t* part = esp_ota_get_next_update_partition(NULL);
if (!part) { print("[ota] no idle OTA slot (partition table?)"); failPhase(); return; }
if (m.size > part->size) {
print("[ota] image %lu B does not fit slot %s (%lu B)", (unsigned long)m.size, part->label, (unsigned long)part->size);
failPhase();
return;
}
print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size);
setPhase(LINK_OTA_INSTALLING, m.version);
notice("Updating %s 0%%", m.version);
bool ok = writeImage(m, part);
char why[64];
if (ok && !parked(why, sizeof(why))) {
print("[ota] new image left inactive in %s: %s", part->label, why);
ok = false;
}
if (ok) {
esp_err_t err = esp_ota_set_boot_partition(part);
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); ok = false; }
}
if (!ok) {
failPhase();
notice("Update failed");
pump(true);
delay(3000);
GaugeScreen::setNotice(NULL);
return;
}
print("[ota] verified and installed %s. Rebooting in 3 s; it confirms itself after %lu s of uptime.",
m.version, (unsigned long)(OTA_CONFIRM_MS / 1000));
notice("Installed %s - restarting", m.version);
g_progress = 100;
pump(true);
delay(3000);
esp_restart();
}
static void check() {
manifest_t m;
if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; }
bool same = strcmp(m.version, FW_VERSION) == 0;
print("[ota] running %s | latest release %s (%lu bytes, signature OK)%s",
FW_VERSION, m.version, (unsigned long)m.size, same ? " - up to date" : " - install to update");
setPhase(same ? LINK_OTA_UP_TO_DATE : LINK_OTA_AVAILABLE, m.version);
}
static void rollback() {
char why[64];
if (!parked(why, sizeof(why))) { print("[ota] refused: %s", why); return; }
if (g_pending_verify) {
print("[ota] rejecting this unconfirmed image; rebooting into the previous one");
delay(500);
esp_ota_mark_app_invalid_rollback_and_reboot();
return;
}
const esp_partition_t* other = esp_ota_get_next_update_partition(NULL);
esp_app_desc_t d;
esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED;
if (!other || esp_ota_get_partition_description(other, &d) != ESP_OK) {
print("[ota] no previous image to roll back to");
return;
}
esp_ota_get_state_partition(other, &ost);
if (ost == ESP_OTA_IMG_INVALID || ost == ESP_OTA_IMG_ABORTED) {
print("[ota] previous image in %s is marked %s - refusing", other->label, stateName(ost));
return;
}
esp_err_t err = esp_ota_set_boot_partition(other);
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; }
print("[ota] booting %s in 2 s", other->label);
delay(2000);
esp_restart();
}
static void runJob(job_t job) {
if (job == JOB_ROLLBACK) { rollback(); return; }
Serial.printf("[ota] heap before job: %u free (largest block %u)\n",
(unsigned)ESP.getFreeHeap(), (unsigned)ESP.getMaxAllocHeap());
// Gauges: the loop is about to block, so drive the outputs to their "no
// link" state (tach off) rather than leaving them frozen mid-value.
automotive_data_t none = {};
GaugeOutputs::update(none, false);
if (!joinWifi()) { failPhase(); return; }
if (job == JOB_CHECK) check();
else install(job == JOB_INSTALL_FORCE);
leaveWifi();
GaugeScreen::setNotice(NULL);
Serial.printf("[ota] heap after job: %u free | loop stack headroom %u B\n",
(unsigned)ESP.getFreeHeap(), (unsigned)uxTaskGetStackHighWaterMark(NULL));
}
static bool startJob(job_t job, char* why = NULL, size_t why_n = 0) {
if (g_job != JOB_NONE) { if (why) snprintf(why, why_n, "busy"); return false; }
if (job != JOB_ROLLBACK && !gate(job != JOB_CHECK, why, why_n)) return false;
if (job == JOB_ROLLBACK) { g_job = job; return true; }
setPhase(job == JOB_CHECK ? LINK_OTA_CHECKING : LINK_OTA_INSTALLING);
g_job = job;
print("[ota] working - the gauges pause until done");
return true;
}
static void status() {
const esp_partition_t* run = esp_ota_get_running_partition();
const esp_partition_t* other = esp_ota_get_next_update_partition(NULL);
esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED;
esp_ota_get_state_partition(run, &st);
print("[ota] version %s (built %s %s), slot %s, state %s%s", FW_VERSION, __DATE__, __TIME__,
run ? run->label : "?", stateName(st), g_pending_verify ? " - confirms after healthy uptime" : "");
if (other) {
esp_app_desc_t d;
esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED;
esp_ota_get_state_partition(other, &ost);
if (esp_ota_get_partition_description(other, &d) == ESP_OK)
print("[ota] other slot %s: image built %s %s, state %s", other->label, d.date, d.time, stateName(ost));
else
print("[ota] other slot %s: empty", other->label);
}
print("[ota] updates from %s/%s/releases (%s) | credentials %s | paired %s",
OTA_SERVER, OTA_REPO, OTA_TARGET, LinkPeer::hasWifiCredentials() ? "yes" : "no",
LinkPeer::isPaired() ? "yes" : "no");
}
static void help() {
Serial.println("ota status running version, slot, rollback state");
Serial.println("ota check join Wi-Fi, ask Gitea for the latest release");
Serial.println("ota install [force] download + verify + flash idle slot + reboot (parked only)");
Serial.println("ota rollback boot the previous slot (parked only)");
}
// ---- public ----------------------------------------------------------------
const char* version() { return FW_VERSION; }
void onLinkCommand(uint8_t cmd, uint8_t flags) {
char why[96];
bool ok = false;
switch (cmd) {
case LINK_OTA_CMD_CHECK: ok = startJob(JOB_CHECK, why, sizeof(why)); break;
case LINK_OTA_CMD_INSTALL: ok = startJob((flags & LINK_OTA_FORCE) ? JOB_INSTALL_FORCE : JOB_INSTALL, why, sizeof(why)); break;
case LINK_OTA_CMD_ROLLBACK: ok = startJob(JOB_ROLLBACK, why, sizeof(why)); break;
default: snprintf(why, sizeof(why), "unknown command %u", cmd); break;
}
if (!ok) {
// Tell A on the next STATUS why nothing happened
setPhase(LINK_OTA_FAILED, NULL, why);
}
}
void init() {
const esp_partition_t* run = esp_ota_get_running_partition();
esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED;
if (run && esp_ota_get_state_partition(run, &st) == ESP_OK && st == ESP_OTA_IMG_PENDING_VERIFY) {
g_pending_verify = true;
}
LinkPeer::setOtaCommandHandler(onLinkCommand);
report();
print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?",
g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset before healthy uptime rolls back)" : "");
}
void tick() {
if (g_job != JOB_NONE) {
job_t j = g_job;
runJob(j);
g_job = JOB_NONE;
}
if (g_pending_verify && millis() > OTA_CONFIRM_MS) {
esp_ota_mark_app_valid_cancel_rollback();
g_pending_verify = false;
report();
print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION);
}
}
bool handleCommand(const char* line) {
if (strcmp(line, "help") == 0) { help(); return false; }
char buf[48];
strlcpy(buf, line, sizeof(buf));
char* argv[4] = {0};
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 0 || strcmp(argv[0], "ota") != 0) return false;
if (argc == 1 || !strcmp(argv[1], "help")) help();
else if (!strcmp(argv[1], "status")) status();
else if (!strcmp(argv[1], "check")) startJob(JOB_CHECK);
else if (!strcmp(argv[1], "install")) startJob(argc > 2 && !strcmp(argv[2], "force") ? JOB_INSTALL_FORCE : JOB_INSTALL);
else if (!strcmp(argv[1], "rollback")) startJob(JOB_ROLLBACK);
else help();
return true;
}
} // namespace Ota
+15
View File
@@ -3,6 +3,7 @@
*/
#include "modules/uart_receiver.h"
#include "modules/link_peer.h"
#include "modules/debug_monitor.h"
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
@@ -81,6 +82,20 @@ void processFrame(const uint8_t* frame, size_t len, link_source_t source) {
uint32_t now = millis();
if (type == PACKET_TYPE_PAIR) {
// The shared secret. Wire only: a PAIR heard on the radio is somebody
// else's business (or an attack) and is dropped.
if (source == LINK_SOURCE_UART) {
link_pair_t p;
memcpy(&p, payload, sizeof(p));
LinkPeer::onPairFrame(&p);
} else {
Serial.println("[Link] PAIR frame on the radio ignored - pairing is wire-only");
}
return;
}
if (type != PACKET_TYPE_DATA && type != PACKET_TYPE_CONFIG) return; // STATUS/SECURE never come this way
if (type == PACKET_TYPE_CONFIG) {
link_config_t cfg;
memcpy(&cfg, payload, sizeof(cfg));