* new helper for ESP32: SerialBLEInterface

* Some refactoring in BaseChatMesh and Terminal Chat
* new companion_radio example
This commit is contained in:
Scott Powell 2025-01-28 20:30:15 +11:00
parent 52f9c358b7
commit d9dc76f197
8 changed files with 1000 additions and 9 deletions

View file

@ -51,6 +51,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
from->name[sizeof(from->name)-1] = 0;
from->type = parser.getType();
from->last_advert_timestamp = timestamp;
from->lastmod = getRTCClock()->getCurrentTime();
onDiscoveredContact(*from, is_new); // let UI know
}
@ -93,8 +94,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
data[len] = 0; // need to make a C string again, with null terminator
//if ( ! alreadyReceived timestamp ) {
if ((flags >> 2) == 0) { // plain text msg?
onMessageRecv(from, packet->isRouteFlood(), timestamp, (const char *) &data[5]); // let UI know
if ((flags >> 2) == TXT_TYPE_PLAIN) {
onMessageRecv(from, packet->isRouteFlood() ? packet->path_len : 0xFF, timestamp, (const char *) &data[5]); // let UI know
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, 5 + strlen((char *)&data[5]), from.id.pub_key, PUB_KEY_SIZE);
@ -132,6 +133,7 @@ bool BaseChatMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const ui
// NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
// FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
from.lastmod = getRTCClock()->getCurrentTime();
onContactPathUpdated(from);
@ -213,9 +215,7 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint8_t attempt, co
}
void BaseChatMesh::resetPathTo(ContactInfo& recipient) {
if (recipient.out_path_len >= 0) {
recipient.out_path_len = -1;
}
recipient.out_path_len = -1;
}
static ContactInfo* table; // pass via global :-(
@ -254,6 +254,14 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) {
return NULL; // not found
}
ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int prefix_len) {
for (int i = 0; i < num_contacts; i++) {
auto c = &contacts[i];
if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c;
}
return NULL; // not found
}
bool BaseChatMesh::addContact(const ContactInfo& contact) {
if (num_contacts < MAX_CONTACTS) {
auto dest = &contacts[num_contacts++];
@ -290,6 +298,10 @@ mesh::GroupChannel* BaseChatMesh::addChannel(const char* psk_base64) {
}
#endif
ContactsIterator BaseChatMesh::startContactsIterator() {
return ContactsIterator();
}
bool ContactsIterator::hasNext(const BaseChatMesh* mesh, ContactInfo& dest) {
if (next_idx >= mesh->num_contacts) return false;

View file

@ -3,6 +3,7 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <helpers/AdvertDataHelpers.h>
#include <helpers/TxtDataHelpers.h>
#define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - 4 - CIPHER_MAC_SIZE - 1)
@ -13,8 +14,9 @@ struct ContactInfo {
uint8_t flags;
int8_t out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
uint32_t last_advert_timestamp;
uint32_t last_advert_timestamp; // by THEIR clock
uint8_t shared_secret[PUB_KEY_SIZE];
uint32_t lastmod; // by OUR clock
};
#define MAX_SEARCH_RESULTS 8
@ -74,7 +76,7 @@ protected:
virtual void onDiscoveredContact(ContactInfo& contact, bool is_new) = 0;
virtual bool processAck(const uint8_t *data) = 0;
virtual void onContactPathUpdated(const ContactInfo& contact) = 0;
virtual void onMessageRecv(const ContactInfo& contact, bool was_flood, uint32_t sender_timestamp, const char *text) = 0;
virtual void onMessageRecv(const ContactInfo& contact, uint8_t path_len, uint32_t sender_timestamp, const char *text) = 0;
virtual uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const = 0;
virtual uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const = 0;
virtual void onSendTimeout() = 0;
@ -98,7 +100,10 @@ public:
void resetPathTo(ContactInfo& recipient);
void scanRecentContacts(int last_n, ContactVisitor* visitor);
ContactInfo* searchContactsByPrefix(const char* name_prefix);
ContactInfo* lookupContactByPubKey(const uint8_t* pub_key, int prefix_len);
bool addContact(const ContactInfo& contact);
int getNumContacts() const { return num_contacts; }
ContactsIterator startContactsIterator();
mesh::GroupChannel* addChannel(const char* psk_base64);
void loop();

View file

@ -0,0 +1,21 @@
#pragma once
#include <Arduino.h>
#define MAX_FRAME_SIZE 160
class BaseSerialInterface {
protected:
BaseSerialInterface() { }
public:
virtual void enable() = 0;
virtual void disable() = 0;
virtual bool isEnabled() const = 0;
virtual bool isConnected() const = 0;
virtual bool isWriteBusy() const = 0;
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
virtual size_t checkRecvFrame(uint8_t dest[]) = 0;
};

View file

@ -0,0 +1,239 @@
#include "SerialBLEInterface.h"
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
void SerialBLEInterface::begin(const char* device_name, uint32_t pin_code) {
_pin_code = pin_code;
// Create the BLE Device
BLEDevice::init(device_name);
BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
BLEDevice::setSecurityCallbacks(this);
BLEDevice::setMTU(MAX_FRAME_SIZE);
BLESecurity sec;
sec.setStaticPIN(pin_code);
sec.setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND);
//BLEDevice::setPower(ESP_PWR_LVL_N8);
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(this);
// Create the BLE Service
pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
pTxCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED);
pTxCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
pRxCharacteristic->setAccessPermissions(ESP_GATT_PERM_WRITE_ENCRYPTED);
pRxCharacteristic->setCallbacks(this);
pServer->getAdvertising()->addServiceUUID(SERVICE_UUID);
}
// -------- BLESecurityCallbacks methods
uint32_t SerialBLEInterface::onPassKeyRequest() {
BLE_DEBUG_PRINTLN("onPassKeyRequest()");
return _pin_code;
}
void SerialBLEInterface::onPassKeyNotify(uint32_t pass_key) {
BLE_DEBUG_PRINTLN("onPassKeyNotify(%u)", pass_key);
}
bool SerialBLEInterface::onConfirmPIN(uint32_t pass_key) {
BLE_DEBUG_PRINTLN("onConfirmPIN(%u)", pass_key);
return true;
}
bool SerialBLEInterface::onSecurityRequest() {
BLE_DEBUG_PRINTLN("onSecurityRequest()");
return true; // allow
}
void SerialBLEInterface::onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) {
if (cmpl.success) {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Success");
//deviceConnected = true;
} else {
BLE_DEBUG_PRINTLN(" - SecurityCallback - Authentication Failure*");
//pServer->removePeerDevice(pServer->getConnId(), true);
pServer->disconnect(pServer->getConnId());
checkAdvRestart = true;
}
}
// -------- BLEServerCallbacks methods
void SerialBLEInterface::onConnect(BLEServer* pServer) {
}
void SerialBLEInterface::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param) {
BLE_DEBUG_PRINTLN("onConnect(), conn_id=%d, mtu=%d", param->connect.conn_id, pServer->getPeerMTU(param->connect.conn_id));
}
void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) {
BLE_DEBUG_PRINTLN("onMtuChanged(), mtu=%d", pServer->getPeerMTU(param->mtu.conn_id));
deviceConnected = true;
}
void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
BLE_DEBUG_PRINTLN("onDisconnect()");
if (_isEnabled) {
checkAdvRestart = true;
// loop() will detect this on next loop, and set deviceConnected to false
}
}
// -------- BLECharacteristicCallbacks methods
void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param) {
uint8_t* rxValue = pCharacteristic->getData();
int len = pCharacteristic->getLength();
if (len > MAX_FRAME_SIZE) {
BLE_DEBUG_PRINTLN("ERROR: onWrite(), frame too big, len=%d", len);
} else if (recv_queue_len >= FRAME_QUEUE_SIZE) {
BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!");
} else {
recv_queue[recv_queue_len].len = len;
memcpy(recv_queue[recv_queue_len].buf, rxValue, len);
recv_queue_len++;
}
}
// ---------- public methods
void SerialBLEInterface::enable() {
if (_isEnabled) return;
_isEnabled = true;
clearBuffers();
// Start the service
pService->start();
// Start advertising
//pServer->getAdvertising()->setMinInterval(500);
//pServer->getAdvertising()->setMaxInterval(1000);
pServer->getAdvertising()->start();
checkAdvRestart = false;
}
void SerialBLEInterface::disable() {
_isEnabled = false;
BLE_DEBUG_PRINTLN("SerialBLEInterface::disable");
pServer->getAdvertising()->stop();
pService->stop();
oldDeviceConnected = deviceConnected = false;
checkAdvRestart = false;
}
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
if (len > MAX_FRAME_SIZE) {
BLE_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d", len);
return 0;
}
if (deviceConnected && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len; // add to send queue
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;
}
#define BLE_WRITE_MIN_INTERVAL 20
bool SerialBLEInterface::isWriteBusy() const {
return millis() < _last_write + BLE_WRITE_MIN_INTERVAL; // still too soon to start another write?
}
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
if (send_queue_len > 0 // first, check send queue
&& millis() >= _last_write + BLE_WRITE_MIN_INTERVAL // space the writes apart
) {
_last_write = millis();
pTxCharacteristic->setValue(send_queue[0].buf, send_queue[0].len);
pTxCharacteristic->notify();
BLE_DEBUG_PRINTLN("writeBytes: sz=%d", (uint32_t)send_queue[0].len);
send_queue_len--;
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
send_queue[i] = send_queue[i + 1];
}
}
if (recv_queue_len > 0) { // check recv queue
size_t len = recv_queue[0].len; // take from top of queue
memcpy(dest, recv_queue[0].buf, len);
recv_queue_len--;
for (int i = 0; i < recv_queue_len; i++) { // delete top item from queue
recv_queue[i] = recv_queue[i + 1];
}
return len;
}
if (pServer->getConnectedCount() == 0) deviceConnected = false;
if (deviceConnected != oldDeviceConnected) {
if (!deviceConnected) { // disconnecting
clearBuffers();
BLE_DEBUG_PRINTLN("SerialBLEInterface -> disconnecting...");
delay(500); // give the bluetooth stack the chance to get things ready
//pServer->getAdvertising()->setMinInterval(500);
//pServer->getAdvertising()->setMaxInterval(1000);
checkAdvRestart = true;
} else {
BLE_DEBUG_PRINTLN("SerialBLEInterface -> stopping advertising");
BLE_DEBUG_PRINTLN("SerialBLEInterface -> connecting...");
// connecting
// do stuff here on connecting
pServer->getAdvertising()->stop();
checkAdvRestart = false;
}
oldDeviceConnected = deviceConnected;
}
if (checkAdvRestart) {
if (pServer->getConnectedCount() == 0) {
BLE_DEBUG_PRINTLN("SerialBLEInterface -> re-starting advertising");
pServer->getAdvertising()->start(); // re-Start advertising
}
checkAdvRestart = false;
}
return 0;
}
bool SerialBLEInterface::isConnected() const {
return deviceConnected; //pServer != NULL && pServer->getConnectedCount() > 0;
}

View file

@ -0,0 +1,83 @@
#pragma once
#include "../BaseSerialInterface.h"
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLEServerCallbacks, BLECharacteristicCallbacks {
BLEServer *pServer;
BLEService *pService;
BLECharacteristic * pTxCharacteristic;
bool deviceConnected;
bool oldDeviceConnected;
bool checkAdvRestart;
bool _isEnabled;
uint32_t _pin_code;
unsigned long _last_write;
struct Frame {
uint8_t len;
uint8_t buf[MAX_FRAME_SIZE];
};
#define FRAME_QUEUE_SIZE 4
int recv_queue_len;
Frame recv_queue[FRAME_QUEUE_SIZE];
int send_queue_len;
Frame send_queue[FRAME_QUEUE_SIZE];
void clearBuffers() { recv_queue_len = 0; send_queue_len = 0; }
protected:
// BLESecurityCallbacks methods
uint32_t onPassKeyRequest() override;
void onPassKeyNotify(uint32_t pass_key) override;
bool onConfirmPIN(uint32_t pass_key) override;
bool onSecurityRequest() override;
void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl) override;
// BLEServerCallbacks methods
void onConnect(BLEServer* pServer) override;
void onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param) override;
void onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) override;
void onDisconnect(BLEServer* pServer) override;
// BLECharacteristicCallbacks methods
void onWrite(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param) override;
public:
SerialBLEInterface() {
pServer = NULL;
pService = NULL;
deviceConnected = false;
oldDeviceConnected = false;
checkAdvRestart = false;
_isEnabled = false;
_last_write = 0;
send_queue_len = recv_queue_len = 0;
}
void begin(const char* device_name, uint32_t pin_code);
// BaseSerialInterface methods
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