81 lines
2.0 KiB
C++
81 lines
2.0 KiB
C++
#include "ble.h"
|
|
|
|
bool BLEManager::deviceConnected = false;
|
|
BLEServer* BLEManager::pServer = nullptr;
|
|
BLECharacteristic* BLEManager::pTxCharacteristic = nullptr;
|
|
|
|
class BLEManagerServerCallbacks : public BLEServerCallbacks
|
|
{
|
|
void onConnect(BLEServer *pServer)
|
|
{
|
|
BLEManager::deviceConnected = true;
|
|
};
|
|
|
|
void onDisconnect(BLEServer *pServer)
|
|
{
|
|
BLEManager::deviceConnected = false;
|
|
// 重新开始广播
|
|
pServer->getAdvertising()->start();
|
|
}
|
|
};
|
|
|
|
class BLEManagerCharacteristicCallbacks : public BLECharacteristicCallbacks
|
|
{
|
|
void onWrite(BLECharacteristic *pCharacteristic)
|
|
{
|
|
std::string rxValue = pCharacteristic->getValue();
|
|
if (rxValue.length() > 0)
|
|
{
|
|
for (int i = 0; i < rxValue.length(); i++)
|
|
{
|
|
processSerialIncomingByte((uint8_t)rxValue[i], *BLEManager::pTxCharacteristic);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
void BLEManager::init(String deviceName)
|
|
{
|
|
BLEDevice::init(deviceName.c_str());
|
|
pServer = BLEDevice::createServer();
|
|
pServer->setCallbacks(new BLEManagerServerCallbacks());
|
|
|
|
BLEService *pService = pServer->createService(SERVICE_UUID);
|
|
|
|
// 创建 RX 特征值 (用于接收数据)
|
|
BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(
|
|
CHARACTERISTIC_UUID_RX,
|
|
BLECharacteristic::PROPERTY_WRITE);
|
|
pRxCharacteristic->setCallbacks(new BLEManagerCharacteristicCallbacks());
|
|
|
|
// 创建 TX 特征值 (用于发送数据)
|
|
pTxCharacteristic = pService->createCharacteristic(
|
|
CHARACTERISTIC_UUID_TX,
|
|
BLECharacteristic::PROPERTY_NOTIFY);
|
|
pTxCharacteristic->addDescriptor(new BLE2902());
|
|
|
|
pService->start();
|
|
pServer->getAdvertising()->start();
|
|
}
|
|
|
|
void BLEManager::updateDeviceName(const String &newName) {
|
|
// 保存新的设备名称
|
|
Storage::setName(newName);
|
|
|
|
// 停止广播
|
|
if (pServer) {
|
|
pServer->getAdvertising()->stop();
|
|
}
|
|
|
|
// 更新设备名称
|
|
BLEDevice::deinit(true);
|
|
BLEDevice::init(newName.c_str());
|
|
|
|
// 重新初始化 BLE 服务
|
|
init(newName);
|
|
}
|
|
|
|
void BLEManager::restart() {
|
|
ESP.restart(); // 重启 ESP32
|
|
}
|