fix: non-blocking BLE scan with stall recovery and BLE watchdog
- Scan with a completion callback instead of blocking start(); results are only cleared when the scanner is confirmed idle - Stall detection per block; 2 stalls re-init NimBLE, 5 reboot the ESP32 - Reboot if BLE worked before and no valid packet for 30 min - Diag counters: adv_total, mac_hits, victron_prefix, ble_stalls, ble_recoveries; log first foreign Victron address seen - Log target MAC at scanner init - Static scan callback instance (no leak on re-init)
This commit is contained in:
parent
83683de27c
commit
9ed43e36a1
18
README.md
18
README.md
|
|
@ -335,10 +335,26 @@ Notes:
|
|||
"ble_valid": 14321,
|
||||
"ble_ignored": 0,
|
||||
"ble_rssi": -72,
|
||||
"ble_age_s": 2
|
||||
"ble_age_s": 2,
|
||||
"adv_total": 53210,
|
||||
"mac_hits": 14400,
|
||||
"victron_prefix": 14400,
|
||||
"ble_stalls": 0,
|
||||
"ble_recoveries": 0
|
||||
}
|
||||
```
|
||||
|
||||
BLE counters: `adv_total` counts every advertisement the scanner delivers,
|
||||
`mac_hits` those from `VICTRON_MAC`, and `victron_prefix` any Victron device.
|
||||
If `adv_total` rises while `mac_hits` stays 0, the configured MAC is wrong; the
|
||||
serial log prints the address of the first Victron device it sees. `ble_stalls`
|
||||
counts scan blocks that failed to complete; `ble_recoveries` counts NimBLE
|
||||
re-initialisations.
|
||||
|
||||
BLE self-healing: after 2 consecutive stalls NimBLE is re-initialised; after 5 the
|
||||
ESP32 reboots. If BLE worked before and no valid packet arrives for 30 minutes,
|
||||
the ESP32 reboots (`BLE_STALE_REBOOT_MS`).
|
||||
|
||||
<details>
|
||||
<summary><b>Charge state values</b></summary>
|
||||
|
||||
|
|
|
|||
149
src/main.cpp
149
src/main.cpp
|
|
@ -32,6 +32,11 @@ static volatile uint32_t s_lastBleMs = 0;
|
|||
static volatile int s_lastBleRssi = 0;
|
||||
static volatile bool s_bleSeen = false;
|
||||
static volatile uint32_t s_lastPublishOkMs = 0;
|
||||
static volatile uint32_t s_advTotal = 0;
|
||||
static volatile uint32_t s_macHits = 0;
|
||||
static volatile uint32_t s_victronPrefix = 0;
|
||||
static volatile uint32_t s_bleStalls = 0;
|
||||
static volatile uint32_t s_bleRecoveries = 0;
|
||||
|
||||
static uint32_t s_lastDiscoveryAttemptMs = 0;
|
||||
|
||||
|
|
@ -92,6 +97,23 @@ static uint32_t s_lastDiscoveryAttemptMs = 0;
|
|||
#define BLE_SCAN_PAUSE_MS 1000
|
||||
#endif
|
||||
|
||||
// A scan block that has not completed this long after its period is a stall
|
||||
#ifndef BLE_SCAN_STALL_MARGIN_MS
|
||||
#define BLE_SCAN_STALL_MARGIN_MS 10000UL
|
||||
#endif
|
||||
// Consecutive stalls before NimBLE is de-initialised and re-initialised
|
||||
#ifndef BLE_STALLS_BEFORE_REINIT
|
||||
#define BLE_STALLS_BEFORE_REINIT 2
|
||||
#endif
|
||||
// Consecutive stalls before the whole ESP32 is restarted
|
||||
#ifndef BLE_STALLS_BEFORE_RESTART
|
||||
#define BLE_STALLS_BEFORE_RESTART 5
|
||||
#endif
|
||||
// Worked before, but no valid Victron packet for this long -> reboot
|
||||
#ifndef BLE_STALE_REBOOT_MS
|
||||
#define BLE_STALE_REBOOT_MS 1800000UL
|
||||
#endif
|
||||
|
||||
// Reconnect strategy
|
||||
#ifndef WIFI_RETRY_MS
|
||||
#define WIFI_RETRY_MS 10000UL
|
||||
|
|
@ -350,19 +372,24 @@ static bool publishData(const MpptData& d, uint32_t now) {
|
|||
static void publishDiagnostics(uint32_t now) {
|
||||
uint32_t bleAgeS = s_bleSeen ? (now - s_lastBleMs) / 1000UL : 999999UL;
|
||||
|
||||
char buf[320];
|
||||
char buf[448];
|
||||
snprintf(buf, sizeof(buf),
|
||||
"{\"uptime_s\":%lu,\"wifi_status\":%d,\"wifi_rssi\":%d,"
|
||||
"\"free_heap\":%u,\"min_free_heap\":%u,"
|
||||
"\"wifi_disconnects\":%lu,\"mqtt_connects\":%lu,"
|
||||
"\"publish_failures\":%lu,\"ble_valid\":%lu,"
|
||||
"\"ble_ignored\":%lu,\"ble_rssi\":%d,\"ble_age_s\":%lu}",
|
||||
"\"ble_ignored\":%lu,\"ble_rssi\":%d,\"ble_age_s\":%lu,"
|
||||
"\"adv_total\":%lu,\"mac_hits\":%lu,\"victron_prefix\":%lu,"
|
||||
"\"ble_stalls\":%lu,\"ble_recoveries\":%lu}",
|
||||
(unsigned long)(now / 1000UL), (int)WiFi.status(), (int)WiFi.RSSI(),
|
||||
(unsigned)ESP.getFreeHeap(), (unsigned)ESP.getMinFreeHeap(),
|
||||
(unsigned long)s_wifiDisconnects, (unsigned long)s_mqttConnects,
|
||||
(unsigned long)s_pubFailures, (unsigned long)s_bleValid,
|
||||
(unsigned long)s_bleIgnored, (int)s_lastBleRssi,
|
||||
(unsigned long)bleAgeS);
|
||||
(unsigned long)bleAgeS,
|
||||
(unsigned long)s_advTotal, (unsigned long)s_macHits,
|
||||
(unsigned long)s_victronPrefix, (unsigned long)s_bleStalls,
|
||||
(unsigned long)s_bleRecoveries);
|
||||
|
||||
bool ok = s_mqtt.publish(MQTT_TOPIC_DIAG, buf, false);
|
||||
if (ok) {
|
||||
|
|
@ -454,12 +481,28 @@ void mqttTask(void* param) {
|
|||
|
||||
class VictronAdvertisedDeviceCallbacks : public NimBLEAdvertisedDeviceCallbacks {
|
||||
void onResult(NimBLEAdvertisedDevice* device) override {
|
||||
NimBLEAddress targetAddr(VICTRON_MAC);
|
||||
if (device->getAddress() != targetAddr) return;
|
||||
if (!device->haveManufacturerData()) return;
|
||||
s_advTotal++;
|
||||
|
||||
std::string mfr = device->getManufacturerData();
|
||||
if (mfr.size() < 6 || (uint8_t)mfr[0] != 0xE1 || (uint8_t)mfr[1] != 0x02) return;
|
||||
std::string mfr = device->haveManufacturerData() ? device->getManufacturerData()
|
||||
: std::string();
|
||||
bool victronMfr = mfr.size() >= 2 && (uint8_t)mfr[0] == 0xE1 && (uint8_t)mfr[1] == 0x02;
|
||||
|
||||
NimBLEAddress targetAddr(VICTRON_MAC);
|
||||
if (device->getAddress() != targetAddr) {
|
||||
if (victronMfr) {
|
||||
s_victronPrefix++;
|
||||
static bool loggedOther = false;
|
||||
if (!loggedOther) {
|
||||
loggedOther = true;
|
||||
std::string addr = device->getAddress();
|
||||
Serial.printf("[BLE] Victron device seen at %s (configured %s)\n",
|
||||
addr.c_str(), VICTRON_MAC);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
s_macHits++;
|
||||
if (!victronMfr || mfr.size() < 6) return;
|
||||
|
||||
const uint8_t* payload = (const uint8_t*)mfr.data() + 2;
|
||||
size_t payloadLen = mfr.size() - 2;
|
||||
|
|
@ -484,16 +527,48 @@ class VictronAdvertisedDeviceCallbacks : public NimBLEAdvertisedDeviceCallbacks
|
|||
// ── BLE Scanner (runs on Core 1 via loop()) ───────────────────────────────────
|
||||
|
||||
static NimBLEScan* s_scan = nullptr;
|
||||
static VictronAdvertisedDeviceCallbacks s_adCallbacks;
|
||||
static volatile bool s_scanDone = false;
|
||||
static bool s_scanRunning = false;
|
||||
static uint32_t s_scanStartMs = 0;
|
||||
static uint32_t s_nextScanMs = 0;
|
||||
static uint32_t s_consecutiveStalls = 0;
|
||||
|
||||
static void onScanComplete(NimBLEScanResults) {
|
||||
s_scanDone = true;
|
||||
}
|
||||
|
||||
static void bleInit() {
|
||||
NimBLEDevice::init("esp32-victron");
|
||||
s_scan = NimBLEDevice::getScan();
|
||||
s_scan->setAdvertisedDeviceCallbacks(new VictronAdvertisedDeviceCallbacks(), true);
|
||||
s_scan->setAdvertisedDeviceCallbacks(&s_adCallbacks, true);
|
||||
s_scan->setActiveScan(false);
|
||||
s_scan->setInterval(BLE_SCAN_INTERVAL_MS);
|
||||
s_scan->setWindow(BLE_SCAN_WINDOW_MS);
|
||||
Serial.printf("[BLE] Scanner initialised (interval %d ms, window %d ms, %d s blocks)\n",
|
||||
BLE_SCAN_INTERVAL_MS, BLE_SCAN_WINDOW_MS, BLE_SCAN_PERIOD_S);
|
||||
Serial.printf("[BLE] Scanner initialised (interval %d ms, window %d ms, %d s blocks, target %s)\n",
|
||||
BLE_SCAN_INTERVAL_MS, BLE_SCAN_WINDOW_MS, BLE_SCAN_PERIOD_S, VICTRON_MAC);
|
||||
}
|
||||
|
||||
// Called when a block did not finish in time or failed to start.
|
||||
// Escalates: stop -> re-init NimBLE -> restart the ESP32.
|
||||
static void bleRecover() {
|
||||
s_scan->stop();
|
||||
s_bleStalls++;
|
||||
s_consecutiveStalls++;
|
||||
Serial.printf("[BLE] Stall #%lu (consecutive %lu)\n",
|
||||
(unsigned long)s_bleStalls, (unsigned long)s_consecutiveStalls);
|
||||
|
||||
if (s_consecutiveStalls >= BLE_STALLS_BEFORE_RESTART) {
|
||||
Serial.println("[BLE] Recovery failed, rebooting");
|
||||
Serial.flush();
|
||||
ESP.restart();
|
||||
}
|
||||
if (s_consecutiveStalls >= BLE_STALLS_BEFORE_REINIT) {
|
||||
Serial.println("[BLE] Re-initialising NimBLE");
|
||||
NimBLEDevice::deinit();
|
||||
bleInit();
|
||||
s_bleRecoveries++;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Setup & Loop ─────────────────────────────────────────────────────────────
|
||||
|
|
@ -527,10 +602,52 @@ void setup() {
|
|||
}
|
||||
|
||||
void loop() {
|
||||
// Long passive scan, then clear: NimBLE 1.4.x keeps one result object per
|
||||
// unique BLE address (including phones with rotating MACs) until a scan
|
||||
// completes, so clearing after each block keeps the heap flat.
|
||||
s_scan->start(BLE_SCAN_PERIOD_S, false);
|
||||
uint32_t now = millis();
|
||||
|
||||
// BLE stopped delivering while MQTT/WiFi stay healthy. Only applies once BLE
|
||||
// has worked, so a wrong MAC or an absent MPPT never causes a reboot loop.
|
||||
if (s_bleSeen && now - s_lastBleMs >= BLE_STALE_REBOOT_MS) {
|
||||
Serial.printf("[BLE] No valid packet for %lus, rebooting\n",
|
||||
(unsigned long)((now - s_lastBleMs) / 1000UL));
|
||||
Serial.flush();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
// Non-blocking scan block. NimBLE 1.4.x keeps one result object per unique
|
||||
// address until a scan completes, so results are cleared between blocks,
|
||||
// but only when the scanner is confirmed idle.
|
||||
if (!s_scanRunning) {
|
||||
if (now < s_nextScanMs || s_scan->isScanning()) {
|
||||
delay(20);
|
||||
return;
|
||||
}
|
||||
s_scan->clearResults();
|
||||
delay(BLE_SCAN_PAUSE_MS);
|
||||
s_scanDone = false;
|
||||
if (s_scan->start(BLE_SCAN_PERIOD_S, onScanComplete)) {
|
||||
s_scanRunning = true;
|
||||
s_scanStartMs = now;
|
||||
} else {
|
||||
Serial.println("[BLE] Scan failed to start");
|
||||
bleRecover();
|
||||
s_nextScanMs = millis() + BLE_SCAN_PAUSE_MS;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (s_scanDone && !s_scan->isScanning()) {
|
||||
s_scanRunning = false;
|
||||
s_consecutiveStalls = 0;
|
||||
s_nextScanMs = now + BLE_SCAN_PAUSE_MS;
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - s_scanStartMs >= BLE_SCAN_PERIOD_S * 1000UL + BLE_SCAN_STALL_MARGIN_MS) {
|
||||
Serial.println("[BLE] Scan block did not complete");
|
||||
s_scanRunning = false;
|
||||
bleRecover();
|
||||
s_nextScanMs = millis() + BLE_SCAN_PAUSE_MS;
|
||||
return;
|
||||
}
|
||||
|
||||
delay(20);
|
||||
}
|
||||
Loading…
Reference in New Issue