#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#define SERVICE_UUID "0954b12b-f7f4-48ee-9b36-ce43977dc5be"
#define CHARACTERISTIC_UUID "601a46c8-f361-4c5e-b8e5-d29aca044406"
class MyServerCallbacks : public BLEServerCallbacks
{
void onConnect(BLEServer *pServer)
{
Serial.println("现在有设备接入~");
};
void onDisconnect(BLEServer *pServer)
{
Serial.println("现在有设备断开连接~");
// 在有设备接入后Advertising广播会被停止,所以要在设备断开连接时重新开启广播
// 不然的话只有重启ESP32后才能重新搜索到
pServer->startAdvertising(); // 该行效果同 BLEDevice::startAdvertising();
}
};
class MyCallbacks : public BLECharacteristicCallbacks
{
void onWrite(BLECharacteristic *pCharacteristic)
{
uint8_t *data = pCharacteristic->getData();
//按字节解析指令
}
};
void setup()
{
// 初始化BLE并设置设备名称
BLEDevice::init(name);
// 创建BLE服务器
BLEServer *pServer = BLEDevice::createServer();
// 创建BLE服务
BLEService *pService = pServer->createService(SERVICE_UUID);
// 创建BLE特征
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
// BLECharacteristic::PROPERTY_READ |
// BLECharacteristic::PROPERTY_WRITE
BLECharacteristic::PROPERTY_WRITE_NR // 表示一个特性可以被写入,但只接受无响应的写入
);
pServer->setCallbacks(new MyServerCallbacks(this)); // 绑定回调函数
pCharacteristic->setCallbacks(new MyCallbacks(this)); // 设置回调函数
// 启动服务
pService->start();
// 启动广告
pServer->getAdvertising()->start();
}
void loop()
{
}