Merge meshcore-dev dev with companion and board integrations

This commit is contained in:
mikecarper committed 2026-09-15 20:51:43 -07:00
commit 476aac92de
78 files changed
+1904 -190

No files matched your search

+2
View File
@@ -228,6 +228,7 @@ public:
#endif
// Power management interface (boards with power management override these)
virtual bool isPwrMgtInitialised() const { return false; }
virtual bool isExternalPowered() { return false; }
virtual bool isUsbDataConnected() { return false; }
// True when the device is enumerated by a USB host, even if its serial port
@@ -235,6 +236,7 @@ public:
// that cannot distinguish a computer from USB power.
virtual bool isUsbHostConnected() { return isUsbDataConnected(); }
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; }
+1
View File
@@ -1,4 +1,5 @@
#include "ConfigSerializer.h"
#include <stdlib.h> // atoi/atol/atof (Arduino.h pulls this in on-device, native builds do not)
bool ConfigSerializer::saveSerial(Stream& s) {
Context context(&s, OP::WRITE);
+6 -10
View File
@@ -263,7 +263,7 @@ const char* NRF52Board::getShutdownReasonString(uint8_t reason) {
}
bool NRF52Board::checkBootVoltage(const PowerMgtConfig* config) {
initPowerMgr();
pwrmgtInit();
if (config == nullptr) return true;
@@ -381,22 +381,19 @@ 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);
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (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);
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/8 VDD)", ain_channel, 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);
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake armed (AIN%d, ref=%d/16 VDD)", ain_channel, ref_num);
}
}
void NRF52Board::armVbusWake() {
@@ -409,8 +406,7 @@ void NRF52Board::armVbusWake() {
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
+4
View File
@@ -37,6 +37,7 @@ protected:
char *ota_name;
#ifdef NRF52_POWER_MANAGEMENT
void pwrmgtInit() { initPowerMgr(); }
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)
@@ -44,6 +45,7 @@ protected:
bool checkBootVoltage(const PowerMgtConfig* config);
void enterSystemOff(uint8_t reason);
void configureVoltageWake(uint8_t ain_channel, uint8_t refsel);
void pwrmgtWakeArmVbus() { armVbusWake(); }
virtual void initiateShutdown(uint8_t reason);
#endif
@@ -85,6 +87,8 @@ public:
const char* getShutdownReasonString(uint8_t reason) override;
bool isPowerManagementInitialized() const override { return power_mgr_initialized; }
bool supportsVoltageWake() const override { return true; }
bool isPwrMgtInitialised() const override { return isPowerManagementInitialized(); }
bool getWakeLpcompSupported() const override { return supportsVoltageWake(); }
#endif
};
+1
View File
@@ -140,6 +140,7 @@ public:
(void)blocked;
return false;
}
virtual bool isGPSDetected() const { return false; }
// Helper functions to manage setting by keys (useful in many places ...)
const char* getSettingByKey(const char* key) {
+6 -1
View File
@@ -172,10 +172,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");
}
}
bool StaticPoolPacketManager::queueOutbound(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for) {
if (packet == NULL) return false;
if (!send_queue.add(packet, priority, scheduled_for)) {
MESH_DEBUG_PRINTLN("queueOutbound: send queue full, dropping packet");
return false;
@@ -216,6 +220,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);
+4 -1
View File
@@ -28,7 +28,10 @@ public:
int count() const { return _num; }
int countBefore(uint32_t now) const;
bool getNextTime(uint32_t now, uint32_t& scheduled_for) 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);
bool reschedule(mesh::Packet* packet, uint32_t scheduled_for);
};
+1 -1
View File
@@ -157,7 +157,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() {
+208
View File
@@ -0,0 +1,208 @@
// 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);
}
bool SerialBLEInterface::begin(const char* prefix, const char* name, uint32_t pin_code,
const uint8_t* custom_address, bool clear_bonds,
bool stealth_pair_once,
const mesh::companion::BluetoothPeerIdentity* bonded_only_peer) {
if (custom_address || clear_bonds || stealth_pair_once || bonded_only_peer) return false;
// 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);
char mac_name[13];
if (strcmp(name, "@@MAC") == 0) {
bd_addr_t a;
gap_local_bd_addr(a);
snprintf(mac_name, sizeof(mac_name), "%02X%02X%02X%02X%02X%02X", a[0], a[1], a[2], a[3], a[4], a[5]);
name = mac_name;
}
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);
return true;
}
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
+85
View File
@@ -0,0 +1,85 @@
#pragma once
#include "../BaseSerialInterface.h"
#include <BLE.h>
#include <btstack.h>
#include <helpers/BluetoothMac.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
*/
bool begin(const char* prefix, const char* name, uint32_t pin_code,
const uint8_t* custom_address = nullptr, bool clear_bonds = false,
bool stealth_pair_once = false,
const mesh::companion::BluetoothPeerIdentity* bonded_only_peer = nullptr);
// Pico W currently supports normal authenticated pairing, not the optional
// ESP32/nRF52 identity-rotation and bonded-only advertising policies.
bool takeSuccessfulConnection(mesh::companion::BluetoothPeerIdentity* = nullptr) { return false; }
bool takeBondedOnlyRecovery() { return false; }
bool enableBondedOnlyAdvertising(const mesh::companion::BluetoothPeerIdentity&) { return false; }
void cancelStealthPairingTransition() { }
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
@@ -47,6 +47,7 @@ public:
EnvironmentSensorManager(LocationProvider &location):
_location(&location), _configured_location(&location) {};
LocationProvider* getLocationProvider() { return _location; }
bool isGPSDetected() const override { return gps_detected; }
#else
EnvironmentSensorManager(){};
#endif