I'm currently worken on a project where I let two ESP32 communicate with each other via BLE and it is working pretty fine. There is only one problem:
When the ESP32 running as BLE client disconnects form the ESP32 running as server (because it is too far away or whatever) the client crashes and reboots because it tries reading values from the server which it isn't connected to anymore. So I was wondering if anyone could tell me how I can request if the client is still connected to the server.
Thank you for your help!
The code:
- #include <BLEDevice.h>
- #include <Strings.h>
- std::string rxValue;
- String rxValueArduino ="";
- static BLEUUID SERVICE_UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E");
- static BLEUUID CHARACTERISTIC_UUID_RX("6E400003-B5A3-F393-E0A9-E50E24DCCA9E");
- static BLEUUID CHARACTERISTIC_UUID_TX("6E400002-B5A3-F393-E0A9-E50E24DCCA9E");
- static BLEAddress *pServerAddress;
- static boolean doConnect = false;
- static boolean deviceConnected = false;
- static BLERemoteCharacteristic* pRemoteCharacteristic;
- BLERemoteService* pRemoteService;
- bool connectToServer(BLEAddress pAddress)
- {
- Serial.print("Forming a connection to ");
- Serial.println(pAddress.toString().c_str());
- BLEClient* pClient = BLEDevice::createClient();
- pClient->connect(pAddress);
- Serial.println(" - Connected to server");
- pRemoteService = pClient->getService(SERVICE_UUID);
- if (pRemoteService == nullptr)
- {
- Serial.print("Failed to find our service UUID: ");
- Serial.println(SERVICE_UUID.toString().c_str());
- return false;
- }
- Serial.println(" - Found our service");
- }
- class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks
- {
- void onResult(BLEAdvertisedDevice advertisedDevice)
- {
- Serial.print("BLE Advertised Device found: ");
- Serial.println(advertisedDevice.toString().c_str());
- if (advertisedDevice.haveServiceUUID() && advertisedDevice.getServiceUUID().equals(SERVICE_UUID))
- {
- Serial.print("Found our device! address: ");
- advertisedDevice.getScan()->stop();
- pServerAddress = new BLEAddress(advertisedDevice.getAddress());
- doConnect = true;
- }
- }
- };
- void setup()
- {
- BLEDevice::init("ESP32");
- BLEScan* pBLEScan = BLEDevice::getScan();
- pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
- pBLEScan->setActiveScan(true);
- pBLEScan->start(10);
- }
- void loop()
- {
- if (doConnect == true)
- {
- if (connectToServer(*pServerAddress))
- {
- Serial.println("We are now connected to the BLE Server.");
- deviceConnected = true;
- }
- else
- {
- Serial.println("We have failed to connect to the server; there is nothin more we will do.");
- }
- doConnect = false;
- }
- if (deviceConnected)
- {
- pRemoteCharacteristic = pRemoteService->getCharacteristic(CHARACTERISTIC_UUID_RX);
- rxValue = pRemoteCharacteristic->readValue();
- rxValueArduino ="";
- for (int i = 0; i < rxValue.length(); i++)
- {
- rxValueArduino += rxValue[i];
- }
- }
- }