ESP32 BLE Philips HUE Bulb

shaunie
Posts: 5
Joined: Sat May 07, 2022 9:16 pm

ESP32 BLE Philips HUE Bulb

Postby shaunie » Sat May 07, 2022 9:35 pm

Hi to all,

I'm new here. And I have a problem.
I have a Philips Hue ble bulb and I want to control it with a ESP32.
As a IDE I use Arduino. I took the BLE CLient example and used it.

Code: Select all

//-----------------------------------------------------------------\\
//
//  BLE Phillips HUE Lampe schalten bzw. Dimmen
//  c7:f7:7e:8e:76:0a
//-----------------------------------------------------------------\\

#include "BLEDevice.h"

static BLEUUID serviceUUID("932c32bd-0000-47a2-835a-a8d455b859dd");     //Service der Lampe
static BLEUUID charONFUUID("932c32bd-0002-47a2-835a-a8d455b859dd");     //Characteristic für an und aus
static BLEUUID charDIMUUID("932c32bd-0003-47a2-835a-a8d455b859dd");     //Characteristic für Dimmen

bool conected = false;
static BLEAdvertisedDevice* myDevice;

class MyCallbacks: public BLEAdvertisedDeviceCallbacks
{
    void onResult(BLEAdvertisedDevice advertisedDevice)
    {
      const char* compareAddress = advertisedDevice.getAddress().toString().c_str();
      //BLEAddress adress = advertisedDevice.getAddress();
      if (strcmp(compareAddress, "c7:f7:7e:8e:76:0a") == 0)
      {
        Serial.print("found it");
        advertisedDevice.getScan()->stop();
        myDevice = new BLEAdvertisedDevice(advertisedDevice);
        conected = true;
      }
    }
};

bool ConnectToServer()
{
  BLEClient* pMyClient = BLEDevice::createClient();
  pMyClient->connect(myDevice);
  Serial.println("connected is here");
  conected = false;
  BLERemoteService* pRemoteService = pMyClient->getService(serviceUUID);
  BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic(charONFUUID);

  if (pRemoteCharacteristic->canRead())
  {
    Serial.println("canRead");
    std::string myValue;
    uint8_t* test = pRemoteCharacteristic->readRawData();
    if (test == nullptr)
    {
      Serial.println("Fail-NullPointer");
    }
  }



  //Serial.println(pMyClient->getService(serviceUUID).toString().c_str());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  BLEDevice::init("");
  BLEScan* pMyScan = BLEDevice::getScan();
  pMyScan->setAdvertisedDeviceCallbacks(new MyCallbacks());
  pMyScan->start(2);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (conected == true)
  {
    ConnectToServer();
    Serial.println("HI");
  }

  delay(200);
}
I can connect to the bulb but when i want to read the value from the characteristic (uint8_t* test = pRemoteCharacteristic->readRawData();) then in test there is just the nullptr. I used the nRF Connect app on a iPad to test if the service and characteristic is the right one. With this app I can switch the Bulb on and off and I can dimm it. But with my ESP32 i cant read or write the value.
I'm not the best programmer and totaly new to BLE.
Can anyone help me with this or knows what I am missing/doing wrong?

Thanks in advance
Shaunie

jenrique_aguado
Posts: 3
Joined: Thu May 12, 2022 8:44 am

Re: ESP32 BLE Philips HUE Bulb

Postby jenrique_aguado » Thu May 12, 2022 8:51 am

I was working on this topic about 18 months ago.

I was able to control the HUE BLE from a ESP32
But previously I had to activate the HUE APP on the iPad to make the bulbs detectable by ALEXA.

shaunie
Posts: 5
Joined: Sat May 07, 2022 9:16 pm

Re: ESP32 BLE Philips HUE Bulb

Postby shaunie » Fri May 13, 2022 11:46 am

jenrique_aguado do you still have the code that was working?
Or can you see what the Problem with my code is?

jenrique_aguado
Posts: 3
Joined: Thu May 12, 2022 8:44 am

Re: ESP32 BLE Philips HUE Bulb

Postby jenrique_aguado » Fri May 13, 2022 1:49 pm

Hello,

Attached is the code I used.
It was only a test to prove that I was able to control the HUE.

I would appreciate if you share if it works for you, or if you find improvements.
In case I ever have time again to do further research on this topic.
Best regards

Code: Select all

 
 
 /**
 * A BLE client example that is rich in capabilities.
 * There is a lot new capabilities implemented.
 * author unknown
 * updated by chegewara
 * 
 * https://github.com/0015/ThatProject/blob/master/Esp32_BLE_to_BLE/ESP32_ble_client/ESP32_ble_client.ino
 * 
 * mas o menos funciona en el sentido que aparentemente el ESP32 (CLIENT) se conecta con el HUE (SERVER) 
 * pero no puedo hacer nada en la version _2_HUE  voy a intentar tener dos servicios cada uno con una caracteristica
 */

#include "BLEDevice.h"
 

////////////////////////////////////////////////////////////////////////

/* las siguientes 2 lineas añadidas para recibir comandos */
String Orden_Recibida;
long valor_numerico_Recibido;
////////////////////////////////////////////////////////////////////////

// The remote service we wish to connect to.
static BLEUUID serviceUUID("0000fe0f-0000-1000-8000-00805f9b34fb");        // cambiado del original
static BLEUUID serviceUUID_2("932c32bd-0000-47a2-835a-a8d455b859dd");      // cambiado del original  SERVICIO donde esta la caraacterisctica de apagado y encendido
// The characteristic of the remote service we are interested in.


static BLEUUID    charUUID("97fe6561-0003-4f62-86e9-b71ee2da3d22");      // segunda caracteristica del servicio anterior
static BLEUUID    charUUID_2("932c32bd-0002-47a2-835a-a8d455b859dd");      // en esta caracteristica se puede apagar y encender la bombilla
static BLEUUID    charUUID_3("932c32bd-0003-47a2-835a-a8d455b859dd");      // en esta caracteristica cambio el brillo

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLERemoteCharacteristic* pRemoteCharacteristic_2;        // apagado y encendido
static BLERemoteCharacteristic* pRemoteCharacteristic_3;        // control del brillo

static BLEAdvertisedDevice* myDevice;

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    Serial.print("Notify callback for characteristic ");
    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
    Serial.print(" of data length ");
    Serial.println(length);
    Serial.print("data: ");
    Serial.println((char*)pData);
}

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());

    BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);       //  añadido al original
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");

    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service 1");


    ////busco un segundo servicio

    BLERemoteService* pRemoteService_2 = pClient->getService(serviceUUID_2);
    if (pRemoteService_2 == nullptr) {
      Serial.print("Failed to find our service UUID_2: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service 2");


    

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
    if (pRemoteCharacteristic == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic 1");

 
   
   //////////////////////////////////////////////////////////////////////////////////////////////////////////////

   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   //  encedido apagado
   ///  servicio 2    caracteristica 2
    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic_2 = pRemoteService_2->getCharacteristic(charUUID_2);
    if (pRemoteCharacteristic_2 == nullptr) {
      Serial.print("Failed to find our characteristic UUID_2: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic 2");


    // Set the characteristic's value to be the array of bytes that is actually a string.
    //pRemoteCharacteristic_2->writeValue("00",1);
    //byte OFF1 = 0x00;
    //pRemoteCharacteristic_2->writeValue(OFF1, sizeof(OFF1));


 

   //////////////////////////////////////////////////////////////////////////////////////////////////////////////

   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   //  BRILLO
   ///  servicio 2    caracteristica 3
    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristic_3 = pRemoteService_2->getCharacteristic(charUUID_3);
    if (pRemoteCharacteristic_3 == nullptr) {
      Serial.print("Failed to find our characteristic UUID_3: ");
      Serial.println(charUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic 3 (Brillo)");


    // Set the characteristic's value to be the array of bytes that is actually a string.
    // pRemoteCharacteristic_2->writeValue("00",1);
    // byte Brillo_1 = 0x7F;
    // pRemoteCharacteristic_3->writeValue(Brillo_1, sizeof(Brillo_1));


   

   //////////////////////////////////////////////////////////////////////////////////////////////////////////////







      

    connected = true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    
    String currDevAddr = advertisedDevice.getAddress().toString().c_str(); 
    Serial.print("BLE Advertised adress: ");
    Serial.println(currDevAddr);
    

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks


void setup() {
  delay(5000);
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");

  // Retrieve a Scanner and set the callback we want to use to be informed when we
  // have detected a new device.  Specify that we want active scanning and start the
  // scan to run for 5 seconds.
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
} // End of setup.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 void convertidor_String_Char(String CadenaPruebas){

    // parte A convierte un string en cadena de caracteres
    
    int CadenaPruebas_len = CadenaPruebas.length() +1;   // calcula la longitud de la cadena original
    char str[CadenaPruebas_len];
    CadenaPruebas.toCharArray(str, CadenaPruebas_len);  // aqui queda el resultado

   
     Serial.println(CadenaPruebas);
 
    char *pch;
    int i=0;
    pch = strtok (str,";");
    String buff[sizeof(str)];
    while (pch != NULL)
    {
      buff[i]=(pch);
      pch = strtok (NULL, ";");i++;
    }
 
   // una vez separado los almaceno en variables String
   
   Orden_Recibida = buff[0];
   

   String Valor_Recibido;
   Valor_Recibido = buff[1];
   valor_numerico_Recibido = Valor_Recibido.toInt(); //por ultimo genero un valor numerico del segundo trozo del string
   
   }

////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////   

// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
    
 
    
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
  }




  String command_recibido;   // comando recibido desde monitor es el comando + valor separado por ;
  String command;
  String command_value;
  int valor_command_value;

  if(Serial.available()){
        command_recibido = Serial.readStringUntil('\n');

 
          Serial.printf("Command received %s \n", command_recibido);
          convertidor_String_Char(command_recibido);
          Serial.println( Orden_Recibida);
          Serial.println(valor_numerico_Recibido);

          byte valor_byte = 10;

          
          

         command= Orden_Recibida;

                if(command.equals("1")){

                 byte ON1 = 0x01;
                 pRemoteCharacteristic_2->writeValue(ON1, sizeof(ON1));


            
                } else if(command.equals("0")){

                  byte OFF1 = 0x00;
                 pRemoteCharacteristic_2->writeValue(OFF1, sizeof(OFF1));


                  } else if(command.equals("b")){

                 byte brillo_Low_1 = 0x10;
                 pRemoteCharacteristic_3->writeValue(brillo_Low_1, sizeof(brillo_Low_1));

                  } else if(command.equals("a")){
                          byte brillo_High_1 = 0xfe;
                          pRemoteCharacteristic_3->writeValue(brillo_High_1, sizeof(brillo_High_1));

                  }
  }  // fin serial available         
  
  delay(1000); // Delay a second between loops.
} // End of loop



shaunie
Posts: 5
Joined: Sat May 07, 2022 9:16 pm

Re: ESP32 BLE Philips HUE Bulb

Postby shaunie » Fri May 13, 2022 4:17 pm

Thanks for your code, but I have the same problem as with mine.
I can connect to the lamp but it is not possible to change anything.
HUI-Lamp-not working.PNG
HUI-Lamp-not working.PNG (44.14 KiB) Viewed 3424 times

jenrique_aguado
Posts: 3
Joined: Thu May 12, 2022 8:44 am

Re: ESP32 BLE Philips HUE Bulb

Postby jenrique_aguado » Sat May 14, 2022 7:13 am

Do not forget:

" previously I had to activate the HUE APP on the iPad to make the bulbs detectable by ALEXA".


With my code I was able to control the HUE

shaunie
Posts: 5
Joined: Sat May 07, 2022 9:16 pm

Re: ESP32 BLE Philips HUE Bulb

Postby shaunie » Mon May 16, 2022 7:06 pm

jenrique_aguado I also used the iPad app.
But this doesn't change anything...I dont know what I am doing wrong :?

Who is online

Users browsing this forum: No registered users and 75 guests