62 строки
Без EOL
1,7 КиБ
C++
62 строки
Без EOL
1,7 КиБ
C++
#include <BLEDevice.h>
|
|
#include <BLEServer.h>
|
|
#include <BLEUtils.h>
|
|
#include <BLE2902.h>
|
|
#include "config.h"
|
|
|
|
// https://www.instructables.com/ESP32-Bluetooth-Low-Energy/
|
|
|
|
void setup_BLE();
|
|
|
|
BLEServer *server;
|
|
bool deviceConnected = false;
|
|
#define SERVICE_UUID "ab0828b1-198e-4351-b779-901fa0e0371e"
|
|
#define CHARACTERISTIC_UUID_RX "4ac8a682-9736-4e5d-932b-e9b31405049c"
|
|
#define CHARACTERISTIC_UUID_TX "0972EF8C-7613-4075-AD52-756F33D4DA91"
|
|
|
|
class CharacteristicCallbacks : public BLECharacteristicCallbacks {
|
|
void onWrite(BLECharacteristic *characteristic) {
|
|
std::string rxValue = characteristic->getValue();
|
|
if (rxValue.length() <= 0) {
|
|
return;
|
|
}
|
|
|
|
if (rxValue.find("wifi") != -1 || rxValue.find("w") != -1) {
|
|
triggerWifi();
|
|
} else {
|
|
action();
|
|
}
|
|
}
|
|
};
|
|
|
|
class ServerCallbacks : public BLEServerCallbacks {
|
|
void onConnect(BLEServer *pServer) {
|
|
deviceConnected = true;
|
|
BLEDevice::startAdvertising();
|
|
};
|
|
|
|
void onDisconnect(BLEServer *pServer) {
|
|
deviceConnected = false;
|
|
BLEDevice::startAdvertising();
|
|
}
|
|
};
|
|
|
|
void setup_BLE() {
|
|
BLEDevice::init(BLE_NAME);
|
|
server = BLEDevice::createServer();
|
|
server->setCallbacks(new ServerCallbacks());
|
|
BLEService *service = server->createService(SERVICE_UUID);
|
|
|
|
BLECharacteristic *characteristicTX = service->createCharacteristic(
|
|
CHARACTERISTIC_UUID_TX,
|
|
BLECharacteristic::PROPERTY_NOTIFY);
|
|
characteristicTX->addDescriptor(new BLE2902());
|
|
|
|
BLECharacteristic *characteristic = service->createCharacteristic(
|
|
CHARACTERISTIC_UUID_RX,
|
|
BLECharacteristic::PROPERTY_WRITE);
|
|
characteristic->setCallbacks(new CharacteristicCallbacks());
|
|
|
|
service->start();
|
|
BLEDevice::startAdvertising();
|
|
} |