# MystBin ! - file.txt #include #include #include #include #include BLEClient* pClient; bool connected = false; BLEUUID customServiceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); BLEUUID customCharUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8"); OWIRE myLED; static void ledNotifyCallback(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) { int value = *pData; if (value == 0) { myLED.setModeAndColor(OW_SOLID, OW_RED); } else { myLED.setModeAndColor(OW_SOLID, OW_GREEN); } } class MyClientCallback : public BLEClientCallbacks { void onConnect(BLEClient* pclient) { connected = true; myLED.setModeAndColor(OW_SOLID, OW_YELLOW); } void onDisconnect(BLEClient* pclient) { ESP.restart(); } }; void setup() { Serial.begin(115200); myLED.begin(4, false); myLED.setModeAndColor(OW_SOLID, OW_BLUE); BLEDevice::init("LED Client"); pClient = BLEDevice::createClient(); pClient->setClientCallbacks(new MyClientCallback()); while (!connected) { BLEScan* pBLEScan = BLEDevice::getScan(); pBLEScan->setActiveScan(true); pBLEScan->setInterval(100); pBLEScan->setWindow(99); BLEScanResults scanResults = pBLEScan->start(5); for (int i = 0; i < scanResults.getCount(); i++) { BLEAdvertisedDevice device = scanResults.getDevice(i); BLEUUID service_uuid = device.getServiceUUID(); String device_name = device.getName().c_str(); Serial.print("Device Found! Name: '"); Serial.print(device_name); Serial.print("' Advertising Service: '"); Serial.print(service_uuid.equals(customServiceUUID)); Serial.print("' Service UUID: '"); Serial.print(service_uuid.toString().c_str()); Serial.println("'"); Serial.println(); if (device.haveServiceUUID() && device.isAdvertisingService(customServiceUUID)) { Serial.println("Attempting connection to device with valid service..."); pClient->connect(&device); break; } } if (!connected) { Serial.println("Connection failed. Waiting 15 seconds before retrying."); myLED.setModeAndColor(OW_SOLID, OW_CYAN); delay(15000); // Wait for 15 seconds before retrying myLED.setModeAndColor(OW_SOLID, OW_BLUE); } } if (connected) { Serial.println("Successfully connected to service! attempting to fetch service..."); BLERemoteService* pRemoteService = pClient->getService(customServiceUUID); if (pRemoteService) { Serial.println("Found service! attempting to find characteristic..."); BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic(customCharUUID); if (pRemoteCharacteristic) { Serial.println("Found Characteristic! attempting to setup callback..."); pRemoteCharacteristic->registerForNotify(ledNotifyCallback); pRemoteCharacteristic->getDescriptor(BLEUUID((uint16_t)0x2902))->writeValue((uint8_t*)"\x01", 1); Serial.println("Set callback and found descriptor successfully! All Complete."); } else { Serial.println("Custom characteristic not found."); } } else { Serial.println("Custom service not found."); } } } void loop() { // Nothing to do in the loop for this example }