#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
uint8_t value = 0;
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
BLEDevice::init("MyESP32");
BLEServer *pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
pCharacteristic->addDescriptor(new BLE2902());
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x06);
pAdvertising->setMinPreferred(0x12);
BLEDevice::startAdvertising();
}
void loop() {
if (deviceConnected) {
pCharacteristic->setValue(&value, 1);
pCharacteristic->notify();
value++;
delay(10);
}
}
// Advertise Data
uint8_t gap_manuf_data[17] = {
// Manufacturer Specific Data
0x0d, // length of this data
0xff, // manufacturer specific data
0xb5, // Apple Company ID (example)
0x02, // type of data, 2 for beacon data
0xc5, // Beacon advertisement indicator byte
0x06, // # of bytes that follow in first AD struct
0x1a, // type of datap1
0xff, // Bedacon UUID - must match iOS app
0x4c,
0x00,
0x02,
0x15, // type of data
0xe2, // Estimote company ID
0xc5, // Beacon advertisement indicator byte
0x6d,
0x02,
0xbe,
0x7f,
0x30,
0x00
};
// Scan Response Data
uint8_t scan_rsp_data[] = {
0x02, 0x11, 0x07, 0x03, 0x60, 0x95, 0xeb, 0x12
};
...
// Set Advertise Data
pAdvertising->setManufacturerData(gap_manuf_data, sizeof(gap_manuf_data));
// Set Scan Response Data
pAdvertising->setScanResponseData(scan_rsp_data, sizeof(scan_rsp_data));
...
// Start advertising
pAdvertising->start();
Với các thông tin cụ thể hơn về Advertise Data và Scan Response Data, cũng như các cách cấu hình khác của đối tượng BLEAdvertising, ta có thể tham khảo thêm tài liệu của thư viện ESP32 BLE hoặc các ví dụ khác của các nhà phát triển và sản phẩm liên quan đến BLE.