Is there a way, with known connection info, to connect to a non-advertising ESP32 over BLE?
My arduino code.
- #include <BLEDevice.h>
- #include <BLEServer.h>
- #include <BLEUtils.h>
- #include <BLE2902.h>
- //UUIDs
- #define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
- #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
- #define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
- int currentCommand = 0;
- int newCommand = 0;
- /*====== BLE VARIABLES ======*/
- bool deviceConnected = false;
- const char* DEVICE_NAME = "ESP32 TEST";
- BLECharacteristic *pCharacteristic;
- /*====== Incoming Message Handler ======*/
- void ParseMessage(std::string receiveValue)
- {
- int newCommand = (int)atoi(receiveValue.c_str());
- if (newCommand != currentCommand)
- {
- currentCommand = newCommand;
- }
- Serial.println("New Command");Serial.println(newCommand);
- pCharacteristic->setValue(receiveValue);
- pCharacteristic->notify();
- delay(10);
- }
- /* ====== On Connect/Disconnect Callbacks ======*/
- class MyServerCallbacks: public BLEServerCallbacks
- {
- void onConnect(BLEServer* pServer)
- {
- deviceConnected = true;
- Serial.println("A device has connected");
- };
- void onDisconnect(BLEServer* pServer)
- {
- deviceConnected = false;
- Serial.println("A device has disconnected");
- }
- };
- /*====== NEW BLE DATA CALLBACK ======*/
- class MyCallbacks: public BLECharacteristicCallbacks
- {
- //On receive message call back
- void onWrite(BLECharacteristic *pCharacteristic)
- {
- std::string receiveValue = pCharacteristic->getValue();
- if (receiveValue.length() > 0)
- {
- ParseMessage(receiveValue);
- delay(10);
- }
- }
- };
- void setup() {
- Serial.begin(115200); Serial.println("Serial Started");
- /*====== Setup the server ======*/
- BLEDevice::init(DEVICE_NAME);
- BLEServer *pServer = BLEDevice::createServer();
- pServer->setCallbacks(new MyServerCallbacks());
- //Create a service to advertise
- BLEService *pService = pServer->createService(SERVICE_UUID);
- /*======= Create TX Characteristic ======*/
- pCharacteristic = pService -> createCharacteristic
- (
- CHARACTERISTIC_UUID_TX,
- BLECharacteristic::PROPERTY_NOTIFY
- );
- // Add descriptor
- pCharacteristic -> addDescriptor(new BLE2902());
- /*======= Create RX Characteristic ======*/
- BLECharacteristic* pCharacteristic = pService -> createCharacteristic
- (
- CHARACTERISTIC_UUID_RX,
- BLECharacteristic::PROPERTY_WRITE
- );
- pCharacteristic -> setCallbacks(new MyCallbacks());
- Serial.println("BLE Server ready");
- /*====== Start Server ======*/
- pService->start();
- Serial.println("BLE Server Started");
- //hacky advertising window
- int i = 0; Serial.println("Start Advertising");
- while(i < 100 && deviceConnected == false)
- {
- digitalWrite(ONBOARD_LED, HIGH);
- delay(50);
- digitalWrite(ONBOARD_LED, LOW);
- delay(50);
- i++;
- }
- }
- void loop() {
- }