Merge branch 'observer-firmware-dev' into fix/mqtt-review-2026-09-09
This commit is contained in:
commit
800a27fe83
66 files changed
+1874
-179
No files matched your search
@@ -75,8 +75,10 @@ public:
|
||||
virtual bool otaFromManifest(const char* current_ver, bool dry_run, char reply[]) { return false; }
|
||||
|
||||
// Power management interface (boards with power management override these)
|
||||
virtual bool isPwrMgtInitialised() const { return false; }
|
||||
virtual bool isExternalPowered() { return false; }
|
||||
virtual uint16_t getBootVoltage() { return 0; }
|
||||
virtual bool getWakeLpcompSupported() const { return false; }
|
||||
virtual uint32_t getResetReason() const { return 0; }
|
||||
virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; }
|
||||
virtual uint8_t getShutdownReason() const { return 0; }
|
||||
|
||||
@@ -67,8 +67,14 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
|
||||
return true;
|
||||
}
|
||||
if (memcmp(command, "set af ", 7) == 0) {
|
||||
setAirtimeFactor(atof(&command[7]));
|
||||
strcpy(reply, "OK");
|
||||
char* end;
|
||||
float af = strtof(&command[7], &end);
|
||||
if (end == &command[7] || af < 0 || af > 9) {
|
||||
strcpy(reply, "ERROR: af must be 0-9");
|
||||
} else {
|
||||
setAirtimeFactor(af);
|
||||
strcpy(reply, "OK");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ int ConfigSerializer::Context::readNext() {
|
||||
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
|
||||
case EXPECT_KEY:
|
||||
read_key:
|
||||
if (rd_len == 0 && c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; } // empty object after whitespace
|
||||
if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; }
|
||||
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
|
||||
if (rd_len < CONFIG_MAX_KEYLEN-1 &&
|
||||
|
||||
+27
-20
@@ -47,7 +47,8 @@ static void __attribute__((constructor(101))) nrf52_early_reset_capture() {
|
||||
g_nrf52_shutdown_reason = NRF_POWER->GPREGRET2;
|
||||
}
|
||||
|
||||
void NRF52Board::initPowerMgr() {
|
||||
void NRF52Board::pwrmgtInit() {
|
||||
if (pwrmgt_initialised) return;
|
||||
// Copy early-captured register values
|
||||
reset_reason = g_nrf52_reset_reason;
|
||||
shutdown_reason = g_nrf52_shutdown_reason;
|
||||
@@ -74,6 +75,7 @@ void NRF52Board::initPowerMgr() {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: Reset = %s (0x%lX)",
|
||||
getResetReasonString(reset_reason), (unsigned long)reset_reason);
|
||||
}
|
||||
pwrmgt_initialised = true;
|
||||
}
|
||||
|
||||
const char* NRF52Board::getResetReasonString(uint32_t reason) {
|
||||
@@ -98,6 +100,7 @@ const char* NRF52Board::getResetReasonString(uint32_t reason) {
|
||||
|
||||
const char* NRF52Board::getShutdownReasonString(uint8_t reason) {
|
||||
switch (reason) {
|
||||
case SHUTDOWN_REASON_NONE: return "None";
|
||||
case SHUTDOWN_REASON_LOW_VOLTAGE: return "Low Voltage";
|
||||
case SHUTDOWN_REASON_USER: return "User Request";
|
||||
case SHUTDOWN_REASON_BOOT_PROTECT: return "Boot Protection";
|
||||
@@ -106,7 +109,7 @@ const char* NRF52Board::getShutdownReasonString(uint8_t reason) {
|
||||
}
|
||||
|
||||
bool NRF52Board::checkBootVoltage(const PowerMgtConfig* config) {
|
||||
initPowerMgr();
|
||||
pwrmgtInit();
|
||||
|
||||
// Read boot voltage
|
||||
boot_voltage_mv = getBattMilliVolts();
|
||||
@@ -173,24 +176,30 @@ void NRF52Board::enterSystemOff(uint8_t reason) {
|
||||
NVIC_SystemReset();
|
||||
}
|
||||
|
||||
void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
|
||||
void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t lpcomp_refsel) {
|
||||
pwrmgtWakeArmVbus();
|
||||
if (!isPwrMgtInitialised()) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake not armed. Reason: Power Management not initialised");
|
||||
return;
|
||||
}
|
||||
if (!getWakeLpcompSupported()) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake not armed. Reason: LPCOMP unsupported on variant");
|
||||
return;
|
||||
}
|
||||
// LPCOMP is not managed by SoftDevice - direct register access required
|
||||
// Halt and disable before reconfiguration
|
||||
NRF_LPCOMP->TASKS_STOP = 1;
|
||||
NRF_LPCOMP->ENABLE = LPCOMP_ENABLE_ENABLE_Disabled;
|
||||
|
||||
// Select analog input (AIN0-7 maps to PSEL 0-7)
|
||||
NRF_LPCOMP->PSEL = ((uint32_t)ain_channel << LPCOMP_PSEL_PSEL_Pos) & LPCOMP_PSEL_PSEL_Msk;
|
||||
NRF_LPCOMP->PSEL = ((uint32_t)PWRMGT_LPCOMP_AIN << LPCOMP_PSEL_PSEL_Pos) & LPCOMP_PSEL_PSEL_Msk;
|
||||
|
||||
// Reference: REFSEL (0-6=1/8..7/8, 7=ARef, 8-15=1/16..15/16)
|
||||
NRF_LPCOMP->REFSEL = ((uint32_t)refsel << LPCOMP_REFSEL_REFSEL_Pos) & LPCOMP_REFSEL_REFSEL_Msk;
|
||||
NRF_LPCOMP->REFSEL = ((uint32_t)lpcomp_refsel << LPCOMP_REFSEL_REFSEL_Pos) & LPCOMP_REFSEL_REFSEL_Msk;
|
||||
|
||||
// Detect UP events (voltage rises above threshold for battery recovery)
|
||||
NRF_LPCOMP->ANADETECT = LPCOMP_ANADETECT_ANADETECT_Up;
|
||||
|
||||
// Enable 50mV hysteresis for noise immunity
|
||||
NRF_LPCOMP->HYST = LPCOMP_HYST_HYST_Hyst50mV;
|
||||
|
||||
// Clear stale events/interrupts before enabling wake
|
||||
NRF_LPCOMP->EVENTS_READY = 0;
|
||||
NRF_LPCOMP->EVENTS_DOWN = 0;
|
||||
@@ -204,23 +213,22 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
|
||||
NRF_LPCOMP->ENABLE = LPCOMP_ENABLE_ENABLE_Enabled;
|
||||
NRF_LPCOMP->TASKS_START = 1;
|
||||
|
||||
// Wait for comparator to settle before entering SYSTEMOFF
|
||||
// Wait for comparator to settle
|
||||
for (uint8_t i = 0; i < 20 && !NRF_LPCOMP->EVENTS_READY; i++) {
|
||||
delayMicroseconds(50);
|
||||
}
|
||||
|
||||
if (refsel == 7) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=ARef)", ain_channel);
|
||||
} else if (refsel <= 6) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=%d/8 VDD)",
|
||||
ain_channel, refsel + 1);
|
||||
if (lpcomp_refsel == 7) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=ARef)", PWRMGT_LPCOMP_AIN);
|
||||
} else if (lpcomp_refsel <= 6) {
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/8 VDD)", PWRMGT_LPCOMP_AIN, lpcomp_refsel + 1);
|
||||
} else {
|
||||
uint8_t ref_num = (uint8_t)((refsel - 8) * 2 + 1);
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake configured (AIN%d, ref=%d/16 VDD)",
|
||||
ain_channel, ref_num);
|
||||
uint8_t ref_num = (uint8_t)((lpcomp_refsel - 8) * 2 + 1);
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/16 VDD)", PWRMGT_LPCOMP_AIN, ref_num);
|
||||
}
|
||||
}
|
||||
|
||||
// Configure VBUS (USB power) wake alongside LPCOMP
|
||||
void NRF52Board::pwrmgtWakeArmVbus() {
|
||||
uint8_t sd_enabled = 0;
|
||||
sd_softdevice_is_enabled(&sd_enabled);
|
||||
if (sd_enabled) {
|
||||
@@ -229,8 +237,7 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
|
||||
NRF_POWER->EVENTS_USBDETECTED = 0;
|
||||
NRF_POWER->INTENSET = POWER_INTENSET_USBDETECTED_Msk;
|
||||
}
|
||||
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: VBUS wake configured");
|
||||
MESH_DEBUG_PRINTLN("PWRMGT: VBUS wake armed");
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -26,15 +26,15 @@ struct PowerMgtConfig {
|
||||
#endif
|
||||
|
||||
class NRF52Board : public mesh::MainBoard {
|
||||
#ifdef NRF52_POWER_MANAGEMENT
|
||||
void initPowerMgr();
|
||||
#endif
|
||||
private:
|
||||
bool pwrmgt_initialised = false;
|
||||
|
||||
protected:
|
||||
uint8_t startup_reason;
|
||||
char *ota_name;
|
||||
|
||||
#ifdef NRF52_POWER_MANAGEMENT
|
||||
void pwrmgtInit();
|
||||
uint32_t reset_reason; // RESETREAS register value
|
||||
uint8_t shutdown_reason; // GPREGRET value (why we entered last SYSTEMOFF)
|
||||
uint16_t boot_voltage_mv; // Battery voltage at boot (millivolts)
|
||||
@@ -42,6 +42,7 @@ protected:
|
||||
bool checkBootVoltage(const PowerMgtConfig* config);
|
||||
void enterSystemOff(uint8_t reason);
|
||||
void configureVoltageWake(uint8_t ain_channel, uint8_t refsel);
|
||||
void pwrmgtWakeArmVbus();
|
||||
virtual void initiateShutdown(uint8_t reason);
|
||||
#endif
|
||||
|
||||
@@ -66,6 +67,10 @@ public:
|
||||
uint8_t getShutdownReason() const override { return shutdown_reason; }
|
||||
const char* getResetReasonString(uint32_t reason) override;
|
||||
const char* getShutdownReasonString(uint8_t reason) override;
|
||||
bool isPwrMgtInitialised() const override { return pwrmgt_initialised; }
|
||||
#ifdef PWRMGT_LPCOMP_AIN
|
||||
bool getWakeLpcompSupported() const override { return true; }
|
||||
#endif
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ public:
|
||||
virtual const char* getSettingValue(int i) const { return NULL; }
|
||||
virtual bool setSettingValue(const char* name, const char* value) { return false; }
|
||||
virtual LocationProvider* getLocationProvider() { return NULL; }
|
||||
virtual bool isGPSDetected() const { return false; }
|
||||
|
||||
// Helper functions to manage setting by keys (useful in many places ...)
|
||||
const char* getSettingByKey(const char* key) {
|
||||
|
||||
@@ -44,7 +44,7 @@ mesh::Packet* PacketQueue::get(uint32_t now) {
|
||||
}
|
||||
|
||||
mesh::Packet* PacketQueue::removeByIdx(int i) {
|
||||
if (i >= _num) return NULL; // invalid index
|
||||
if (i < 0 || i >= _num) return NULL; // invalid index
|
||||
|
||||
mesh::Packet* item = _table[i];
|
||||
_num--;
|
||||
@@ -80,10 +80,14 @@ mesh::Packet* StaticPoolPacketManager::allocNew() {
|
||||
}
|
||||
|
||||
void StaticPoolPacketManager::free(mesh::Packet* packet) {
|
||||
unused.add(packet, 0, 0);
|
||||
if (packet == NULL) return;
|
||||
if (!unused.add(packet, 0, 0)) {
|
||||
MESH_DEBUG_PRINTLN("free: unused queue full, possible double-free detected");
|
||||
}
|
||||
}
|
||||
|
||||
void StaticPoolPacketManager::queueOutbound(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for) {
|
||||
if (packet == NULL) return;
|
||||
if (!send_queue.add(packet, priority, scheduled_for)) {
|
||||
MESH_DEBUG_PRINTLN("queueOutbound: send queue full, dropping packet");
|
||||
free(packet);
|
||||
@@ -115,6 +119,7 @@ mesh::Packet* StaticPoolPacketManager::removeOutboundByIdx(int i) {
|
||||
}
|
||||
|
||||
void StaticPoolPacketManager::queueInbound(mesh::Packet* packet, uint32_t scheduled_for) {
|
||||
if (packet == NULL) return;
|
||||
if (!rx_queue.add(packet, 0, scheduled_for)) {
|
||||
MESH_DEBUG_PRINTLN("queueInbound: rx queue full, dropping packet");
|
||||
free(packet);
|
||||
|
||||
@@ -14,7 +14,10 @@ public:
|
||||
bool add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for);
|
||||
int count() const { return _num; }
|
||||
int countBefore(uint32_t now) const;
|
||||
mesh::Packet* itemAt(int i) const { return _table[i]; }
|
||||
mesh::Packet* itemAt(int i) const {
|
||||
if (i < 0 || i >= _num) return NULL;
|
||||
return _table[i];
|
||||
}
|
||||
mesh::Packet* removeByIdx(int i);
|
||||
};
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ class CustomLR2021 : public LR2021 {
|
||||
|
||||
int16_t startReceive() override {
|
||||
// include the PREAMBLE_DETECTED irq bit in reported flags
|
||||
return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
|
||||
return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
|
||||
}
|
||||
|
||||
bool isReceiving() {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// only built when the env enables the core BLE stack (build_as_lib.py globs this dir)
|
||||
#ifdef PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH
|
||||
#include "SerialBLEInterface.h"
|
||||
#include <BluetoothLock.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
// Nordic UART 6E4000xx-B5A3-F393-E0A9-E50E24DCCA9E, as raw bytes: the core lib's string
|
||||
// parser uses sscanf("%llx"), which newlib-nano on the RP2040 doesn't support (yields all zeros)
|
||||
#define NUS_UUID(n) { 0x6E, 0x40, 0x00, n, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E }
|
||||
static const uint8_t SERVICE_UUID[16] = NUS_UUID(0x01);
|
||||
static const uint8_t CHARACTERISTIC_UUID_RX[16] = NUS_UUID(0x02);
|
||||
static const uint8_t CHARACTERISTIC_UUID_TX[16] = NUS_UUID(0x03);
|
||||
|
||||
// The BLE core lib's own setValue()/notify path reallocs the value buffer on every call,
|
||||
// so a second frame queued before the radio drained the first would corrupt it. We keep our
|
||||
// own frame queue and drive att_server_notify() from the can-send-now callback instead.
|
||||
|
||||
SerialBLEInterface::SerialBLEInterface()
|
||||
: BLEService(BLEUUID(SERVICE_UUID)),
|
||||
_rx(BLEUUID(CHARACTERISTIC_UUID_RX), BLEWrite, nullptr, ATT_SECURITY_AUTHENTICATED, ATT_SECURITY_AUTHENTICATED),
|
||||
_tx(BLEUUID(CHARACTERISTIC_UUID_TX), BLERead | BLENotify, nullptr, ATT_SECURITY_AUTHENTICATED, ATT_SECURITY_AUTHENTICATED)
|
||||
{
|
||||
_isEnabled = false;
|
||||
_tx_pending = false;
|
||||
send_queue_len = 0;
|
||||
recv_queue_len = 0;
|
||||
memset(&_can_send, 0, sizeof(_can_send));
|
||||
_rx.setCallbacks(this);
|
||||
addCharacteristic(&_rx);
|
||||
addCharacteristic(&_tx);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code) {
|
||||
// JustWorks here only makes the server request pairing on connect; caps are overridden below
|
||||
BLE.setSecurity(BLESecurityJustWorks);
|
||||
// adv data carries the 128-bit service UUID, leaving room for only 8 name chars;
|
||||
// the full name goes in the scan response
|
||||
BLE.begin(prefix);
|
||||
|
||||
if (strcmp(name, "@@MAC") == 0) {
|
||||
bd_addr_t a;
|
||||
gap_local_bd_addr(a);
|
||||
sprintf(name, "%02X%02X%02X%02X%02X%02X", a[0], a[1], a[2], a[3], a[4], a[5]); // modify (IN-OUT param)
|
||||
}
|
||||
char dev_name[32+16];
|
||||
snprintf(dev_name, sizeof(dev_name), "%s%s", prefix, name);
|
||||
|
||||
BLE.server()->setName(dev_name); // GAP device name characteristic
|
||||
BLE.server()->addService(this);
|
||||
BLE.server()->setCallbacks(this);
|
||||
|
||||
// static passkey pairing with MITM protection, matching the esp32/nrf52 interfaces
|
||||
sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
|
||||
sm_set_authentication_requirements(SM_AUTHREQ_MITM_PROTECTION | SM_AUTHREQ_BONDING);
|
||||
sm_use_fixed_passkey_in_display_role(pin_code);
|
||||
|
||||
size_t n = strlen(dev_name);
|
||||
if (n > sizeof(_scan_rsp) - 2) n = sizeof(_scan_rsp) - 2;
|
||||
_scan_rsp[0] = n + 1;
|
||||
_scan_rsp[1] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
|
||||
memcpy(&_scan_rsp[2], dev_name, n);
|
||||
gap_scan_response_set_data(n + 2, _scan_rsp);
|
||||
|
||||
BLE_DEBUG_PRINTLN("begin: name=%s", dev_name);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::clearBuffers() {
|
||||
send_queue_len = 0;
|
||||
recv_queue_len = 0;
|
||||
_tx_pending = false; // a stale registration just fires into an empty queue; BTstack ignores double-adds
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onConnect(BLEServer* s) {
|
||||
BLE_DEBUG_PRINTLN("connected handle=0x%04X", _tx.conHandle());
|
||||
clearBuffers();
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onDisconnect(BLEServer* s) {
|
||||
BLE_DEBUG_PRINTLN("disconnected");
|
||||
clearBuffers(); // BTstack re-enables advertising on its own
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onWrite(BLECharacteristic* c) {
|
||||
if (c != &_rx) return;
|
||||
size_t len = _rx.valueLen();
|
||||
if (len == 0 || len > MAX_FRAME_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("onWrite: bad frame len=%u", (unsigned)len);
|
||||
return;
|
||||
}
|
||||
if (recv_queue_len >= FRAME_QUEUE_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("onWrite: recv queue full, dropping frame");
|
||||
return;
|
||||
}
|
||||
recv_queue[recv_queue_len].len = len;
|
||||
memcpy(recv_queue[recv_queue_len].buf, _rx.valueData(), len);
|
||||
recv_queue_len++;
|
||||
}
|
||||
|
||||
// caller holds the BT lock (or is in the BT context)
|
||||
void SerialBLEInterface::kickSend() {
|
||||
if (_tx_pending) return;
|
||||
_tx_pending = true;
|
||||
_can_send.callback = onCanSend;
|
||||
_can_send.context = this;
|
||||
if (att_server_register_can_send_now_callback(&_can_send, _tx.conHandle()) != 0) {
|
||||
_tx_pending = false;
|
||||
}
|
||||
}
|
||||
|
||||
// BT context: one notification per can-send-now, re-arm while frames remain
|
||||
void SerialBLEInterface::sendNext() {
|
||||
_tx_pending = false;
|
||||
if (send_queue_len == 0) return;
|
||||
if (!isConnected()) {
|
||||
BLE_DEBUG_PRINTLN("sendNext: not connected, clearing send queue");
|
||||
send_queue_len = 0;
|
||||
return;
|
||||
}
|
||||
uint16_t h = _tx.conHandle();
|
||||
Frame& f = send_queue[0];
|
||||
uint16_t mtu = att_server_get_mtu(h);
|
||||
if (f.len + 3 > mtu) {
|
||||
// att would silently truncate; drop instead (client must negotiate MTU >= MAX_FRAME_SIZE+3)
|
||||
BLE_DEBUG_PRINTLN("sendNext: frame len=%u exceeds mtu=%u, dropping", f.len, mtu);
|
||||
} else {
|
||||
uint8_t err = att_server_notify(h, _tx.valueHandle(), f.buf, f.len);
|
||||
if (err == BTSTACK_ACL_BUFFERS_FULL) {
|
||||
kickSend();
|
||||
return;
|
||||
}
|
||||
if (err) {
|
||||
BLE_DEBUG_PRINTLN("sendNext: notify failed err=%u, dropping", err);
|
||||
} else {
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%u, hdr=%u", f.len, f.buf[0]);
|
||||
}
|
||||
}
|
||||
send_queue_len--;
|
||||
memmove(&send_queue[0], &send_queue[1], send_queue_len * sizeof(Frame));
|
||||
if (send_queue_len > 0) kickSend();
|
||||
}
|
||||
|
||||
void SerialBLEInterface::enable() {
|
||||
if (_isEnabled) return;
|
||||
_isEnabled = true;
|
||||
clearBuffers();
|
||||
BLE.startAdvertising(true);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::disconnect() {
|
||||
uint16_t h = _tx.conHandle();
|
||||
if (h) gap_disconnect(h);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::disable() {
|
||||
_isEnabled = false;
|
||||
BLE_DEBUG_PRINTLN("disable");
|
||||
disconnect();
|
||||
BLE.stopAdvertising();
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isConnected() const {
|
||||
// notifications can only be enabled once the link is authenticated (CCCD inherits the perms)
|
||||
return _isEnabled && _tx.conHandle() != 0 && _tx.notifyEnabled();
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::isWriteBusy() const {
|
||||
return send_queue_len >= (FRAME_QUEUE_SIZE * 2 / 3);
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
if (len == 0 || len > MAX_FRAME_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), frame too big, len=%u", (unsigned)len);
|
||||
return 0;
|
||||
}
|
||||
if (!isConnected()) return 0;
|
||||
|
||||
BluetoothLock lock;
|
||||
if (send_queue_len >= FRAME_QUEUE_SIZE) {
|
||||
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
|
||||
return 0;
|
||||
}
|
||||
send_queue[send_queue_len].len = len;
|
||||
memcpy(send_queue[send_queue_len].buf, src, len);
|
||||
send_queue_len++;
|
||||
kickSend();
|
||||
return len;
|
||||
}
|
||||
|
||||
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
BluetoothLock lock;
|
||||
if (recv_queue_len == 0) return 0;
|
||||
|
||||
size_t len = recv_queue[0].len;
|
||||
memcpy(dest, recv_queue[0].buf, len);
|
||||
recv_queue_len--;
|
||||
memmove(&recv_queue[0], &recv_queue[1], recv_queue_len * sizeof(Frame));
|
||||
BLE_DEBUG_PRINTLN("readBytes: sz=%u, hdr=%u", (unsigned)len, dest[0]);
|
||||
return len;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include "../BaseSerialInterface.h"
|
||||
#include <BLE.h>
|
||||
#include <btstack.h>
|
||||
|
||||
// Nordic UART service over the arduino-pico BLE library (BTstack on the CYW43).
|
||||
// Build with -D PIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH so the core links liblwip-bt.
|
||||
class SerialBLEInterface : public BaseSerialInterface, BLEService, BLEServerCallbacks, BLECharacteristicCallbacks {
|
||||
// subclass only to reach the protected connection/notify state
|
||||
struct Characteristic : public BLECharacteristic {
|
||||
using BLECharacteristic::BLECharacteristic;
|
||||
uint16_t valueHandle() const { return _valueHandle; }
|
||||
uint16_t conHandle() const { return con_handle; }
|
||||
bool notifyEnabled() const { return _notificationEnabled; }
|
||||
};
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
uint8_t buf[MAX_FRAME_SIZE];
|
||||
};
|
||||
|
||||
#define FRAME_QUEUE_SIZE 8
|
||||
|
||||
Characteristic _rx;
|
||||
Characteristic _tx;
|
||||
bool _isEnabled;
|
||||
bool _tx_pending; // a can-send-now callback is registered
|
||||
btstack_context_callback_registration_t _can_send;
|
||||
uint8_t _scan_rsp[31]; // complete local name; BTstack keeps the pointer
|
||||
|
||||
uint8_t send_queue_len;
|
||||
Frame send_queue[FRAME_QUEUE_SIZE];
|
||||
uint8_t recv_queue_len;
|
||||
Frame recv_queue[FRAME_QUEUE_SIZE];
|
||||
|
||||
void clearBuffers();
|
||||
void kickSend();
|
||||
void sendNext();
|
||||
static void onCanSend(void* ctx) { ((SerialBLEInterface*)ctx)->sendNext(); }
|
||||
|
||||
// BLE library callbacks (run in the BT context)
|
||||
void onWrite(BLECharacteristic* c) override;
|
||||
void onConnect(BLEServer* s) override;
|
||||
void onDisconnect(BLEServer* s) override;
|
||||
|
||||
public:
|
||||
SerialBLEInterface();
|
||||
|
||||
/**
|
||||
* init the BLE interface.
|
||||
* @param prefix a prefix for the device name
|
||||
* @param name IN/OUT - a name for the device (combined with prefix). If "@@MAC", is modified and returned
|
||||
* @param pin_code the BLE security pin
|
||||
*/
|
||||
void begin(const char* prefix, char* name, uint32_t pin_code);
|
||||
|
||||
void disconnect();
|
||||
void enable() override;
|
||||
void disable() override;
|
||||
bool isEnabled() const override { return _isEnabled; }
|
||||
bool isConnected() const override;
|
||||
bool isWriteBusy() const override;
|
||||
size_t writeFrame(const uint8_t src[], size_t len) override;
|
||||
size_t checkRecvFrame(uint8_t dest[]) override;
|
||||
};
|
||||
|
||||
#if BLE_DEBUG_LOGGING && ARDUINO
|
||||
#include <Arduino.h>
|
||||
#define BLE_DEBUG_PRINT(F, ...) Serial.printf("BLE: " F, ##__VA_ARGS__)
|
||||
#define BLE_DEBUG_PRINTLN(F, ...) Serial.printf("BLE: " F "\n", ##__VA_ARGS__)
|
||||
#else
|
||||
#define BLE_DEBUG_PRINT(...) {}
|
||||
#define BLE_DEBUG_PRINTLN(...) {}
|
||||
#endif
|
||||
@@ -38,6 +38,7 @@ public:
|
||||
#if ENV_INCLUDE_GPS
|
||||
EnvironmentSensorManager(LocationProvider &location): _location(&location){};
|
||||
LocationProvider* getLocationProvider() { return _location; }
|
||||
bool isGPSDetected() const override { return gps_detected; }
|
||||
#else
|
||||
EnvironmentSensorManager(){};
|
||||
#endif
|
||||
|
||||
File renamed without changes.
File renamed without changes.
Reference in new issue
Block a user