77 lines
2.2 KiB
C++
77 lines
2.2 KiB
C++
#include <BLEDevice.h>
|
|
#include <BLEUtils.h>
|
|
#include <BLEScan.h>
|
|
#include <BLEAdvertisedDevice.h>
|
|
#include <BLEClient.h>
|
|
#include <BLEUUID.h>
|
|
|
|
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
|
|
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
|
|
|
|
BLEClient* pClient;
|
|
BLERemoteCharacteristic* pRemoteCharacteristic;
|
|
bool doConnect = false;
|
|
bool connected = false;
|
|
BLEAdvertisedDevice* myDevice;
|
|
|
|
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
|
|
void onResult(BLEAdvertisedDevice advertisedDevice) {
|
|
if (advertisedDevice.haveServiceUUID() && advertisedDevice.getServiceUUID().equals(BLEUUID(SERVICE_UUID))) {
|
|
Serial.println("Found target device! Connecting...");
|
|
myDevice = new BLEAdvertisedDevice(advertisedDevice);
|
|
doConnect = true;
|
|
}
|
|
}
|
|
};
|
|
|
|
void connectToServer() {
|
|
pClient = BLEDevice::createClient();
|
|
Serial.println(" - Created client");
|
|
|
|
pClient->connect(myDevice);
|
|
Serial.println(" - Connected to server");
|
|
|
|
BLERemoteService* pRemoteService = pClient->getService(SERVICE_UUID);
|
|
if (pRemoteService == nullptr) {
|
|
Serial.println("Failed to find service UUID");
|
|
pClient->disconnect();
|
|
return;
|
|
}
|
|
Serial.println(" - Found service");
|
|
|
|
pRemoteCharacteristic = pRemoteService->getCharacteristic(CHARACTERISTIC_UUID);
|
|
if (pRemoteCharacteristic == nullptr) {
|
|
Serial.println("Failed to find characteristic UUID");
|
|
pClient->disconnect();
|
|
return;
|
|
}
|
|
Serial.println(" - Found characteristic");
|
|
|
|
if (pRemoteCharacteristic->canNotify()) {
|
|
pRemoteCharacteristic->registerForNotify([](BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {
|
|
Serial.print("Received: ");
|
|
Serial.println((char*)pData);
|
|
});
|
|
}
|
|
connected = true;
|
|
}
|
|
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
Serial.println("Starting BLE Client...");
|
|
|
|
BLEDevice::init("");
|
|
BLEScan* pBLEScan = BLEDevice::getScan();
|
|
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
|
|
pBLEScan->setActiveScan(true);
|
|
pBLEScan->start(5, false);
|
|
}
|
|
|
|
void loop() {
|
|
if (doConnect && !connected) {
|
|
connectToServer();
|
|
doConnect = false;
|
|
}
|
|
//delay(1000);
|
|
}
|