Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
// sensors.cpp — time sync, scale reads and measurement JSON assembly.
#include "sensors.h"
#include "inspection.h"
#include <esp_system.h>
#include "globals.h"
#include "config.h"
#include "hivehub_network.h"
#include "storage_power.h"
#include "bee_counter_client.h"
#include "hive_config.h"
#include "i2c_bus.h"
#include "scale_bus.h"
#include "scale_math.h"
#include "sht4x_recovery.h"
#include <WiFi.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h> // setenv(), for the night-mode timezone
#include <math.h>
#include <vector>
#if ENABLE_INMP441_MICS
#include "mics.h"
#endif
#if ENABLE_BLE_SCAN
#include "ble_sensor.h"
#endif
#if ENABLE_BEEHIVE_GATT
#include "beehive_gatt.h"
#endif
#include "night_mode.h" // nightmode::MINUTES_PER_DAY, the "no clock" sentinel
void initializeTime(bool wokeFromDeepSleep) {
if (rtcHasValidTime()) {
timeSource = "rtc";
Serial.print("[TIME] Using RTC: ");
Serial.println(timestampNow());
// Refresh RTC from NTP on cold/manual boots, but avoid doing this on every
// timer wake because WiFi will already be used for upload and RTC is valid.
if (!wokeFromDeepSleep) {
syncTime();
}
return;
}
syncTime();
}
// ---------------------------------------------------------------------------
// Local wall-clock time, for the HiveTraffic night-mode window
// ---------------------------------------------------------------------------
// Everything else in this firmware works in UTC and never has to care: readings
// carry a UTC timestamp and the backend does the rest. Night mode is the one
// feature the beekeeper expresses in local time — "20:00" means 20:00 at the
// apiary — so this is where UTC becomes local, and the only place a timezone
// exists at all.
//
// It matters more than it looks. configTime(0, 0, ...) puts the device on UTC,
// so without a TZ a window entered as 20:00 would fire at 21:00 local in
// summer and 20:00 in winter — an hour of foraging silently discarded on the
// long evenings when there is most of it. The TZ string carries the DST rules,
// so the window tracks the clock on the wall all year.
// Push the configured POSIX TZ into the C library, when it changes. Cheap and
// idempotent: called from the accessor below rather than from a setup path, so
// no ordering between "config arrived" and "window evaluated" can leave a stale
// zone in place.
static void applyNightTimezone() {
static String applied = "\x01"; // impossible value: forces the first apply
if (applied == nightTimezone) return;
applied = nightTimezone;
if (nightTimezone.length()) {
setenv("TZ", nightTimezone.c_str(), 1);
} else {
setenv("TZ", "UTC0", 1);
}
tzset();
Serial.printf("[TIME] Timezone set to %s\n",
nightTimezone.length() ? nightTimezone.c_str() : "UTC");
}
// Current UTC epoch, or 0 when there is no trustworthy clock.
//
// The system clock is preferred because NTP sets it directly; the DS3231 is the
// fallback for a boot with no WiFi. Both hold UTC — syncTime() writes gmtime()
// into the RTC — so DateTime::unixtime() is a straight conversion and no
// timezone is involved on this side.
static time_t currentUtcEpoch() {
const time_t sys = time(nullptr);
if (sys > 1700000000) return sys; // plausible: past Nov 2023
if (rtcHasValidTime()) return (time_t)rtc.now().unixtime();
return 0;
}
uint16_t localMinuteOfDay() {
const time_t epoch = currentUtcEpoch();
// No clock: the caller must treat this as "do not guess". An unsynced device
// reports a plausible-looking 1970, which is the middle of the night, and
// would otherwise park every counter in the fleet indefinitely.
if (epoch == 0) return nightmode::MINUTES_PER_DAY;
applyNightTimezone();
struct tm local;
if (localtime_r(&epoch, &local) == nullptr) return nightmode::MINUTES_PER_DAY;
return (uint16_t)(local.tm_hour * 60 + local.tm_min);
}
String timestampNow() {
if (rtcOk) {
DateTime now = rtc.now();
// A wedged driver makes rtc.now() return zeroed registers (year 2000). Heal
// once and re-read so a bus that another device wedged doesn't force the
// timestamp onto the NTP/1970 fallback.
if (!(now.year() >= 2024 && now.year() <= 2099) && i2cbus::healForRead()) {
now = rtc.now();
}
if (now.year() >= 2024 && now.year() <= 2099) {
char buf[25];
snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02dZ", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second());
return String(buf);
}
}
struct tm tmNow;
if (getLocalTime(&tmNow, 100)) {
char buf[25];
snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02dZ", tmNow.tm_year + 1900, tmNow.tm_mon + 1, tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec);
return String(buf);
}
return String("1970-01-01T00:00:00Z");
}
void syncTime() {
if (connectWifi()) {
Serial.println("[TIME] Syncing with NTP...");
configTime(0, 0, "pool.ntp.org", "time.nist.gov", "time.google.com");
struct tm tmNow;
for (int i = 0; i < 20; i++) {
if (getLocalTime(&tmNow, 500)) {
time_t nowUnix = mktime(&tmNow);
if (nowUnix > 1700000000) {
Serial.println("[TIME] NTP sync OK");
timeSource = "ntp";
if (rtcOk) {
struct tm* utc = gmtime(&nowUnix);
rtc.adjust(DateTime(utc->tm_year + 1900, utc->tm_mon + 1, utc->tm_mday, utc->tm_hour, utc->tm_min, utc->tm_sec));
Serial.println("[TIME] RTC updated from NTP");
}
Serial.print("[TIME] Current timestamp: ");
Serial.println(timestampNow());
return;
}
}
delay(500);
}
Serial.println("[TIME] NTP sync FAILED");
} else {
Serial.println("[TIME] Cannot sync time: WiFi unavailable");
}
// NTP was unavailable (no WiFi, or the sync attempt failed). Fall back to the
// RTC if it holds a plausible time; otherwise we have no trustworthy wall
// clock. Both no-WiFi and NTP-failure paths must land here so the outcome is
// the same: mark the time invalid instead of leaving a stale "unknown", which
// previously caused the offline no-RTC path to emit a bogus 1970 timestamp.
// "invalid" makes buildMeasurementDoc() omit the timestamp entirely and lets
// the server stamp the reading with its receive time.
if (rtcHasValidTime()) {
timeSource = "rtc";
Serial.println("[TIME] Using RTC");
return;
}
timeSource = "invalid";
}
float weightFromRaw(long raw, long offset, float factor) {
if (factor == 0.0f) return NAN;
return ((float)(raw - offset)) / factor;
}
// Human-readable reason a checked scale read was rejected — for the serial log,
// so a field report can name the failing stage (device, mux channel, ADC
// channel and hive index are printed alongside by the caller).
static const char* scaleFailReason(const scalebus::ReadResult& r) {
if (r.notConfigured) return "not configured / bus down / chip init failed";
if (r.routeFailed) return "mux routing failed (unverified selection)";
if (r.channelSwitchFailed) return "ADC channel switch unverified";
if (r.timedOut) return "conversion timeout";
if (r.samplesAcquired < r.samplesRequested) return "incomplete sample set";
if (r.railed) return "railed/zero raw (open input or no chip)";
if (r.unstable) return "unstable (sample spread too high)";
return "I2C communication error";
}
static const char* scaleBackendName(hivecfg::ScaleBackend b) {
switch (b) {
case hivecfg::ScaleBackend::HX711: return "hx711";
case hivecfg::ScaleBackend::NAU7802: return "nau7802";
default: return "none";
}
}
#if ENABLE_BLE_SCAN
// First present in-hive snapshot mapped to hive-array slot `hiveArrIdx` (else the
// first one paired to that hive even if absent, so callers can still report it).
static const blesensor::Snapshot* snapForHive(
const std::vector<int>& hiveOfMac,
const std::vector<blesensor::Snapshot>& snaps,
int hiveArrIdx) {
const blesensor::Snapshot* fallback = nullptr;
for (size_t i = 0; i < snaps.size() && i < hiveOfMac.size(); i++) {
if (hiveOfMac[i] != hiveArrIdx) continue;
if (snaps[i].present) return &snaps[i];
if (!fallback) fallback = &snaps[i];
}
return fallback;
}
#endif
#if ENABLE_BEEHIVE_GATT
static void writeBeehiveHeartToHive(JsonObject ho, const bhgatt::HeartReading& heart) {
JsonObject obj = ho["hiveheart"].to<JsonObject>();
obj["present"] = true;
obj["temp_c"] = heart.temp_c;
obj["humidity_percent"] = heart.humidity_pct;
obj["frequency_hz"] = heart.frequency_hz;
obj["energy"] = heart.energy;
obj["peak"] = heart.peak;
obj["battery_v"] = heart.battery_v;
obj["rssi_dbm"] = heart.rssi_dbm;
if (heart.fft_present) {
JsonArray fft = obj["fft"].to<JsonArray>();
for (int j = 0; j < 8; j++) fft.add(heart.fft[j]);
}
}
static void writeBeehiveScaleToHive(JsonObject ho, const bhgatt::ScaleReading& sc) {
JsonObject obj = ho["hivescale"].to<JsonObject>();
obj["present"] = true;
obj["weight_kg"] = sc.weight_kg;
obj["raw_weight"] = sc.raw_weight;
obj["temp_c"] = sc.temp_c;
obj["humidity_percent"] = sc.humidity_pct;
obj["pressure_hpa"] = sc.pressure_hpa;
obj["battery_v"] = sc.battery_v;
obj["rssi_dbm"] = sc.rssi_dbm;
}
#endif
// Per-hive wired-scale aggregate: filled by the pre-radio I2C pass and consumed
// during JSON assembly, so the NAU7802 transactions all run before any BLE/WiFi
// radio activity can wedge the C6 I2C peripheral. MAX_SCALES_PER_HIVE == 1, so
// one aggregate per hive is sufficient.
struct WiredScaleAgg {
double weightSum = 0.0;
bool anyScale = false; // at least one fully valid reading
bool triedWiredScale = false; // a wired NAU7802/HX711 channel exists
long firstRaw = 0;
const char* scaleSrc = "";
};
// Snapshot of the wired I2C readings captured pre-radio by the prefetch pass
// and consumed by buildMeasurementDoc().
struct WiredSensorSnapshot {
float ambientTemp = NAN;
float ambientHumidity = NAN;
float ambientPressure = NAN; // hPa; only a pressure-capable ambient sensor
// (BME280) fills this, else stays NAN/omitted
bool shtRead = false; // THIS cycle's ambient sensor read was valid
// (distinct from shtOk = detected at boot)
#if ENABLE_INA219_SOLAR
float solarBusVoltage = NAN, solarShuntVoltageMv = NAN, solarLoadVoltage = NAN;
float solarCurrentMa = NAN, solarPowerMw = NAN;
#endif
#if ENABLE_MAX17048_BATTERY
float batteryVoltage = NAN, batterySoc = NAN;
bool batteryAlert = false;
#endif
WiredScaleAgg scale[MAX_HIVES];
};
static WiredSensorSnapshot gWired;
// Each *Ops struct binds the Arduino-free acquisition sequence in sht4x_recovery.h
// to one ambient sensor family's real driver/I2C calls. On the first read failure
// the template heals the wedged ESP32-C6 driver and — crucially — FULLY
// reinitializes the driver object before the one bounded retry (Wire.end()/begin()
// invalidates the cached I2C device the driver holds, so a bare re-read cannot
// recover). read() stores the values on success. See sht4x_recovery.h for why the
// ordering matters. Exactly one family is compiled (config.h), so at most one of
// these structs exists in any build.
#if ENABLE_SHT4X_AMBIENT
struct Sht4xOps {
float& tempC;
float& humidity;
bool read() {
sensors_event_t humidityEvt, tempEvt;
if (!sht4.getEvent(&humidityEvt, &tempEvt)) return false;
tempC = tempEvt.temperature;
humidity = humidityEvt.relative_humidity;
return true;
}
bool heal() { return i2cbus::healForRead(); }
bool ack() { return i2cbus::deviceResponds(SHT4X_I2C_ADDRESS); }
bool reinit() {
if (!sht4.begin(&Wire)) return false;
sht4.setPrecision(SHT4X_HIGH_PRECISION);
sht4.setHeater(SHT4X_NO_HEATER);
return true;
}
void onInitialFail() { Serial.println("[SHT4x] Initial read failed"); }
void onAck(bool ok) { Serial.printf("[SHT4x] ACK after I2C heal: %s\n", ok ? "yes" : "no"); }
void onReinit(bool ok) { Serial.printf("[SHT4x] Reinitialization after I2C heal: %s\n", ok ? "OK" : "FAILED"); }
void onRetry(bool ok) { Serial.printf("[SHT4x] Retry read: %s\n", ok ? "OK" : "FAILED"); }
};
#endif
#if ENABLE_SHT3X_AMBIENT
struct Sht3xOps {
float& tempC;
float& humidity;
bool read() {
float t = sht3.readTemperature();
float h = sht3.readHumidity();
if (isnan(t) || isnan(h)) return false;
tempC = t;
humidity = h;
return true;
}
bool heal() { return i2cbus::healForRead(); }
bool ack() { return i2cbus::deviceResponds(SHT3X_I2C_ADDRESS); }
bool reinit() {
if (!sht3.begin(SHT3X_I2C_ADDRESS)) return false;
sht3.heater(false);
return true;
}
void onInitialFail() { Serial.println("[SHT3x] Initial read failed"); }
void onAck(bool ok) { Serial.printf("[SHT3x] ACK after I2C heal: %s\n", ok ? "yes" : "no"); }
void onReinit(bool ok) { Serial.printf("[SHT3x] Reinitialization after I2C heal: %s\n", ok ? "OK" : "FAILED"); }
void onRetry(bool ok) { Serial.printf("[SHT3x] Retry read: %s\n", ok ? "OK" : "FAILED"); }
};
#endif
#if ENABLE_BME280_AMBIENT
struct Bme280Ops {
float& tempC;
float& humidity;
float& pressureHpa;
bool read() {
// Forced mode: kick a single conversion, then read the registers.
if (!bme.takeForcedMeasurement()) return false;
float t = bme.readTemperature();
float h = bme.readHumidity();
float p = bme.readPressure(); // Pa
if (isnan(t) || isnan(h) || isnan(p)) return false;
tempC = t;
humidity = h;
pressureHpa = p / 100.0f; // Pa -> hPa
return true;
}
bool heal() { return i2cbus::healForRead(); }
bool ack() { return i2cbus::deviceResponds(BME280_I2C_ADDRESS); }
bool reinit() {
if (!bme.begin(BME280_I2C_ADDRESS, &Wire)) return false;
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::SAMPLING_X1,
Adafruit_BME280::FILTER_OFF);
return true;
}
void onInitialFail() { Serial.println("[BME280] Initial read failed"); }
void onAck(bool ok) { Serial.printf("[BME280] ACK after I2C heal: %s\n", ok ? "yes" : "no"); }
void onReinit(bool ok) { Serial.printf("[BME280] Reinitialization after I2C heal: %s\n", ok ? "OK" : "FAILED"); }
void onRetry(bool ok) { Serial.printf("[BME280] Retry read: %s\n", ok ? "OK" : "FAILED"); }
};
#endif
// Returns true (and fills tempC/humidity, plus pressureHpa on pressure-capable
// parts) only when a real measurement was obtained, on the first try or the
// single post-heal retry. Dispatches to whichever ambient family is compiled.
static bool readAmbientSensor(float& tempC, float& humidity, float& pressureHpa) {
#if ENABLE_SHT4X_AMBIENT
(void)pressureHpa;
Sht4xOps ops{tempC, humidity};
return sht4xrec::acquire(ops).ok;
#elif ENABLE_SHT3X_AMBIENT
(void)pressureHpa;
Sht3xOps ops{tempC, humidity};
return sht4xrec::acquire(ops).ok;
#elif ENABLE_BME280_AMBIENT
Bme280Ops ops{tempC, humidity, pressureHpa};
return sht4xrec::acquire(ops).ok;
#else
(void)tempC; (void)humidity; (void)pressureHpa;
return false;
#endif
}
void prefetchAmbientSensors() {
// Phase 1: device-level ambient I2C sensors. This runs BEFORE
// scalebus::begin() probes the optional TCA9548A and before WiFi/BLE start —
// see the header note. On the ESP32-C6 a transaction to an absent device (the
// mux probe) or radio start-up wedges the I2C peripheral into
// ESP_ERR_INVALID_STATE; capturing the ambient SHT4x here, on the known-good
// bus, is the only reliable window. Resets the per-cycle snapshot and heal
// budget for the whole prefetch (phase 3 shares them).
Serial.println("[PREFETCH] Reading ambient wired I2C sensors before scale probe/radio...");
i2cbus::resetReadHeals();
gWired = WiredSensorSnapshot(); // fresh each cycle (setup runs every wake)
#if ENABLE_DS18B20_HIVE_TEMP
ds18b20.requestTemperatures();
#endif
// ── Ambient sensor (device-level, outside-hive: SHT4x/SHT3x/BME280) ─────────
if (shtOk) {
gWired.shtRead = readAmbientSensor(gWired.ambientTemp, gWired.ambientHumidity,
gWired.ambientPressure);
}
#if ENABLE_INA219_SOLAR
if (solarMonitorOk) {
solarMonitor.powerSave(false);
delay(10);
gWired.solarBusVoltage = solarMonitor.getBusVoltage_V();
gWired.solarShuntVoltageMv = solarMonitor.getShuntVoltage_mV();
gWired.solarCurrentMa = solarMonitor.getCurrent_mA();
gWired.solarPowerMw = solarMonitor.getPower_mW();
gWired.solarLoadVoltage = gWired.solarBusVoltage + (gWired.solarShuntVoltageMv / 1000.0f);
solarMonitor.powerSave(true);
}
#endif
#if ENABLE_MAX17048_BATTERY
if (batteryMonitorOk) {
gWired.batteryVoltage = batteryGauge.getVoltage();
// A connected LiPo never reads 0.0 V, so 0.0 means the VCELL read failed.
if (gWired.batteryVoltage == 0.0f && i2cbus::healForRead()) {
gWired.batteryVoltage = batteryGauge.getVoltage();
}
gWired.batterySoc = batteryGauge.getSOC();
gWired.batteryAlert = batteryGauge.getAlert();
if (gWired.batteryAlert) batteryGauge.clearAlert();
}
#endif
}
void prefetchWiredScales() {
// Phase 3: wired scales. Runs AFTER scalebus::begin() so no scale read is
// attempted before scale state has been initialized, and after phase 1 so the
// ambient SHT4x was captured before any absent-device probe. Shares the
// snapshot and heal budget prefetchAmbientSensors() reset at the cycle start.
// Power up the (HX711) scales before reading them; no-op on the C6 where the
// only scale backend is the I2C NAU7802 (configured by scalebus::begin()).
powerUpScales();
// ── Wired scales (NAU7802): cache one aggregate per hive. ──────────────────
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
const hivecfg::Hive& hive = hivecfg::gHives[h];
WiredScaleAgg& agg = gWired.scale[h];
for (uint8_t s = 0; s < hive.scaleCount; s++) {
const hivecfg::ScaleChannel& ch = hive.scales[s];
if (ch.backend == hivecfg::ScaleBackend::None) continue;
agg.triedWiredScale = true;
if (s == 0) agg.scaleSrc = scaleBackendName(ch.backend);
if (ch.configError) {
Serial.printf("[MEASURE] hive %u scale %u (%s) SKIPPED: invalid/conflicting configuration (fix in portal)\n",
hive.index, s, scaleBackendName(ch.backend));
continue;
}
scalebus::ReadResult rr = scalebus::readChannel(ch);
if (s == 0) agg.firstRaw = rr.raw;
if (!rr.ok) {
Serial.printf("[MEASURE] hive %u scale %u (%s addr=0x%02X mux=%d adc=%u) INVALID: %s "
"(samples %u/%u, commErr %u, spread %ld, recovery %s)\n",
hive.index, s, scaleBackendName(ch.backend),
ch.backend == hivecfg::ScaleBackend::NAU7802 ? NAU7802_I2C_ADDRESS : 0,
(int)ch.muxChannel, ch.adcChannel, scaleFailReason(rr),
rr.samplesAcquired, rr.samplesRequested, rr.commErrors, rr.spread,
rr.recoveryAttempted ? (rr.recoverySucceeded ? "ok" : "failed") : "none");
continue;
}
if (!scalemath::factorPlausible(ch.factor)) {
Serial.printf("[MEASURE] hive %u scale %u (%s) INVALID: calibration factor %.3f implausible\n",
hive.index, s, scaleBackendName(ch.backend), (double)ch.factor);
continue;
}
float kg = weightFromRaw(rr.raw, ch.offset, ch.factor);
if (!isnan(kg)) { agg.weightSum += kg; agg.anyScale = true; }
Serial.printf("[MEASURE] hive %u scale %u (%s mux=%d adc=%u) raw=%ld kg=%.3f "
"(samples %u/%u, spread %ld)\n",
hive.index, s, scaleBackendName(ch.backend), (int)ch.muxChannel,
ch.adcChannel, rr.raw, kg, rr.samplesAcquired, rr.samplesRequested,
rr.spread);
}
}
}
// Assemble the per-cycle payload into `doc`. Assembly is split from
// serialization so the caller can stamp fields that are only knowable after
// assembly has finished — specifically sd_ok: SD.begin() must not run before
// the RTC read below (it is the boundary after which the ESP32-C6 I2C-NG driver
// starts rejecting transfers), so the SD card is brought up by runUploadCycle()
// once this returns, and it stamps sd_ok itself.
void buildMeasurementDoc(JsonDocument& doc) {
Serial.println("[MEASURE] Assembling upload from pre-radio wired snapshot...");
// The wired I2C sensors (ambient SHT4x/SHT3x/BME280, INA219, MAX17048, NAU7802 scales) were
// captured by prefetchAmbientSensors()/prefetchWiredScales() BEFORE WiFi/BLE
// started, because radio
// start-up wedges the C6 I2C peripheral in a way Wire.end()/begin() cannot
// clear. Consume that snapshot here instead of reading live post-radio.
const float ambientTemp = gWired.ambientTemp;
const float ambientHumidity = gWired.ambientHumidity;
#if AMBIENT_HAS_PRESSURE
const float ambientPressure = gWired.ambientPressure;
#endif
const bool shtRead = gWired.shtRead;
#if ENABLE_INA219_SOLAR
const float solarBusVoltage = gWired.solarBusVoltage;
const float solarShuntVoltageMv = gWired.solarShuntVoltageMv;
const float solarLoadVoltage = gWired.solarLoadVoltage;
const float solarCurrentMa = gWired.solarCurrentMa;
const float solarPowerMw = gWired.solarPowerMw;
#endif
#if ENABLE_MAX17048_BATTERY
const float batteryVoltage = gWired.batteryVoltage;
const float batterySoc = gWired.batterySoc;
const bool batteryAlert = gWired.batteryAlert;
#endif
// The RTC timestamp is the only I2C touched in this (post-radio) function;
// timestampNow() falls back to NTP/system time when the RTC is absent or its
// read fails, so a radio-wedged bus cannot break the timestamp.
i2cbus::resetReadHeals();
String measuredAt;
if (timeSource != "invalid") measuredAt = timestampNow();
// ══ Phase 2: radio (BLE beacons + GATT). No I2C transaction runs past here. ═
// ── In-hive BLE beacon sensors for ALL hives ───────────────────────────────
// One passive scan window catches every paired beacon at once (HolyIot,
// RuuviTag, nRF54 HiveInside), so any number of them costs the same airtime and
// deep sleep stays effective. (HiveHeart/HiveScale/HiveTraffic GATT reads,
// handled by their own modules below, remain capped by MAX_GATT_READS_PER_CYCLE.)
#if ENABLE_BLE_SCAN
std::vector<String> bleMacs;
std::vector<int> bleHiveOfMac; // gHives[] index each MAC belongs to
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
const hivecfg::Hive& hive = hivecfg::gHives[h];
for (uint8_t b = 0; b < hive.bleCount; b++) {
const hivecfg::BlePairing& p = hive.ble[b];
// In-hive beacon sensors go through this bridge; HiveHeart/HiveScale/
// HiveTraffic are handled by their own GATT modules below. "hiveinside_nrf54"
// is the XIAO nRF54LM20A HiveInside — like HolyIot and RuuviTag it is a
// passive beacon caught by the single shared scan. (The legacy ESP32-C6
// "hiveinside" GATT prototype was removed from the ecosystem.)
if (p.type == "holyiot" || p.type == "ruuvitag" ||
p.type == "hiveinside_nrf54") {
bleMacs.push_back(p.mac);
bleHiveOfMac.push_back(h);
}
}
}
std::vector<blesensor::Snapshot> bleSnaps;
blesensor::scanPairedSensorsMulti(bleMacs, bleSnaps);
#endif
// ── beehivemonitoring.com GATT sensors (HiveHeart / HiveScale) — all hives ──
#if ENABLE_BEEHIVE_GATT
bhgatt::CycleResult bh;
bhgatt::runCycle(bh);
#endif
// ── Wired stereo mics (device-level; left=hive 1, right=hive 2) ────────────
#if ENABLE_INMP441_MICS
bool wiredMicUsed = true;
#if ENABLE_BLE_SCAN
if (BLE_OVERRIDE_MICS) {
const blesensor::Snapshot* s1 = snapForHive(bleHiveOfMac, bleSnaps, 0);
const blesensor::Snapshot* s2 = snapForHive(bleHiveOfMac, bleSnaps, 1);
if ((s1 && s1->providesMic()) || (s2 && s2->providesMic())) {
wiredMicUsed = false;
Serial.println("[ARB] BLE supplies in-hive acoustics; skipping wired INMP441 mics");
}
}
#endif
MicMeasurement micResult;
if (wiredMicUsed) micResult = readMicSamples();
#endif
// ── BeeCounter (entrance gates) — BLE/GATT only ────────────────────────────
// HiveTraffic counters are read over BLE for ANY hive that carries a
// "beecounter" pairing in the registry (like HiveHeart/HiveScale), indexed
// by registry position. There is NO wired I2C BeeCounter path and no
// fallback: a hive without a pairing reports nothing; a paired but
// unreachable counter reports bee_counter.ok=false.
beecnt::Snapshot beeSnaps[MAX_HIVES];
#if ENABLE_WIRELESS_BEECOUNTER
beecnt::bleRunCycleRegistry(beeSnaps, MAX_HIVES);
#endif
// ── Assemble the upload document ───────────────────────────────────────────
doc["device_id"] = deviceId;
// This ID is generated once while creating the JSON, then follows the exact
// same line through SD backup, retry cache and every replay. It lets the
// backend make ambiguous HTTP retries idempotent.
doc["measurement_id"] = String((uint32_t)esp_random(), HEX) + "-" +
String(rtcBootCount) + "-" + String(millis());
if (claimCode.length() > 0 && !claimRegistered) doc["claim_code"] = claimCode;
if (timeSource != "invalid") doc["timestamp"] = measuredAt;
doc["ambient_temp_c"] = ambientTemp;
doc["ambient_humidity_percent"] = ambientHumidity;
#if AMBIENT_HAS_PRESSURE
// Barometric pressure from a pressure-capable ambient sensor (BME280). Emitted
// only when such a sensor is compiled; the ingest schema ignores it if the
// backend has no ambient_pressure_hpa column yet, so this is upload-safe.
doc["ambient_pressure_hpa"] = ambientPressure;
#endif
doc["network_transport"] = "wifi";
doc["rssi_dbm"] = WiFi.status() == WL_CONNECTED ? WiFi.RSSI() : 0;
doc["firmware_version"] = FIRMWARE_VERSION;
doc["calibration_mode"] = calibrationModeActive;
// Inspection mode. The hive readings below are still measured and still
// uploaded — this flag is what lets the backend keep them out of charts,
// insights and alert rules without throwing the data away. Hub-level fields
// above (ambient, battery, solar, RSSI) are unaffected on purpose: they are
// how you tell "the beekeeper had the hive open" from "the hub died".
doc["inspection"] = inspection::active();
if (inspection::active() && inspection::startedAt() != 0) {
doc["inspection_started_at"] = inspection::startedAt();
}
doc["boot_count"] = rtcBootCount;
doc["time_source"] = timeSource;
doc["hive_count"] = hivecfg::gHiveCount;
// sd_ok is deliberately NOT stamped here: sdOk is still false at assembly time
// on every deep-sleep wake (prepareSdForSleep() clears it and the card is only
// re-mounted after this function returns). runUploadCycle() stamps it right
// after initSdCard(), when the flag reflects the real card state.
doc["rtc_ok"] = rtcOk;
// sht_ok reports whether THIS cycle produced a valid ambient-sensor measurement
// (SHT4x/SHT3x/BME280) — it is false whenever the ambient values are null
// because the read failed (e.g. a wedged C6 I2C driver), never the boot-time
// detection result. sht_detected preserves that detection/initialization
// diagnostic separately (the field names stay sht_* for backend compatibility;
// the backend ignores unknown fields, so this is upload-safe).
doc["sht_ok"] = shtRead;
doc["sht_detected"] = shtOk;
#if ENABLE_INA219_SOLAR
doc["solar_monitor_ok"] = solarMonitorOk;
doc["solar_bus_voltage_v"] = solarBusVoltage;
doc["solar_shunt_voltage_mv"] = solarShuntVoltageMv;
doc["solar_load_voltage_v"] = solarLoadVoltage;
doc["solar_current_ma"] = solarCurrentMa;
doc["solar_power_mw"] = solarPowerMw;
#endif
#if ENABLE_MAX17048_BATTERY
doc["battery_monitor_ok"] = batteryMonitorOk;
doc["battery_voltage_v"] = batteryVoltage;
doc["battery_soc_percent"] = batterySoc;
doc["battery_alert"] = batteryAlert;
#endif
#if ENABLE_INMP441_MICS
if (wiredMicUsed) {
doc["mic_ok"] = micResult.ok;
doc["mic_sample_rate_hz"] = (uint32_t)INMP441_SAMPLE_RATE;
doc["mic_sample_frames"] = (uint32_t)INMP441_SAMPLE_FRAMES;
doc["mic_left_ok"] = micResult.left.ok;
doc["mic_left_rms_dbfs"] = micResult.left.rmsDbfs;
doc["mic_left_peak_dbfs"] = micResult.left.peakDbfs;
doc["mic_left_rms_normalized"] = micResult.left.rmsNormalized;
doc["mic_right_ok"] = micResult.right.ok;
doc["mic_right_rms_dbfs"] = micResult.right.rmsDbfs;
doc["mic_right_peak_dbfs"] = micResult.right.peakDbfs;
doc["mic_right_rms_normalized"] = micResult.right.rmsNormalized;
doc["mic_left_band_sub_bass_dbfs"] = micResult.left.bands.sub_bass_dbfs;
doc["mic_left_band_hum_dbfs"] = micResult.left.bands.hum_dbfs;
doc["mic_left_band_piping_dbfs"] = micResult.left.bands.piping_dbfs;
doc["mic_left_band_stress_dbfs"] = micResult.left.bands.stress_dbfs;
doc["mic_left_band_high_dbfs"] = micResult.left.bands.high_dbfs;
doc["mic_right_band_sub_bass_dbfs"] = micResult.right.bands.sub_bass_dbfs;
doc["mic_right_band_hum_dbfs"] = micResult.right.bands.hum_dbfs;
doc["mic_right_band_piping_dbfs"] = micResult.right.bands.piping_dbfs;
doc["mic_right_band_stress_dbfs"] = micResult.right.bands.stress_dbfs;
doc["mic_right_band_high_dbfs"] = micResult.right.bands.high_dbfs;
}
#endif
#if ENABLE_BEEHIVE_GATT
bhgatt::writeToJson(doc, bh);
#endif
// ── Per-hive array — the heart of the multi-hive upload ────────────────────
JsonArray hivesArr = doc["hives"].to<JsonArray>();
for (uint8_t h = 0; h < hivecfg::gHiveCount; h++) {
const hivecfg::Hive& hive = hivecfg::gHives[h];
JsonObject ho = hivesArr.add<JsonObject>();
ho["index"] = hive.index;
if (hive.name.length()) ho["name"] = hive.name;
#if ENABLE_BLE_SCAN
const blesensor::Snapshot* sn = snapForHive(bleHiveOfMac, bleSnaps, h);
#endif
#if ENABLE_BEEHIVE_GATT
const bhgatt::HeartReading* bhHeart = (h < MAX_HIVES && bh.heart[h].present) ? &bh.heart[h] : nullptr;
const bhgatt::ScaleReading* bhScale = (h < MAX_HIVES && bh.scale[h].present) ? &bh.scale[h] : nullptr;
#endif
// Scales: consume the per-hive aggregate computed in phase 1 (pre-radio).
// Every read went through the checked scalebus layer, which returns a
// structured result — a weight is produced ONLY from a verified route +
// verified ADC channel + complete, stable sample set. Anything else marks
// the hive scale_ok=false with weight_kg omitted (null), never a nonsense
// value.
const WiredScaleAgg& agg = gWired.scale[h];
if (agg.anyScale) {
ho["weight_kg"] = agg.weightSum;
ho["raw_weight"] = agg.firstRaw;
ho["scale_source"] = agg.scaleSrc;
ho["scale_ok"] = true;
}
#if ENABLE_BEEHIVE_GATT
else if (bhScale) {
ho["weight_kg"] = bhScale->weight_kg;
ho["raw_weight"] = bhScale->raw_weight;
ho["scale_source"] = "hivescale_gatt";
}
#endif
else if (agg.triedWiredScale) {
// A wired scale is configured but produced no usable reading. Expose the raw
// (the railed full-scale value or 0) for diagnostics, but omit weight_kg so
// the DB stores null instead of a bogus weight.
ho["raw_weight"] = agg.firstRaw;
ho["scale_source"] = agg.scaleSrc;
ho["scale_ok"] = false;
}
// Temperature arbitration: BLE overrides the wired DS18B20 when configured;
// otherwise the wired probe wins and BLE/HiveHeart are the fallback.
float t = NAN;
const char* tsrc = nullptr;
#if ENABLE_BLE_SCAN
bool bleHasTemp = sn && sn->present && !isnan(sn->temp_c);
#else
bool bleHasTemp = false;
#endif
#if (ENABLE_BLE_SCAN && BLE_OVERRIDE_DS18B20)
if (bleHasTemp) { t = sn->temp_c; tsrc = "ble"; }
#endif
#if ENABLE_DS18B20_HIVE_TEMP
if (isnan(t)) {
float wired = NAN;
if (hive.hasDsRom) {
wired = ds18b20.getTempC((const uint8_t*)hive.dsRom);
} else if (hive.index >= 1 && hive.index <= 2) {
// Legacy/migrated hives without a mapped ROM fall back to probe order.
wired = ds18b20.getTempCByIndex(hive.index - 1);
}
if (!isnan(wired) && wired > DEVICE_DISCONNECTED_C) { t = wired; tsrc = "ds18b20"; }
}
#endif
#if ENABLE_BLE_SCAN
if (isnan(t) && bleHasTemp) { t = sn->temp_c; tsrc = "ble"; }
#endif
#if ENABLE_BEEHIVE_GATT
if (isnan(t) && bhHeart) {
t = bhHeart->temp_c;
tsrc = "hiveheart";
}
#endif
if (!isnan(t)) { ho["temp_c"] = t; if (tsrc) ho["temp_source"] = tsrc; }
// In-hive humidity (BLE sensor, or HiveHeart).
#if ENABLE_BLE_SCAN
if (sn && sn->present && !isnan(sn->humidity_pct)) ho["humidity_percent"] = sn->humidity_pct;
#endif
#if ENABLE_BEEHIVE_GATT
if (!ho["humidity_percent"].is<float>() && bhHeart)
ho["humidity_percent"] = bhHeart->humidity_pct;
#endif
// Nested wireless/vibration/acoustic data.
#if ENABLE_BLE_SCAN
if (sn) blesensor::writeSnapshotToHive(ho, *sn);
#endif
#if ENABLE_BEEHIVE_GATT
if (bhHeart) writeBeehiveHeartToHive(ho, *bhHeart);
if (bhScale) writeBeehiveScaleToHive(ho, *bhScale);
#endif
// BeeCounter entrance gates (BLE/GATT only): beeSnaps is indexed by
// registry position, matching this loop. A hive emits a bee_counter object
// only when it actually has a paired HiveTraffic counter — present data
// when the read succeeded, ok:false when the paired counter was
// unreachable this cycle. Hives without a pairing report nothing (there is
// no wired path and no implicit hive-1/2 counter anymore).
// The paired MAC comes from the registry rather than the snapshot: it is
// configuration, it is known whether or not the counter answered, and
// keeping it out of beecnt::Snapshot keeps that MAX_HIVES-sized stack array
// from growing for something this loop already has in hand.
const char* counterMac = nullptr;
for (uint8_t b = 0; b < hive.bleCount; b++)
if (hive.ble[b].type == "beecounter" && hive.ble[b].mac.length())
counterMac = hive.ble[b].mac.c_str();
if (h < MAX_HIVES && (beeSnaps[h].present || counterMac != nullptr))
beecnt::writeSnapshotToHive(ho, beeSnaps[h], counterMac);
}
}
// Serialize the assembled document, keep it as the "last measurement" the setup
// portal shows, and log it. Called once the caller has stamped the post-assembly
// fields (sd_ok), so the cached copy, the SD backup line and the upload all
// carry identical content.
String finalizeMeasurementJson(JsonDocument& doc) {
String output;
serializeJson(doc, output);
rememberLastMeasurement(output);
Serial.print("[MEASURE] JSON: ");
Serial.println(output);
return output;
}
1e9bacca8This file is pinned to the selected release. Download the original to open it in your design tool.