Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
3b7903db9This file is pinned to the selected release. Download the original to open it in your design tool.
// network.cpp — WiFi, HTTP, upload, OTA and command-queue implementation.
#include "hivehub_network.h"
#include "inspection.h"
#include "globals.h"
#include "config.h"
#include "device_prefs.h"
#include "storage_power.h"
#include "portal.h"
#include "ca_cert.h"
#include "hive_config.h"
#include "heap_diag.h"
#include "night_mode.h" // MINUTES_PER_DAY, for clamping the delivered window
#include <memory>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Update.h>
#include <esp_heap_caps.h>
#include <esp_app_format.h> // esp_image_header_t / ESP_CHIP_ID_* for the OTA arch guard
#include <esp_system.h> // esp_reset_reason() for the interrupted-relay report
#include <time.h>
#if ENABLE_BLE_SCAN
#include "ble_sensor.h"
#endif
#if HIVEINSIDE_AUDIO_ENABLED
#include "gatt_audio.h"
#endif
#if GATT_OTA_ENABLED
#include "gatt_ota.h"
#endif
// NTP sync — called once after WiFi connects each wake cycle.
// Certificate validation requires the device clock to be accurate.
static bool timeSynced = false;
static void syncTimeIfNeeded() {
if (timeSynced) return;
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
Serial.print("[NTP] Syncing time");
struct tm t;
unsigned long start = millis();
while (millis() - start < 8000) {
if (getLocalTime(&t, 0)) {
timeSynced = true;
Serial.printf(" OK (%04d-%02d-%02d %02d:%02d:%02d UTC)\n",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
return;
}
Serial.print(".");
delay(200);
}
Serial.println();
Serial.println("[NTP] Time sync timed out — TLS cert validation may fail");
}
static void applyTlsConfig(WiFiClientSecure& client) {
client.setCACert(SERVER_CA_CERT);
}
// HTTPS is the secure default. Plain HTTP is an explicit, compile-time opt-in
// for trusted LAN deployments; it must never be selected merely because a TLS
// request fails.
static bool beginHttpRequest(HTTPClient& http, const String& url,
WiFiClientSecure& secureClient,
WiFiClient& plainClient) {
if (url.startsWith("https://")) {
applyTlsConfig(secureClient);
return http.begin(secureClient, url);
}
if (url.startsWith("http://")) {
#if ALLOW_INSECURE_HTTP
Serial.println("[HTTP] WARNING: using insecure plain HTTP");
return http.begin(plainClient, url);
#else
Serial.println("[HTTP] Refusing plain HTTP; set ALLOW_INSECURE_HTTP to 1 to opt in");
return false;
#endif
}
Serial.println("[HTTP] Refusing URL without an http:// or https:// scheme");
return false;
}
String apiUrl(const String& path) {
String base = trimTrailingSlash(apiBaseUrl);
return base + path;
}
bool connectWifi(unsigned long timeoutMs) {
if (WiFi.status() == WL_CONNECTED) {
syncTimeIfNeeded();
return true;
}
int count = getWifiCount();
if (count <= 0) {
Serial.println("[WIFI] No saved WiFi credentials");
return false;
}
String ssids[MAX_WIFI_NETWORKS];
String passes[MAX_WIFI_NETWORKS];
prefs.begin("hivescale", true);
for (int i = 0; i < count; i++) {
ssids[i] = prefs.getString(wifiSsidKey(i).c_str(), "");
passes[i] = prefs.getString(wifiPassKey(i).c_str(), "");
}
prefs.end();
WiFi.mode(WIFI_STA);
// Modem sleep OFF for the short awake window. With WiFi power-save enabled the
// ESP32-C6 leaves the shared I2C peripheral in ESP_ERR_INVALID_STATE after
// radio activity — a wedge Wire.end()/begin() cannot clear. The device
// deep-sleeps between cycles, so keeping the modem awake here costs little.
WiFi.setSleep(false);
for (int i = 0; i < count; i++) {
String ssid = ssids[i];
String pass = passes[i];
if (ssid.length() == 0) continue;
Serial.printf("[WIFI] Trying saved network %d/%d: %s\n", i + 1, count, ssid.c_str());
WiFi.disconnect(true, true);
delay(200);
WiFi.begin(ssid.c_str(), pass.c_str());
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < timeoutMs) {
Serial.print(".");
delay(500);
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
activeWifiSsid = ssid;
Serial.println("[WIFI] Connected");
Serial.print("[WIFI] IP: ");
Serial.println(WiFi.localIP());
Serial.printf("[WIFI] RSSI: %d dBm\n", WiFi.RSSI());
syncTimeIfNeeded();
return true;
}
Serial.printf("[WIFI] Failed network: %s status=%d\n", ssid.c_str(), WiFi.status());
}
Serial.println("[WIFI] All saved networks failed. Not starting AP automatically for power saving.");
return false;
}
bool connectNetwork() {
return connectWifi();
}
void addAuthHeader(HTTPClient& http) {
if (apiKey.length() > 0) http.addHeader("X-API-Key", apiKey);
}
bool httpGetJson(const String& url, JsonDocument& doc) {
if (!connectWifi()) return false;
Serial.println("[HTTP GET]");
Serial.println(url);
WiFiClientSecure secureClient;
WiFiClient plainClient;
HTTPClient http;
http.setConnectTimeout(HTTP_REQUEST_TIMEOUT_MS);
http.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
if (!beginHttpRequest(http, url, secureClient, plainClient)) {
Serial.println("[HTTP GET] http.begin failed");
return false;
}
addAuthHeader(http);
int code = http.GET();
String body = http.getString();
Serial.printf("[HTTP GET] Status: %d\n", code);
Serial.print("[HTTP GET] Body: ");
Serial.println(body);
http.end();
if (code < 200 || code >= 300) return false;
DeserializationError err = deserializeJson(doc, body);
if (err) {
Serial.print("[HTTP GET] JSON parse error: ");
Serial.println(err.c_str());
return false;
}
return true;
}
bool httpPostJson(const String& url, const String& json, String* response) {
if (!connectWifi()) {
Serial.println("[HTTP POST] No WiFi");
return false;
}
Serial.println("[HTTP POST]");
Serial.print("[HTTP POST] URL: ");
Serial.println(url);
Serial.printf("[HTTP POST] Payload: %u bytes (redacted)\n", (unsigned)json.length());
WiFiClientSecure secureClient;
WiFiClient plainClient;
HTTPClient http;
http.setConnectTimeout(HTTP_REQUEST_TIMEOUT_MS);
http.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
if (!beginHttpRequest(http, url, secureClient, plainClient)) {
Serial.println("[HTTP POST] http.begin failed");
return false;
}
http.addHeader("Content-Type", "application/json");
addAuthHeader(http);
int code = http.POST((uint8_t*)json.c_str(), json.length());
String body = http.getString();
Serial.printf("[HTTP POST] Status: %d\n", code);
Serial.printf("[HTTP POST] Response: %u bytes (redacted)\n", (unsigned)body.length());
if (response) *response = body;
http.end();
if (code >= 200 && code < 300) {
Serial.println("[HTTP POST] SUCCESS");
return true;
}
Serial.println("[HTTP POST] FAILED");
return false;
}
bool httpPatchJson(const String& url, const String& json, String* response) {
if (!connectWifi()) {
Serial.println("[HTTP PATCH] No WiFi");
return false;
}
Serial.println("[HTTP PATCH]");
Serial.print("[HTTP PATCH] URL: ");
Serial.println(url);
Serial.print("[HTTP PATCH] Payload: ");
Serial.println(json);
WiFiClientSecure secureClient;
WiFiClient plainClient;
HTTPClient http;
http.setConnectTimeout(HTTP_REQUEST_TIMEOUT_MS);
http.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
if (!beginHttpRequest(http, url, secureClient, plainClient)) {
Serial.println("[HTTP PATCH] http.begin failed");
return false;
}
http.addHeader("Content-Type", "application/json");
addAuthHeader(http);
int code = http.sendRequest("PATCH", (uint8_t*)json.c_str(), json.length());
String body = http.getString();
Serial.printf("[HTTP PATCH] Status: %d\n", code);
Serial.print("[HTTP PATCH] Response: ");
Serial.println(body);
if (response) *response = body;
http.end();
if (code >= 200 && code < 300) {
Serial.println("[HTTP PATCH] SUCCESS");
return true;
}
Serial.println("[HTTP PATCH] FAILED");
return false;
}
bool uploadLine(const String& line, ClaimStatus* claimStatus) {
String response;
bool ok = httpPostJson(apiUrl("/api/v1/measurements"), line, &response);
if (!ok) Serial.println("[UPLOAD] Upload failed");
else Serial.println("[UPLOAD] Upload accepted by server");
// Report whether the server considers this device claimed, so the caller can
// decide when it is safe to stop sending the claim code (see markClaimRegistered
// / device_prefs.cpp). We must NOT latch the claim on a merely-successful upload:
// a rebuilt or restored backend has no record of the device yet, and if the
// device stopped sending its claim code it could never be claimed again.
// Older servers do not return "claimed"; fall back to treating a successful
// upload as confirmation so behaviour against them is unchanged.
//
// An explicit "claimed": false is reported separately from "the server said
// nothing", because it is the signal that the pairing was released (the app
// removed the device) and the claim code must start flowing again.
if (claimStatus) {
ClaimStatus status = ok ? ClaimStatus::Claimed : ClaimStatus::Unknown;
if (ok && response.length()) {
JsonDocument doc;
if (deserializeJson(doc, response) == DeserializationError::Ok &&
doc["claimed"].is<bool>()) {
status = doc["claimed"].as<bool>() ? ClaimStatus::Claimed
: ClaimStatus::Unclaimed;
}
}
*claimStatus = status;
}
return ok;
}
bool uploadCachedLines() {
if (!sdOk) {
Serial.println("[CACHE] No SD card, skipping cached upload");
return true;
}
// A power loss between moving the old queue aside and installing its compacted
// successor leaves only CACHE_PREVIOUS_FILE. Recover it before deciding there
// is no work. The backend's measurement_id idempotency makes a replay after an
// ambiguous power loss safe.
if (!SD.exists(CACHE_FILE) && SD.exists(CACHE_PREVIOUS_FILE)) {
Serial.println("[CACHE] Recovering previous retry queue after interrupted compaction");
if (!SD.rename(CACHE_PREVIOUS_FILE, CACHE_FILE)) {
Serial.println("[CACHE] Failed to recover previous retry queue");
return false;
}
}
if (!SD.exists(CACHE_FILE)) {
Serial.println("[CACHE] No cache file");
return true;
}
if (!cacheFileLooksSane()) {
Serial.println("[CACHE] Cache file was quarantined or removed; skipping cached upload this cycle");
return false;
}
File in = SD.open(CACHE_FILE, FILE_READ);
if (!in) {
Serial.println("[CACHE] Failed to open cache file for read");
return false;
}
SD.remove(TEMP_FILE);
File out = SD.open(TEMP_FILE, FILE_WRITE);
if (!out) {
Serial.println("[CACHE] Failed to open temp cache file");
in.close();
return false;
}
bool encounteredFailure = false;
bool hitUploadLimit = false;
int total = 0;
int uploaded = 0;
int kept = 0;
int dropped = 0;
while (in.available()) {
String line = in.readStringUntil('\n');
line.trim();
if (line.length() == 0) continue;
total++;
if (line.length() > CACHE_MAX_LINE_BYTES) {
dropped++;
Serial.printf("[CACHE] Dropping oversized cached line %d (%u bytes)\n", total, (unsigned)line.length());
continue;
}
bool mayUpload = !encounteredFailure && uploaded < CACHE_UPLOAD_MAX_LINES_PER_CYCLE;
if (mayUpload) {
Serial.printf("[CACHE] Uploading cached line %d\n", total);
if (uploadLine(line)) {
uploaded++;
delay(100);
continue;
}
encounteredFailure = true;
Serial.println("[CACHE] Cached upload failed; keeping this and remaining cached lines");
} else if (!encounteredFailure && uploaded >= CACHE_UPLOAD_MAX_LINES_PER_CYCLE) {
hitUploadLimit = true;
}
kept++;
size_t written = out.println(line);
if (written == 0) {
Serial.println("[CACHE] Failed to write retained line to temp cache");
encounteredFailure = true;
}
}
in.close();
out.flush();
out.close();
if (kept > 0) {
// Never delete the old queue before its replacement is durable. FAT lacks
// atomic replace, so use a two-generation rename and recover .prev next
// boot if power is lost mid-transaction.
SD.remove(CACHE_PREVIOUS_FILE);
if (!SD.rename(CACHE_FILE, CACHE_PREVIOUS_FILE)) {
Serial.println("[CACHE] ERROR: failed to stage old cache file for replacement");
return false;
}
if (!SD.rename(TEMP_FILE, CACHE_FILE)) {
Serial.println("[CACHE] ERROR: failed to rename temp cache file back to cache file");
if (!SD.rename(CACHE_PREVIOUS_FILE, CACHE_FILE)) {
Serial.println("[CACHE] ERROR: failed to restore previous retry queue");
}
return false;
}
SD.remove(CACHE_PREVIOUS_FILE);
} else {
// Keeping the already-uploaded queue through an unexpected reset is safe:
// each line carries a stable measurement_id and the server de-duplicates it.
if (!SD.remove(CACHE_FILE)) {
Serial.println("[CACHE] Warning: failed to remove fully uploaded cache file");
}
SD.remove(TEMP_FILE);
// Drop any staging file left behind by an interrupted compaction so it is
// not resurrected next boot and needlessly replayed.
SD.remove(CACHE_PREVIOUS_FILE);
}
Serial.printf(
"[CACHE] Total=%d Uploaded=%d Kept=%d Dropped=%d Limit=%s\n",
total,
uploaded,
kept,
dropped,
hitUploadLimit ? "yes" : "no"
);
return kept == 0 && !encounteredFailure;
}
void fetchRemoteConfig() {
JsonDocument doc;
String url = apiUrl(String("/api/v1/devices/") + deviceId + "/config");
Serial.println("[CONFIG] Fetching remote config");
if (!httpGetJson(url, doc)) {
Serial.println("[CONFIG] Failed to fetch config");
return;
}
// Backends predating migration 028 retained only the claim-code hash. After
// an upgrade they cannot reconstruct the value shown in Device & admin, so
// they request one fresh submission from firmware that had already latched
// the device as claimed. The next measurement carries it; the backend then
// clears this flag and the normal claim latch suppresses it again.
if (doc["claim_code_required"] | false) {
Serial.println("[CONFIG] Backend needs claim code; scheduling re-submission");
clearClaimRegistered();
}
sendIntervalMs = (unsigned long)(doc["send_interval_seconds"] | 600) * 1000UL;
// HiveTraffic night mode. Applied UNCONDITIONALLY, unlike the calibration
// below: the config_version gate exists because a portal-side tare must not
// be reverted by a server that never learned about it, and night mode has no
// portal-side counterpart to protect — the dashboard is its only source. A
// beekeeper who turns the window off expects it off on the next cycle, not
// after the next unrelated config edit bumps the version.
//
// Defaults match globals.cpp, so a server too old to know these keys leaves
// the feature off rather than half-configured. The window is clamped here as
// well as server-side: night_mode.h refuses an out-of-range window outright,
// and "the counter never slept and nothing said why" is a bad way to find out
// a field was 1500.
nightModeEnabled = doc["beecounter_night_mode_enabled"] | false;
{
const uint32_t start = doc["beecounter_night_start_minute"] | 1200;
const uint32_t end = doc["beecounter_night_end_minute"] | 360;
nightStartMinute = start < nightmode::MINUTES_PER_DAY ? (uint16_t)start : 1200;
nightEndMinute = end < nightmode::MINUTES_PER_DAY ? (uint16_t)end : 360;
}
nightMaxTraffic = doc["beecounter_night_max_traffic"] | 0;
nightTimezone = doc["timezone"] | "";
// How long an inspection may run before the hub ends it itself. Applied
// unconditionally for the same reason night mode is: the dashboard is its only
// source, so there is no local edit for a config_version gate to protect. A
// server too old to send the key leaves the compiled default in place.
inspection::setTimeoutMinutes(doc["inspection_timeout_minutes"] | 0U);
// HiveTraffic emitter banks, delivered as three booleans and assembled into
// the bitmask the counter's SET_BANKS opcode takes. Applied unconditionally
// for the same reason the window above is: the dashboard is the only source,
// so there is no local edit for a config_version gate to protect.
//
// Defaults are all-on, per field, so a server too old to know these keys
// leaves every counter running its full entrance rather than switching banks
// off on the strength of a missing key.
{
uint8_t mask = 0;
if (doc["beecounter_bank1_enabled"] | true) mask |= 0x01;
if (doc["beecounter_bank2_enabled"] | true) mask |= 0x02;
if (doc["beecounter_bank3_enabled"] | true) mask |= 0x04;
// An all-off mask is refused rather than stored. The dashboard will not
// save one and the counter will not apply one, so honouring it here would
// only produce a HiveHub that believes it switched a counter off and a
// counter that is still counting — with the disagreement invisible until
// someone compares the two.
if (mask == 0) {
Serial.println("[CONFIG] All bee counter banks disabled in config — ignoring");
mask = BEECOUNTER_BANK_MASK_ALL;
}
if (mask != beeBankMask) {
Serial.printf("[CONFIG] Bee counter banks 0x%02X -> 0x%02X\n",
(unsigned)beeBankMask, (unsigned)mask);
}
beeBankMask = mask;
}
if (nightModeEnabled) {
Serial.printf("[CONFIG] Night mode %02u:%02u-%02u:%02u %s, max traffic %lu\n",
(unsigned)(nightStartMinute / 60), (unsigned)(nightStartMinute % 60),
(unsigned)(nightEndMinute / 60), (unsigned)(nightEndMinute % 60),
nightTimezone.length() ? nightTimezone.c_str() : "UTC",
(unsigned long)nightMaxTraffic);
}
// Persisted so a hub that boots without WiFi still honours the last known
// window and bank mask, instead of running the emitters all night — or all
// 24 gates — waiting for a config it cannot fetch.
saveNightModePrefs();
// Bridge calibration into the hive registry (the authoritative source for the
// read path) ONLY when the server config actually changed since it was last
// applied. /config always returns scale1/2 offset+factor (DB defaults
// 0 / -7050), and the server never learns a calibration done locally on the
// portal's /calibrate page — so applying these fields unconditionally every
// cycle silently reverts a portal tare/span one cycle later. config_version
// increments on every server-side config edit (dashboard PATCH or command
// result) and is therefore the change signal:
// - same version as last applied -> nothing changed server-side; keep the
// local (possibly portal-calibrated) values;
// - different version -> a deliberate server-side edit; apply it;
// - no version ever applied (fresh device, first boot after upgrade, or
// after a factory reset) -> record the version but do NOT bridge: the
// server only holds defaults for a device it has never calibrated, while
// the device may already carry a portal calibration.
// The legacy scale1/2 fields map to hives 1–2 scale[0]; an optional per-hive
// array calibrates the rest:
// "hive_scales": [ { "index": 5, "scale": 0, "offset": 123, "factor": -7100 }, … ]
uint32_t remoteVersion = doc["config_version"] | 0;
prefs.begin("hivescale", true);
uint32_t appliedVersion = prefs.getUInt("cfg_applied", 0);
prefs.end();
bool versionChanged = remoteVersion != 0 && remoteVersion != appliedVersion;
bool applyCalibration = versionChanged && appliedVersion != 0;
if (applyCalibration) {
scale1Offset = doc["scale1_offset"] | scale1Offset;
scale1Factor = doc["scale1_factor"] | scale1Factor;
scale2Offset = doc["scale2_offset"] | scale2Offset;
scale2Factor = doc["scale2_factor"] | scale2Factor;
bool regChanged = false;
auto applyToHive = [®Changed](uint8_t hiveIndex, uint8_t scaleIdx, long off, float fac) {
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
if (hivecfg::gHives[h].index != hiveIndex) continue;
if (scaleIdx < hivecfg::gHives[h].scaleCount) {
auto& ch = hivecfg::gHives[h].scales[scaleIdx];
if (ch.offset != off || ch.factor != fac) {
ch.offset = off; ch.factor = fac; regChanged = true;
}
}
return;
}
};
applyToHive(1, 0, scale1Offset, scale1Factor);
applyToHive(2, 0, scale2Offset, scale2Factor);
for (JsonObject o : doc["hive_scales"].as<JsonArray>()) {
uint8_t idx = (uint8_t)(o["index"] | 0);
uint8_t sc = (uint8_t)(o["scale"] | 0);
if (idx < 1) continue;
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
if (hivecfg::gHives[h].index != idx || sc >= hivecfg::gHives[h].scaleCount) continue;
auto& ch = hivecfg::gHives[h].scales[sc];
if (!o["offset"].isNull()) {
long v = (long)(o["offset"] | 0L);
if (ch.offset != v) { ch.offset = v; regChanged = true; }
}
if (!o["factor"].isNull()) {
float v = (float)(o["factor"] | -7050.0);
if (ch.factor != v) { ch.factor = v; regChanged = true; }
}
}
}
if (regChanged) hivecfg::saveHiveConfig();
}
if (doc["claim_code"].is<const char*>()) {
String remoteClaimCode = doc["claim_code"].as<String>();
remoteClaimCode.trim();
if (remoteClaimCode.length() > 0 && remoteClaimCode != claimCode) {
Serial.println("[CONFIG] Updating claim code from remote config");
claimCode = remoteClaimCode;
putPrefString("claim_code", claimCode);
// A new code must actually reach the server, and the "claim registered"
// latch would otherwise suppress it for good.
clearClaimRegistered();
}
}
// Persist interval + legacy scale keys, and remember which server version was
// applied, only when the version moved — fetchRemoteConfig runs every cycle,
// and rewriting NVS each time would wear the flash for no reason.
if (versionChanged) {
saveScaleConfig();
prefs.begin("hivescale", false);
prefs.putUInt("cfg_applied", remoteVersion);
prefs.end();
}
Serial.printf("[CONFIG] Remote config applied (version %lu, calibration %s)\n",
(unsigned long)remoteVersion,
applyCalibration ? "applied" : "unchanged");
}
void reportScaleCalibration() {
// Report the device's calibration to the server so a tare/span done offline on
// the portal is reflected server-side. Two storage shapes, matching the reverse
// bridge in fetchRemoteConfig():
// - hives 1–2 -> the legacy scale1/2 offset+factor columns;
// - hives 3–18 -> the hive_scales[] array (server keeps these per hive).
// Only a hive that actually carries a valid scale is reported, so a device that
// uses (say) only hive 2 never clobbers another slot with a default.
JsonDocument body;
int reported = 0;
auto addLegacy = [&](uint8_t hiveIndex, const char* offKey, const char* facKey) {
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
if (hivecfg::gHives[h].index != hiveIndex) continue;
if (hivecfg::gHives[h].scaleCount == 0) return;
const hivecfg::ScaleChannel& ch = hivecfg::gHives[h].scales[0];
if (!ch.valid()) return;
body[offKey] = ch.offset;
body[facKey] = ch.factor;
reported++;
return;
}
};
addLegacy(1, "scale1_offset", "scale1_factor");
addLegacy(2, "scale2_offset", "scale2_factor");
JsonArray hiveScales = body["hive_scales"].to<JsonArray>();
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
const hivecfg::Hive& hive = hivecfg::gHives[h];
if (hive.index < 3) continue; // 1–2 are covered by the legacy fields above
if (hive.scaleCount == 0) continue;
const hivecfg::ScaleChannel& ch = hive.scales[0];
if (!ch.valid()) continue;
JsonObject o = hiveScales.add<JsonObject>();
o["index"] = hive.index;
o["scale"] = 0; // one scale per hive today (MAX_SCALES_PER_HIVE)
o["offset"] = ch.offset;
o["factor"] = ch.factor;
reported++;
}
if (hiveScales.size() == 0) body.remove("hive_scales");
if (reported == 0) {
Serial.println("[CONFIG] No local scale calibration to report; clearing pending flag");
clearScaleCalibrationReport();
return;
}
String payload;
serializeJson(body, payload);
String url = apiUrl(String("/api/v1/devices/") + deviceId + "/config");
String response;
if (!httpPatchJson(url, payload, &response)) {
// Keep the pending flag set so the report is retried on the next cycle.
Serial.println("[CONFIG] Failed to report scale calibration; will retry next cycle");
return;
}
// The PATCH incremented config_version and the response echoes the new config.
// Record that version as the one we've applied so the fetchRemoteConfig() right
// after this sees "unchanged" and does not bridge these very values back into
// the registry (harmless, but it keeps cfg_applied honest and skips a needless
// NVS write).
JsonDocument doc;
if (!deserializeJson(doc, response) && !doc["config_version"].isNull()) {
uint32_t newVersion = doc["config_version"] | 0;
if (newVersion != 0) {
prefs.begin("hivescale", false);
prefs.putUInt("cfg_applied", newVersion);
prefs.end();
}
}
clearScaleCalibrationReport();
Serial.println("[CONFIG] Scale calibration reported to server");
}
String absoluteUrl(String maybeRelativeUrl) {
maybeRelativeUrl.trim();
if (maybeRelativeUrl.startsWith("http://") || maybeRelativeUrl.startsWith("https://")) return maybeRelativeUrl;
if (!maybeRelativeUrl.startsWith("/")) maybeRelativeUrl = "/" + maybeRelativeUrl;
return trimTrailingSlash(apiBaseUrl) + maybeRelativeUrl;
}
// The esp-image chip_id this build belongs to. Used to reject a firmware image
// compiled for a different SoC (e.g. an ESP32-C6/RISC-V image arriving at a 30-pin
// ESP32/Xtensa) before a single byte is written to the OTA partition. Returns
// ESP_CHIP_ID_INVALID when the target is unknown, in which case the check is
// skipped rather than blocking OTA on an unrecognised build.
static uint16_t expectedImageChipId() {
#if defined(CONFIG_IDF_TARGET_ESP32C6)
return ESP_CHIP_ID_ESP32C6;
#elif defined(CONFIG_IDF_TARGET_ESP32)
return ESP_CHIP_ID_ESP32;
#else
return ESP_CHIP_ID_INVALID;
#endif
}
// Rolling CRC-32 (IEEE 802.3, reflected 0xEDB88320 — the same algorithm as the
// backend's zlib.crc32). Start with crc=0 and feed each
// chunk the previous call's return value; the final value is the file CRC.
uint32_t crc32Update(uint32_t crc, const uint8_t* data, size_t len) {
crc = ~crc;
for (size_t i = 0; i < len; i++) {
crc ^= data[i];
for (uint8_t b = 0; b < 8; b++)
crc = (crc & 1) ? (crc >> 1) ^ 0xEDB88320u : (crc >> 1);
}
return ~crc;
}
// Adapts Update to the Stream interface HTTPClient::writeToStream() wants.
// writeToStream is used instead of reading the raw socket because it is the
// only HTTPClient download path that de-frames a Transfer-Encoding: chunked
// body (a proxy/CDN in front of the backend may re-frame the response that
// way); reading the raw stream would interleave chunk-size lines into the
// image. The sink also holds back the first esp_image header for the
// architecture guard and keeps a rolling CRC-32 of everything it forwards, so
// the caller can verify the download before committing the OTA partition.
// Returning 0 from write() makes writeToStream abort the transfer.
class OtaUpdateSink : public Stream {
public:
explicit OtaUpdateSink(uint16_t expectedChipId) : _expectedChip(expectedChipId) {}
size_t write(const uint8_t* data, size_t len) override {
if (_failed) return 0;
size_t consumed = 0;
while (_headerFill < sizeof(_header) && consumed < len)
((uint8_t*)&_header)[_headerFill++] = data[consumed++];
if (_headerFill == sizeof(_header) && !_headerChecked) {
_headerChecked = true;
if (_header.magic != ESP_IMAGE_HEADER_MAGIC) {
Serial.printf("[OTA] Bad image magic 0x%02X (expected 0x%02X); aborting\n",
_header.magic, ESP_IMAGE_HEADER_MAGIC);
_failed = true;
return 0;
}
if (_expectedChip != ESP_CHIP_ID_INVALID && _header.chip_id != _expectedChip) {
Serial.printf("[OTA] Wrong chip: image chip_id=0x%04X, this device=0x%04X (%s) — refusing to flash\n",
(unsigned)_header.chip_id, (unsigned)_expectedChip, HIVEHUB_BOARD_LABEL);
_failed = true;
return 0;
}
if (Update.write((uint8_t*)&_header, sizeof(_header)) != sizeof(_header)) {
_failed = true;
return 0;
}
_crc = crc32Update(_crc, (const uint8_t*)&_header, sizeof(_header));
_written += sizeof(_header);
}
if (consumed < len) {
size_t n = Update.write(const_cast<uint8_t*>(data) + consumed, len - consumed);
_crc = crc32Update(_crc, data + consumed, n);
_written += n;
consumed += n;
if (consumed != len) _failed = true;
}
return consumed;
}
size_t write(uint8_t b) override { return write(&b, 1); }
// Stream demands a read side; the sink is write-only.
int available() override { return 0; }
int read() override { return -1; }
int peek() override { return -1; }
void flush() override {}
bool failed() const { return _failed; }
size_t written() const { return _written; }
uint32_t crc32() const { return _crc; }
private:
esp_image_header_t _header{};
size_t _headerFill = 0;
bool _headerChecked = false;
bool _failed = false;
size_t _written = 0;
uint32_t _crc = 0;
uint16_t _expectedChip;
};
bool performFirmwareUpdate(const String& firmwareUrl, int expectedSize,
uint32_t expectedCrc32) {
if (!connectWifi()) return false;
String url = absoluteUrl(firmwareUrl);
Serial.print("[OTA] Downloading firmware: ");
Serial.println(url);
WiFiClientSecure secureClient;
WiFiClient plainClient;
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
if (!beginHttpRequest(http, url, secureClient, plainClient)) {
Serial.println("[OTA] http.begin failed");
return false;
}
int code = http.GET();
if (code != HTTP_CODE_OK) {
Serial.printf("[OTA] Download failed. HTTP %d\n", code);
http.end();
return false;
}
// A reverse proxy/CDN in front of the backend (e.g. Cloudflare) may deliver
// the image with Transfer-Encoding: chunked, i.e. without a Content-Length
// header — getSize() is then -1 even though the download itself is fine.
// Fall back to the size the backend reported in the OTA check response; when
// even that is unknown (older backend) proceed with UPDATE_SIZE_UNKNOWN, but
// only if a CRC is available to prove the download arrived complete.
int contentLength = http.getSize();
int totalSize = contentLength > 0 ? contentLength : expectedSize;
if (totalSize <= 0 && expectedCrc32 == 0) {
// Without a length OR a checksum a truncated download is indistinguishable
// from a complete one — refuse rather than flash blind.
Serial.printf("[OTA] Invalid content length %d and no expected size/CRC from backend; aborting\n",
contentLength);
http.end();
return false;
}
if (totalSize > 0 && totalSize < (int)sizeof(esp_image_header_t)) {
Serial.println("[OTA] Image smaller than its header; aborting");
http.end();
return false;
}
if (!Update.begin(totalSize > 0 ? (size_t)totalSize : UPDATE_SIZE_UNKNOWN)) {
Serial.printf("[OTA] Update.begin failed. Error %d\n", Update.getError());
http.end();
return false;
}
// The sink enforces the architecture guard (esp-image magic + chip_id) on the
// leading header bytes before anything reaches the OTA partition — a
// cross-architecture image (e.g. an ESP32-C6/RISC-V build reaching a 30-pin
// ESP32/Xtensa) would not boot, so a mislabeled or misrouted release never
// starts a write. The server's per-board OTA matching is the primary defence;
// this is the on-device backstop.
OtaUpdateSink sink(expectedImageChipId());
int streamed = http.writeToStream(&sink);
http.end();
if (streamed < 0 && !sink.failed()) {
Serial.printf("[OTA] Download failed: %s\n", HTTPClient::errorToString(streamed).c_str());
}
if (streamed < 0 || sink.failed()) {
Update.abort();
return false;
}
if (totalSize > 0 && sink.written() != (size_t)totalSize) {
Serial.printf("[OTA] Written only %u/%d bytes; aborting\n",
(unsigned)sink.written(), totalSize);
Update.abort();
return false;
}
if (sink.written() < sizeof(esp_image_header_t)) {
Serial.printf("[OTA] Image truncated at %u bytes; aborting\n", (unsigned)sink.written());
Update.abort();
return false;
}
if (expectedCrc32 != 0 && sink.crc32() != expectedCrc32) {
Serial.printf("[OTA] CRC mismatch: got 0x%08X expected 0x%08X; aborting\n",
(unsigned)sink.crc32(), (unsigned)expectedCrc32);
Update.abort();
return false;
}
// With UPDATE_SIZE_UNKNOWN the updater can never observe "finished" on its
// own, so pass evenIfRemaining=true; the size/CRC checks above already vouch
// for the image being complete, and end() still runs esp_image validation
// before the boot partition is switched.
if (!Update.end(true)) {
Serial.printf("[OTA] Update.end failed. Error %d\n", Update.getError());
return false;
}
Serial.println("[OTA] Update successful, rebooting");
delay(1000);
ESP.restart();
return true;
}
#if GATT_OTA_ENABLED
// Relay a firmware image to a paired BLE sub-device over GATT.
//
// A HiveInside (nRF54LM20A MCUboot) image is >1 MB and will NOT fit in the
// WROOM's RAM. So this STREAMS: it opens the HTTPS download, opens the BLE OTA
// session, then pumps the body straight from the socket into the GATT DATA
// characteristic a chunk at a time. The image is forwarded opaquely — this relay
// path does NOT run the ESP32 self-OTA architecture guard (OtaUpdateSink /
// esp_image_header chip-id check); that guard is only for the hub's own Xtensa/
// RISC-V image. The receiving device verifies the end-to-end CRC-32 (passed in
// BEGIN) before swapping its OTA slot, so a corrupted relay can never brick the
// sub-device — it just aborts and keeps running the old image.
//
// Everything here is target-agnostic: `target` (gatt_ota.h) carries the UUIDs
// and how to reach the peer. HiveTraffic images are far smaller than HiveInside
// ones but travel the identical path.
static bool relayFirmwareOverGatt(const gattota::Target& target,
const String& mac, const String& firmwareUrl,
uint32_t expectedCrc32, String* outMsg) {
auto setMsg = [&](const String& m) { if (outMsg) *outMsg = m; };
const char* tag = target.logTag;
if (!connectWifi()) { setMsg("WiFi connect failed"); return false; }
String url = absoluteUrl(firmwareUrl);
Serial.printf("[%s] Downloading %s firmware: %s\n", tag, target.deviceLabel,
url.c_str());
// The relay is the longest-lived allocation burst in the firmware — a TLS
// session and the BLE stack are both up at once — and a hub panicked here in
// the field, inside the allocator, on a corrupted free block. Probe on the
// way in so the log says whether the heap was already damaged before this
// path touched anything.
heapdiag::probe("relay-start");
WiFiClientSecure secureClient;
WiFiClient plainClient;
HTTPClient http;
// Bound the exchange exactly as every other HTTP path here does. This one was
// the only request left running on the library defaults, which is a poor fit
// for the request that stays open longest.
http.setConnectTimeout(HTTP_REQUEST_TIMEOUT_MS);
http.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
if (!beginHttpRequest(http, url, secureClient, plainClient)) {
Serial.printf("[%s] http.begin failed\n", tag);
setMsg("firmware download init failed");
return false;
}
int code = http.GET();
if (code != HTTP_CODE_OK) {
Serial.printf("[%s] Download failed. HTTP %d\n", tag, code);
http.end();
setMsg(String("firmware download failed (HTTP ") + code + ")");
return false;
}
int contentLength = http.getSize();
if (contentLength <= 0 || contentLength > 4 * 1024 * 1024) {
Serial.printf("[%s] Invalid content length %d\n", tag, contentLength);
http.end();
setMsg(String("invalid firmware content length ") + contentLength);
return false;
}
// Everything from the download line above to gattota::begin's first log line
// used to be silent — TLS handshake, header parse and NimBLE bring-up all in
// one unlit stretch — so a panic in there could not be placed any more
// precisely than "somewhere before the transfer". Name the boundary, and
// probe the heap on both sides of it.
Serial.printf("[%s] Download open: %d bytes; bringing up BLE\n", tag,
contentLength);
heapdiag::probe("relay-download-open");
// Open the BLE OTA session (locates/connects the device, sends BEGIN). Do
// this AFTER we have the Content-Length so the device sizes its OTA slot.
if (!gattota::begin(target, mac, (uint32_t)contentLength, expectedCrc32)) {
Serial.printf("[%s] session begin failed\n", tag);
http.end();
setMsg(gattota::lastError().length() ? gattota::lastError()
: String("BLE OTA begin failed"));
return false;
}
// Pump the HTTPS body straight into the GATT DATA characteristic. The relay
// buffer is tiny (one MTU-sized chunk is written per gattota::write call
// internally); 1 KB here just amortises socket reads.
static const size_t RELAY_BUF = 1024;
uint8_t buf[RELAY_BUF];
WiFiClient* stream = http.getStreamPtr();
int read = 0;
unsigned long lastData = millis();
bool relayOk = true;
bool stalled = false;
while (read < contentLength && (http.connected() || stream->available())) {
size_t avail = stream->available();
if (avail) {
int r = stream->readBytes(buf, min(min(avail, RELAY_BUF), (size_t)(contentLength - read)));
if (r > 0) {
if (!gattota::write(buf, (size_t)r)) {
Serial.printf("[%s] relay write failed at %d/%d\n", tag, read, contentLength);
relayOk = false;
break;
}
read += r;
lastData = millis();
if ((read % (32 * 1024)) < (size_t)r) {
Serial.printf("[%s] relayed %d/%d bytes\n", tag, read, contentLength);
}
}
} else if (millis() - lastData > 15000) {
Serial.printf("[%s] download stalled\n", tag);
relayOk = false;
stalled = true;
break;
} else {
delay(1);
}
}
http.end();
bool ok = false;
if (relayOk && read == contentLength) {
ok = gattota::finish();
if (!ok) {
setMsg(gattota::lastError().length() ? gattota::lastError()
: String("OTA finalize/verify failed"));
}
} else {
Serial.printf("[%s] incomplete relay %d/%d — aborting\n", tag, read, contentLength);
gattota::abort();
if (stalled) {
setMsg(String("firmware download stalled at ") + read + "/" + contentLength + " bytes");
} else {
setMsg(gattota::lastError().length()
? gattota::lastError()
: String("incomplete relay ") + read + "/" + contentLength + " bytes");
}
}
gattota::cleanup();
// After the BLE stack has been torn down again: what the whole session cost,
// and whether it left the heap intact.
heapdiag::probe("relay-end");
if (ok) setMsg(String(target.deviceLabel) + " OTA completed");
Serial.printf("[%s] result: %s\n", tag, ok ? "OK" : "FAIL");
return ok;
}
#endif // GATT_OTA_ENABLED
#if ENABLE_BLE_SCAN && HIVEINSIDE_OTA_ENABLED
bool updateHiveInside(const String& mac, const String& firmwareUrl,
uint32_t expectedCrc32, String* outMsg) {
return relayFirmwareOverGatt(gattota::HIVEINSIDE, mac, firmwareUrl,
expectedCrc32, outMsg);
}
#endif
#if ENABLE_WIRELESS_BEECOUNTER && BEECOUNTER_OTA_ENABLED
bool updateBeeCounter(const String& mac, const String& firmwareUrl,
uint32_t expectedCrc32, String* outMsg) {
return relayFirmwareOverGatt(gattota::BEECOUNTER, mac, firmwareUrl,
expectedCrc32, outMsg);
}
#endif
#if HIVEINSIDE_AUDIO_ENABLED
// Split an absolute URL into the pieces a raw socket needs. The audio upload
// cannot go through HTTPClient: a live session has no length to declare, and
// HTTPClient can only send a body whose size is known up front.
static bool splitUrl(const String& url, bool& tls, String& host, uint16_t& port,
String& path) {
int schemeEnd;
if (url.startsWith("https://")) {
tls = true; port = 443; schemeEnd = 8;
} else if (url.startsWith("http://")) {
tls = false; port = 80; schemeEnd = 7;
} else {
return false;
}
int slash = url.indexOf('/', schemeEnd);
String hostPort = (slash < 0) ? url.substring(schemeEnd)
: url.substring(schemeEnd, slash);
path = (slash < 0) ? String("/") : url.substring(slash);
int colon = hostPort.indexOf(':');
if (colon >= 0) {
port = (uint16_t)hostPort.substring(colon + 1).toInt();
host = hostPort.substring(0, colon);
} else {
host = hostPort;
}
return host.length() > 0 && port != 0;
}
// Relay one HiveInside audio session to the backend.
//
// The upload is a single chunked POST rather than a series of sized ones. A
// live session's length is unknown until it ends, and a fresh TLS handshake per
// chunk would cost more wall-clock time than the audio it carried: the node
// emits 32 kB/s and does not wait. One socket, one handshake, chunk framing for
// the duration.
//
// Ordering matters and is deliberate: the socket and its headers go out BEFORE
// the BLE session starts. Reversed, the one-to-several seconds of scan,
// connect and TLS handshake would run while the node was already streaming into
// a 32 KiB ring, and the first second of every recording would be lost to an
// overrun. An idle socket waiting for its first chunk is the cheaper end of
// that trade.
// Bytes reserved ahead of the payload for an HTTP chunk's hex length line.
// HIVEINSIDE_AUDIO_UPLOAD_CHUNK is 4096, so the longest line is "1000\r\n" —
// six bytes. Eight leaves room for a larger chunk size without revisiting this.
static constexpr size_t CHUNK_SLACK = 8;
static bool relayAudioSession(const String& mac, long recordingId,
uint16_t durationDs, int8_t gainDb,
String* outMsg) {
auto setMsg = [&](const String& m) { if (outMsg) *outMsg = m; };
if (!connectWifi()) { setMsg("WiFi connect failed"); return false; }
// The upload URL is built here, never taken from the command payload. A hub
// that POSTed microphone audio to whatever address a queued command named
// would be one compromised or malformed command away from streaming a hive —
// and a garden — to a stranger.
const String base = String("/api/v1/devices/") + deviceId + "/recordings/" + recordingId;
const String streamUrl = apiUrl(base + "/stream");
bool tls = false; String host, path; uint16_t port = 0;
if (!splitUrl(streamUrl, tls, host, port, path)) {
setMsg("audio upload URL has no http:// or https:// scheme");
return false;
}
#if !ALLOW_INSECURE_HTTP
if (!tls) {
setMsg("refusing to stream audio over plain HTTP "
"(set ALLOW_INSECURE_HTTP to 1 to opt in)");
return false;
}
#endif
heapdiag::probe("audio-start");
WiFiClientSecure secureClient;
WiFiClient plainClient;
WiFiClient* sock = nullptr;
// TWO different timeouts, both in MILLISECONDS, and they are not the same
// knob — which is what the single call here used to get wrong.
//
// `setTimeout(HTTP_REQUEST_TIMEOUT_MS / 1000)` looks like "15 seconds", and
// that division says it was meant as one. But NetworkClient and
// NetworkClientSecure declare no setTimeout at all: the call bound to
// Stream::setTimeout, whose argument is MILLISECONDS (Stream.h: "sets maximum
// milliseconds to wait for stream data"). It asked for a 15 ms budget, and it
// governs only the Stream read helpers — readStringUntil() below — never the
// socket. The status line of the upload's response routinely needs more than
// one TLS record to arrive, so a 15 ms budget returns a truncated or empty
// line, httpStatus parses as 0, and a recording that uploaded perfectly is
// reported to the operator as "backend rejected the upload (HTTP 0)".
//
// The socket's own send/receive timeouts come from a DIFFERENT member, set by
// setConnectionTimeout() (milliseconds) and applied as SO_SNDTIMEO/SO_RCVTIMEO
// on the first write and read. It was never set here, so both defaulted:
// 30 s for the secure client, 3 s for the plain one. Setting it explicitly
// before connect() also bounds the TLS handshake, which is the one part of
// this path that talks to the network before any audio exists.
if (tls) {
applyTlsConfig(secureClient);
secureClient.setConnectionTimeout(HTTP_REQUEST_TIMEOUT_MS);
secureClient.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
if (!secureClient.connect(host.c_str(), port)) {
setMsg("TLS connect to the backend failed");
return false;
}
sock = &secureClient;
} else {
plainClient.setConnectionTimeout(HTTP_REQUEST_TIMEOUT_MS);
plainClient.setTimeout(HTTP_REQUEST_TIMEOUT_MS);
if (!plainClient.connect(host.c_str(), port)) {
setMsg("connect to the backend failed");
return false;
}
sock = &plainClient;
}
String headers = String("POST ") + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: HiveHub/" + FIRMWARE_VERSION + "\r\n" +
"Content-Type: application/octet-stream\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Connection: close\r\n";
if (apiKey.length() > 0) headers += "X-API-Key: " + apiKey + "\r\n";
headers += "\r\n";
sock->print(headers);
// The upload buffer lives on the HEAP, not in this frame.
//
// This function runs on the Arduino loop task, whose stack is 8 kB, and
// `sock->write()` below descends into mbedtls, which wants a couple of
// kilobytes of it to build and encrypt a TLS record. A 4 kB array declared
// here took half the stack before that call was even made, leaving the canary
// a few hundred bytes away on the classic ESP32 — whose windowed-ABI frames
// are larger than the C6's, which is part of why the same firmware crashed on
// one board and not the other. The firmware relay next door has always kept
// its own relay buffer at 1 kB for the same reason; this path is the one that
// got it wrong.
//
// 4 kB is still the right CHUNK — it batches roughly seventeen notifications
// into one TLS record — so move it rather than shrink it.
//
// The allocation carries the chunk framing as well as the payload: CHUNK_SLACK
// bytes ahead of it for the hex length line and two behind it for the trailing
// CRLF, so the whole HTTP chunk goes out as ONE socket write. See sendChunk().
std::unique_ptr<uint8_t, void (*)(void*)> uploadBuf(
(uint8_t*)malloc(CHUNK_SLACK + HIVEINSIDE_AUDIO_UPLOAD_CHUNK + 2), ::free);
uint8_t* const buf = uploadBuf ? uploadBuf.get() + CHUNK_SLACK : nullptr;
if (!buf) {
setMsg("out of memory for the audio upload buffer");
Serial.printf("[HI-AUD] out of memory for the %u B audio upload buffer "
"(free heap %u, largest block %u)\n",
(unsigned)HIVEINSIDE_AUDIO_UPLOAD_CHUNK,
(unsigned)ESP.getFreeHeap(), (unsigned)ESP.getMaxAllocHeap());
sock->print("0\r\n\r\n");
sock->stop();
return false;
}
bool bleOk = gattaudio::begin(mac, durationDs, gainDb);
if (!bleOk) {
setMsg(gattaudio::lastError().length() ? gattaudio::lastError()
: String("audio session failed to start"));
// Close the body cleanly anyway: the backend then sees a zero-byte
// recording it can mark failed, instead of a half-open socket it has to
// time out.
sock->print("0\r\n\r\n");
sock->stop();
gattaudio::cleanup();
return false;
}
// Both radios and the ring are now resident at once — the tightest the heap
// gets on this hub, so say what it looks like. logDiag(), NOT probe():
// checkIntegrity() walks every block in the heap, and the node is already
// streaming 32 kB/s into a one-second ring by the time this line is reached.
// Spending that walk here costs audio.
heapdiag::logDiag("audio-session-open");
// Send one HTTP chunk as a SINGLE socket write.
//
// Every NetworkClientSecure::write() becomes exactly one mbedtls_ssl_write(),
// so the old three-call form (hex length, payload, CRLF) spent three TLS
// records — three lots of ~29 B of framing plus their TCP segments — on every
// chunk, to carry two payload-less lines. At a few hundred chunks a second
// that is the difference between the upload keeping up with the node and the
// staging ring overrunning, which the recording shows as seams.
//
// `buf` deliberately sits CHUNK_SLACK bytes into its allocation so the length
// line can be written immediately BEFORE the payload without moving it.
auto sendChunk = [&](size_t n) -> bool {
char hdr[CHUNK_SLACK + 1];
const int hdrLen = snprintf(hdr, sizeof(hdr), "%X\r\n", (unsigned)n);
if (hdrLen <= 0 || (size_t)hdrLen > CHUNK_SLACK) return false; // unreachable
uint8_t* const start = buf - hdrLen;
memcpy(start, hdr, (size_t)hdrLen);
buf[n] = '\r';
buf[n + 1] = '\n';
const size_t total = (size_t)hdrLen + n + 2;
return sock->write(start, total) == total;
};
const uint32_t maxMs = (uint32_t)HIVEINSIDE_AUDIO_MAX_SECONDS * 1000UL;
const unsigned long startedMs = millis();
unsigned long lastDataMs = startedMs;
uint32_t uploaded = 0;
bool stalled = false, socketLost = false;
while (true) {
// The cap is checked FIRST, before the drain, because it is the only bound
// on this loop that does not depend on the node going quiet.
//
// It used to live below the `continue`, in the branch reached only when
// the ring came back EMPTY. That is the common case — the upload usually
// outruns 32 kB/s — but it is not guaranteed: an open-ended session, where
// the node streams until it is told to stop, keeps refilling the ring while
// the upload drains it, and for as long as a packet is always waiting the
// cap is never read. A bound that a busy link can skip is not a bound.
if (millis() - startedMs > maxMs) {
// The node caps itself at 60 s; reaching this means it never sent a final
// packet, so end the session from this side rather than holding a hive
// off the air indefinitely.
Serial.println("[HI-AUD] hub-side cap reached; stopping the session");
gattaudio::stop();
break;
}
size_t n = gattaudio::read(buf, HIVEINSIDE_AUDIO_UPLOAD_CHUNK);
if (n > 0) {
if (!sendChunk(n)) { socketLost = true; break; }
uploaded += n;
lastDataMs = millis();
if ((uploaded % (64 * 1024)) < n) {
Serial.printf("[HI-AUD] uploaded %u B (%lus)\n", (unsigned)uploaded,
(millis() - startedMs) / 1000UL);
}
continue; // drain hard while there is anything buffered
}
if (!gattaudio::streaming()) break; // node finished; loop once more drained
if (!sock->connected()) { socketLost = true; break; }
if (millis() - lastDataMs > (unsigned long)HIVEINSIDE_AUDIO_STALL_S * 1000UL) {
stalled = true;
break;
}
delay(5);
}
// Tell the node to stop BEFORE draining what it already sent.
//
// Ordered the other way — drain first, stop after — the loop below was
// reading a ring that the node was still filling, and "drain until empty" is
// not a terminating condition against a producer that never stops. Stopping
// first makes the ring a fixed amount of audio, so the drain always ends.
// stop() is idempotent, so the cap path above having already sent one costs
// nothing here.
gattaudio::stop();
// Whatever is still in the ring belongs to this recording. Bounded by the
// stall timeout, because a stopped node's ring is at most one ring-full of
// audio and anything slower than that is a socket that has stopped draining:
// this is the last place one could hold the cycle open, and a few seconds of
// tail audio is not worth a hub that never comes back.
const unsigned long drainDeadline = millis() + HIVEINSIDE_AUDIO_STALL_S * 1000UL;
size_t n = 0;
while (!socketLost && (long)(drainDeadline - millis()) > 0 &&
(n = gattaudio::read(buf, HIVEINSIDE_AUDIO_UPLOAD_CHUNK)) > 0) {
// Checked, like the main loop: a short write here would declare a chunk
// length the body does not carry and mis-frame everything after it.
if (!sendChunk(n)) { socketLost = true; break; }
uploaded += n;
}
gattaudio::Stats stats;
bool sessionOk = gattaudio::finish(&stats);
String sessionErr = gattaudio::lastError();
gattaudio::cleanup();
int httpStatus = 0;
if (!socketLost) {
sock->print("0\r\n\r\n");
// Read just the status line; the body carries nothing this side needs.
// `(long)(deadline - millis()) > 0`, not `millis() < deadline`, matching
// the follow-up window in checkCommands(). The plain comparison reads as
// "already expired" for the ~15 s after millis() wraps, which would skip
// the read and report HTTP 0 for an upload that in fact succeeded.
unsigned long deadline = millis() + HTTP_REQUEST_TIMEOUT_MS;
String line;
while ((long)(deadline - millis()) > 0 && sock->connected() &&
line.length() == 0) {
if (sock->available()) line = sock->readStringUntil('\n');
else delay(10);
}
int sp = line.indexOf(' ');
if (sp > 0) httpStatus = line.substring(sp + 1, sp + 4).toInt();
Serial.printf("[HI-AUD] upload HTTP %d, %u B\n", httpStatus, (unsigned)uploaded);
}
sock->stop();
heapdiag::probe("audio-end");
// Report the session to the backend even when it went badly: a recording row
// that never hears back is indistinguishable from a hub that died, and the
// dashboard would show "recording…" forever.
JsonDocument fin;
fin["bytes"] = uploaded;
fin["crc32"] = stats.crc32;
fin["device_bytes"] = stats.deviceBytes;
fin["device_crc32"] = stats.deviceCrc;
fin["dropped_bytes"] = stats.droppedBytes;
fin["elapsed_ms"] = stats.elapsedMs;
// Reported SEPARATELY since 0.30.2. Summing them was defensible while both
// meant "a seam", but it made the one question a field report actually asks —
// did the radio lose this, or did the hub? — unanswerable without a serial
// cable. `gaps` is now sequence discontinuities on the air (or the node's own
// FLAG_GAP); `ring_overruns` is notifications this hub's staging ring refused
// because the upload was behind. A server older than 0.6.0 ignores the second
// field and simply under-reports, which beats blaming the wrong side.
fin["gaps"] = stats.gaps;
fin["ring_overruns"] = stats.ringOverruns;
fin["ring_dropped_bytes"] = stats.ringDroppedBytes;
fin["sample_rate"] = stats.sampleRate ? stats.sampleRate : 16000;
fin["clipped_pct"] = stats.clippedPct;
fin["device_error"] = stats.error;
String reason;
bool ok = sessionOk && !socketLost && !stalled &&
httpStatus >= 200 && httpStatus < 300;
if (!sessionOk) reason = sessionErr;
else if (stalled) reason = String("no audio for ") + HIVEINSIDE_AUDIO_STALL_S +
"s; session abandoned";
else if (socketLost) reason = "upload connection lost mid-session";
else if (httpStatus < 200 || httpStatus >= 300)
reason = String("backend rejected the upload (HTTP ") + httpStatus + ")";
fin["ok"] = ok;
if (reason.length()) fin["error"] = reason;
String finPayload;
serializeJson(fin, finPayload);
httpPostJson(apiUrl(base + "/finalize"), finPayload);
if (ok) {
// A recording with holes in it is still useful, but the operator has to be
// told rather than left to notice a seam by ear.
String msg = String("recorded ") + uploaded + " B (" +
String(stats.elapsedMs / 1000.0f, 1) + " s)";
if (stats.droppedBytes || stats.gaps || stats.ringOverruns) {
msg += String(" (INCOMPLETE: ") + stats.droppedBytes +
" B dropped by the node, " + stats.gaps + " gap(s) on the air, " +
stats.ringOverruns + " lost to the hub's buffer)";
} else if (stats.crc32 != stats.deviceCrc) {
msg += " (CRC mismatch — audio was corrupted in transit)";
}
setMsg(msg);
} else {
setMsg(reason.length() ? reason : String("audio session failed"));
}
Serial.printf("[HI-AUD] result: %s (%s)\n", ok ? "OK" : "FAIL",
outMsg ? outMsg->c_str() : "");
return ok;
}
bool recordHiveInsideAudio(const String& mac, long recordingId,
uint16_t durationDs, int8_t gainDb, String* outMsg) {
return relayAudioSession(mac, recordingId, durationDs, gainDb, outMsg);
}
#endif // HIVEINSIDE_AUDIO_ENABLED
void checkForOtaUpdate() {
if (!connectNetwork()) {
Serial.println("[OTA] Skipping: network unavailable");
return;
}
JsonDocument doc;
// Report the board/architecture so the backend only offers an image built for
// this SoC (see HIVEHUB_BOARD_LABEL in config.h). Without it the server cannot
// tell a 30-pin ESP32 from an ESP32-C6 and could hand over a non-bootable image.
String url = apiUrl(String("/api/v1/devices/") + deviceId +
"/firmware?version=" + FIRMWARE_VERSION +
"&board=" + HIVEHUB_BOARD_LABEL);
Serial.println("[OTA] Checking for update");
if (!httpGetJson(url, doc)) {
Serial.println("[OTA] Check failed");
return;
}
bool updateAvailable = doc["update"] | false;
if (!updateAvailable) {
Serial.println("[OTA] No update available");
return;
}
String version = doc["version"] | "unknown";
String fwUrl = doc["url"] | "";
// Image size + CRC-32, sent by newer backends. The size stands in for a
// missing Content-Length header (proxy/CDN chunking) and the CRC lets the
// download be verified before flashing; both default to 0 (= unknown) when
// the backend predates them.
int fwSize = doc["size"] | 0;
uint32_t fwCrc = doc["crc32"] | 0U;
if (fwUrl.length() == 0) {
Serial.println("[OTA] Update response missing url");
return;
}
Serial.printf("[OTA] Update available: %s\n", version.c_str());
performFirmwareUpdate(fwUrl, fwSize, fwCrc);
}
// ---- Crash-safe relay reporting -------------------------------------------
//
// A firmware relay runs synchronously for minutes and only reports its outcome
// once it returns, so any reset in between loses the result entirely. The
// backend cannot tell that apart from a hub that never picked the command up:
// it waits STALE_CLAIM_MINUTES, re-queues, and after MAX_COMMAND_ATTEMPTS
// closes the row with "timed out: claimed by the device N time(s) without
// reporting a result" — an hour later, and saying nothing about what happened.
//
// So leave a note in RTC memory before starting and clear it on the way out.
// A boot that finds the note still set knows a relay died mid-flight, and can
// say so against the right command id while the row is still open.
static const uint32_t RELAY_MARKER_MAGIC = 0x48524C59UL; // "HRLY"
// What was running, so the report after a reset names it. A hub that dies
// during a recording used to tell the dashboard "firmware transfer did not
// complete", which sent the operator looking for an OTA that never happened.
enum RelayKind : uint32_t {
RELAY_KIND_FIRMWARE = 0, // also what an unrecognised value is treated as
RELAY_KIND_AUDIO = 1,
};
static void markRelayInFlight(int commandId, RelayKind kind) {
rtcRelayCommandId = (uint32_t)commandId;
// Kind before magic: the magic is what makes the whole record believable, so
// it must be the last field written and the first one checked.
rtcRelayKind = (uint32_t)kind;
rtcRelayMagic = RELAY_MARKER_MAGIC;
}
// Cleared as soon as the relay returns, deliberately BEFORE the result is
// posted. Covering the POST too would mean a reset in the microseconds between
// a successful POST and the clear would overwrite a true "OTA completed" with a
// fabricated failure. The relay is the multi-minute risky part; the POST is the
// same short path three earlier requests in this cycle already took. Better to
// leave that sliver uncovered than to invent a failure that did not happen.
static void clearRelayInFlight() {
rtcRelayCommandId = 0;
rtcRelayKind = RELAY_KIND_FIRMWARE;
rtcRelayMagic = 0;
}
// Report a relay that a reset interrupted. Called once per cycle, before the
// next command is fetched, so the stale row is corrected before anything else
// is claimed.
static void reportInterruptedRelay() {
if (rtcRelayMagic != RELAY_MARKER_MAGIC || rtcRelayCommandId == 0) return;
const int commandId = (int)rtcRelayCommandId;
const bool wasAudio = (rtcRelayKind == RELAY_KIND_AUDIO);
// Clear FIRST. If the report itself is what kills us, the next boot must not
// find the same marker and try again forever; one lost report beats a loop.
clearRelayInFlight();
String msg = String("hub reset during relay (") + resetReasonName() + ") — " +
(wasAudio ? "the audio session did not complete"
: "firmware transfer did not complete");
Serial.printf("[CMD] Reporting interrupted relay for command %d: %s\n",
commandId, msg.c_str());
postCommandResult(commandId, false, msg);
}
void postCommandResult(int commandId, bool success, const String& message) {
JsonDocument result;
result["success"] = success;
result["message"] = message;
String payload;
serializeJson(result, payload);
httpPostJson(apiUrl(String("/api/v1/devices/") + deviceId + "/commands/" + commandId + "/result"), payload);
}
// Claim and run at most one queued command. Returns true when one ran, and
// sets *wasAudio when it was an audio session — checkCommands() uses that to
// stay awake briefly for a follow-up, so a second request does not wait for the
// next wake cycle.
static bool runOneCommand(bool* wasAudio) {
if (wasAudio) *wasAudio = false;
JsonDocument doc;
String url = apiUrl(String("/api/v1/devices/") + deviceId + "/commands/next");
Serial.println("[CMD] Checking for command");
if (!httpGetJson(url, doc)) {
Serial.println("[CMD] Command check failed");
return false;
}
bool hasCommand = doc["command"] | false;
if (!hasCommand) {
Serial.println("[CMD] No pending command");
return false;
}
int commandId = doc["id"] | 0;
String type = doc["command_type"] | "";
JsonObject payload = doc["payload"].as<JsonObject>();
Serial.printf("[CMD] Received command %d: %s\n", commandId, type.c_str());
if (type == "reset_preferences" || type == "factory_reset") {
postCommandResult(commandId, true, "Preferences reset; rebooting");
delay(500);
factoryResetPreferences();
} else if (type == "reset_wifi") {
clearWifiCredentials();
postCommandResult(commandId, true, "WiFi credentials cleared");
delay(500);
ESP.restart();
} else if (type == "check_ota" || type == "ota_update") {
postCommandResult(commandId, true, "OTA check started");
checkForOtaUpdate();
}
#if !(ENABLE_WIRELESS_BEECOUNTER && BEECOUNTER_OTA_ENABLED)
else if (type == "update_beecounter") {
// This build has no counter to relay to (or the relay was compiled out).
// Fail EXPLICITLY — never pretend to have updated — so the queued command
// surfaces as failed in the backend instead of hanging or faking success.
Serial.println("[CMD] Rejecting update_beecounter: BeeCounter OTA is not compiled into this build");
postCommandResult(commandId, false,
"update_beecounter is not supported by this firmware build "
"(rebuild with ENABLE_WIRELESS_BEECOUNTER=1)");
}
#endif
#if ENABLE_BLE_SCAN && HIVEINSIDE_OTA_ENABLED
else if (type == "update_hiveinside") {
// payload: { "slot": 1..MAX_HIVES, "url": "/firmware/hiveinside-x.y.bin", "crc32": <uint32> }
// The MAC is resolved locally from the hive registry, so the backend never
// needs to know the device address. `slot` is the hive index: the lookup
// covers every hive, and it matches only HiveInside pairings — the legacy
// bleSensorMac0/1 globals it replaces reached the first two hives only and
// held the first beacon of ANY type, so a hive whose first pairing was a
// HolyIot or RuuviTag aimed the relay at the wrong device.
int slot = payload["slot"] | 1;
String mac = hivecfg::hiveInsideMacForSlot((uint8_t)slot);
String fwUrl = payload["url"] | "";
// `| 0U`, never `| 0`: ArduinoJson deduces the type from the default, and a
// signed `int` is 32-bit here, so is<int>() is false for any CRC above
// 2147483647 and the fallback (0) is taken. The node was then told to expect
// crc32 = 0, computed the real one, and rejected a perfectly transferred
// image with OTA_ERR_CRC (state=0x13). Since roughly half of all CRC-32
// values exceed 2^31 this made the relay a coin flip — it worked with
// hiveinside 0.3.5 (crc 128852642) and failed with 0.4.2 (crc 2602123579).
// The hub's own self-update path had this right (`| 0U`) all along.
uint32_t crc = payload["crc32"] | 0U;
if (fwUrl.length() == 0) {
postCommandResult(commandId, false, "update_hiveinside missing url");
} else if (mac.length() == 0) {
postCommandResult(commandId, false, String("No HiveInside paired in slot ") + slot);
} else {
// Report the FINAL result with a specific cause, not "started": the relay
// runs synchronously (it can take minutes for a >1 MB image) and we only
// know the real outcome once updateHiveInside returns. Reporting "started"
// eagerly was the main reason a failed OTA still looked successful.
String resultMsg;
// Note the attempt before starting: a reset during the transfer otherwise
// leaves the row to time out silently an hour later.
markRelayInFlight(commandId, RELAY_KIND_FIRMWARE);
bool ok = updateHiveInside(mac, fwUrl, crc, &resultMsg);
clearRelayInFlight();
Serial.printf("[HI-OTA] update result: %s (%s)\n",
ok ? "OK" : "FAIL", resultMsg.c_str());
postCommandResult(commandId, ok,
resultMsg.length() ? resultMsg
: (ok ? "HiveInside OTA completed"
: "HiveInside OTA failed"));
}
}
#endif
#if HIVEINSIDE_AUDIO_ENABLED
else if (type == "record_audio") {
// payload: { "slot": 1..MAX_HIVES, "recording_id": <int>,
// "duration_ds": <0 = live/open-ended>, "gain_db": <-20..20> }
//
// No URL in the payload — the upload target is derived from this hub's own
// device id (see relayAudioSession). Microphone audio must never be posted
// to an address a queued command chose.
int slot = payload["slot"] | 1;
long recordingId = payload["recording_id"] | 0L;
uint16_t durationDs = (uint16_t)(payload["duration_ds"] | 0U);
int8_t gainDb = (int8_t)(payload["gain_db"] | 0);
String mac = hivecfg::hiveInsideMacForSlot((uint8_t)slot);
if (recordingId <= 0) {
postCommandResult(commandId, false, "record_audio missing recording_id");
} else if (mac.length() == 0) {
postCommandResult(commandId, false, String("No HiveInside paired in slot ") + slot);
} else {
// Same crash-safe marker as the OTA relays: a session runs for up to a
// minute and only reports at the end, so a reset in the middle would
// otherwise strand the row until the backend's stale sweep noticed.
markRelayInFlight(commandId, RELAY_KIND_AUDIO);
String resultMsg;
bool ok = recordHiveInsideAudio(mac, recordingId, durationDs, gainDb, &resultMsg);
clearRelayInFlight();
if (wasAudio) *wasAudio = ok;
postCommandResult(commandId, ok,
resultMsg.length() ? resultMsg
: (ok ? "audio session completed"
: "audio session failed"));
}
}
#else
else if (type == "record_audio") {
// Fail explicitly rather than silently: a hub built without the BLE scan
// has no way to reach a HiveInside at all, and a command that just vanished
// would look like a dead node.
postCommandResult(commandId, false,
"record_audio is not supported by this firmware build "
"(needs ENABLE_BLE_SCAN)");
}
#endif
#if ENABLE_WIRELESS_BEECOUNTER && BEECOUNTER_OTA_ENABLED
else if (type == "update_beecounter") {
// payload: { "slot": 1..MAX_HIVES, "url": "/firmware/beecounter-x.y.bin", "crc32": <uint32> }
// Same shape and same resolution rules as update_hiveinside above: the MAC
// comes from the local hive registry, so the backend never needs to know
// the device address, and `slot` is the hive index rather than one of two
// legacy globals.
int slot = payload["slot"] | 1;
String mac = hivecfg::beeCounterMacForSlot((uint8_t)slot);
String fwUrl = payload["url"] | "";
// `| 0U`, never `| 0` — see the note on the HiveInside handler above. A
// signed-int default makes is<int>() false for any CRC above 2147483647,
// silently substituting 0 and making the relay fail on roughly half of all
// images with a bogus CRC mismatch.
uint32_t crc = payload["crc32"] | 0U;
if (fwUrl.length() == 0) {
postCommandResult(commandId, false, "update_beecounter missing url");
} else if (mac.length() == 0) {
postCommandResult(commandId, false, String("No HiveTraffic counter paired in slot ") + slot);
} else {
// Report the FINAL result, not "started": the relay is synchronous and
// the counter stops counting throughout, so the outcome matters and is
// only known once updateBeeCounter returns.
String resultMsg;
// Same crash-safe marker as the HiveInside relay above.
markRelayInFlight(commandId, RELAY_KIND_FIRMWARE);
bool ok = updateBeeCounter(mac, fwUrl, crc, &resultMsg);
clearRelayInFlight();
Serial.printf("[BC-OTA] update result: %s (%s)\n",
ok ? "OK" : "FAIL", resultMsg.c_str());
postCommandResult(commandId, ok,
resultMsg.length() ? resultMsg
: (ok ? "HiveTraffic counter OTA completed"
: "HiveTraffic counter OTA failed"));
}
}
#endif
else if (type == "start_provisioning") {
// This only makes sense while someone is physically near the device.
//
// Only *requested* here, not started: opening the AP switches the radio out
// of station mode, and this runs in the middle of an upload cycle that
// still has cached lines to flush and an OTA check to make. The cycle opens
// the portal as soon as it is finished (see startRequestedProvisioningPortal
// in main.cpp), which is the same point a button press reaches it — so a
// hub sealed in a box behaves exactly as if somebody had pressed setup.
requestProvisioningPortal();
// Reported before the AP opens, and deliberately so: the hub may have to
// reboot at the end of this cycle to give the portal's BLE discovery scan a
// NimBLE port lifetime it is allowed to scan in (see
// startRequestedProvisioningPortal), and after a reboot there is no station
// connection left to report anything on.
postCommandResult(commandId, true,
"Provisioning AP starting at the end of this cycle "
"(the hub may reboot first so BLE pairing can scan)");
} else if (type == "start_calibration_mode") {
unsigned long intervalSeconds = payload["interval_seconds"] | (CALIBRATION_MODE_DEFAULT_INTERVAL_MS / 1000UL);
unsigned long timeoutSeconds = payload["timeout_seconds"] | (CALIBRATION_MODE_DEFAULT_TIMEOUT_MS / 1000UL);
startCalibrationMode(intervalSeconds, timeoutSeconds);
postCommandResult(commandId, true, "Calibration mode started");
} else if (type == "stop_calibration_mode") {
stopCalibrationMode("command received");
postCommandResult(commandId, true, "Calibration mode stopped");
} else if (type == "start_inspection") {
// How HivePal's in-app "start inspection" button reaches a hub. The result
// POST is what the backend shows as "the hub has picked this up" — until it
// arrives the inspection is only requested, not running.
inspection::setActive(true, "command");
postCommandResult(commandId, true, "Inspection mode started");
} else if (type == "stop_inspection") {
inspection::setActive(false, "command");
postCommandResult(commandId, true, "Inspection mode stopped");
} else {
postCommandResult(commandId, false, String("Unknown command: ") + type);
}
return true;
}
void checkCommands() {
if (!connectNetwork()) return;
// Close out a relay that a reset interrupted before claiming anything new.
reportInterruptedRelay();
bool wasAudio = false;
if (!runOneCommand(&wasAudio)) return;
#if HIVEINSIDE_AUDIO_ENABLED
// Somebody asking a hive for audio is usually not asking once — a second
// hive, a longer take, another listen after hearing the first. Each of those
// would otherwise wait a full send interval, turning a two-minute task into a
// half-hour one.
//
// So after an audio session — and only then — stay up briefly and keep
// polling. A hub nobody is recording from never enters this loop.
if (!wasAudio) return;
unsigned long deadline = millis() + HIVEINSIDE_AUDIO_FOLLOWUP_MS;
Serial.printf("[HI-AUD] holding the cycle open %u ms for a follow-up session\n",
(unsigned)HIVEINSIDE_AUDIO_FOLLOWUP_MS);
while ((long)(deadline - millis()) > 0) {
delay(2000);
bool again = false;
if (!runOneCommand(&again)) continue;
// Some other command arrived — hand the cycle back rather than holding it
// open for work that has nothing to do with listening.
if (!again) return;
// Another session ran: restart the window from now, so a listener who
// keeps pressing "continue" is never cut off by the original deadline.
deadline = millis() + HIVEINSIDE_AUDIO_FOLLOWUP_MS;
}
Serial.println("[HI-AUD] follow-up window closed");
#endif
}