Go Down

Topic: Esp32,is it possible to have wifi and ble that work same? (Read 297 times) previous topic - next topic

adamadiarra

Hello, i'm new in programmation of esp32 but i'm programmer of stm32.Actually, i work on the project iot. The goal of the project is to have a BLE(bluetooth low energy) server and wifi to use Firebase(backend of google). I programmed esp32 but i can't to send an information to esp32 of Firebase. When i use just the wifi without BLE, it work.The error that i read in my console is lost connection. I don't know , whta's the problem. Help me
Cordially.

Deva_Rishi

what do you use for communication between BLE and ESP, please post your sketch.
To 'Correct' you have to be Correct. (and not be condescending..)

adamadiarra

This is my code. I use the smartphone to connect with esp and web application to pilot my esp via network.

Code: [Select]
#include <WiFi.h>
#include "FirebaseESP32.h"
#include <EEPROM.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#include <PubSubClient.h>
#define EEPROM_SIZE 509


#define WIFI_SSID "AndroidAP"
#define WIFI_PASSWORD "password"
#define FIREBASE_HOST "projectFirebase.firebaseio.com" //Do not include https:// in FIREBASE_HOST
#define FIREBASE_AUTH "xxxxxxxxxx"
#define MONTER_ID 1
#define DESCENDRE_ID 2
#define SEUIL_HAUT_ID 3
#define SEUIL_BAS_ID 4
#define MONTER_ID 5
#define MONTER_INDIVIDUEL_ID 6
#define DESCENDRE_INDIVIDUELLE_ID 7
#define RXD2 16
#define TXD2 17
#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"



char mytopic[]="commande/monter";
//mutex synchronisation handlle
SemaphoreHandle_t xsynchron_mutex;

//QueueHandle

QueueHandle_t xQueue;

TaskHandle_t Task1;
TaskHandle_t Task2;

struct queumesg
{
  int commandid;
  String message;
  } xqueumesg;
String jsonSend="";

String messageToFirebase;

//Déclaration de la structure

struct queumesg pxMessage;
struct queumesg pxRxMessage;


BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t txValue = 0;



//MQTT param
/*
const char* mqttServer = "servermqtt";
const int mqttPort =23445;
const char* mqttUser = "";
const char* mqttPassword = "";
*/

WiFiClient espClient;
PubSubClient client(espClient);

 BLESecurity *pSecurity = new BLESecurity();

/*
La déclaration des trois datas, monter, descendre et la commande standard.La commande standard concerne les autres commandes comme capteur, seuil bas etc.
*/

FirebaseData firebaseData1;
FirebaseData firebaseData2;


unsigned long sendDataPrevMillis1;
unsigned long sendDataPrevMillis2;

uint16_t count1;
uint16_t count2;

String json = "";

String path = "/commande";
String path2="/ESP";
//descendre




//BLE


void setKeySize(uint8_t key_size) {
  //m_keySize = key_size;
  esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
} //setKeySize

/**
 * Setup for static PIN connection, call it first and then call setAuthenticationMode eventually to change it
 */
void setStaticPIN(uint32_t pin){
    uint32_t passkey = pin;
    esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t));
   pSecurity->setCapability(ESP_IO_CAP_OUT);
  setKeySize(16);
  pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_BOND);
   pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
}


//Sécurité class

class MySecurity : public BLESecurityCallbacks {
  
  bool onConfirmPIN(uint32_t pin){
    Serial.println("onconfirm");
    return false;
  }
  
  uint32_t onPassKeyRequest(){
        ESP_LOGI(LOG_TAG, "PassKeyRequest");
        Serial.println("passkey");
    return 123456;
  }

  void onPassKeyNotify(uint32_t pass_key){
        ESP_LOGI(LOG_TAG, "On passkey Notify number:%d", pass_key);
         Serial.println("passkey");
          Serial.println(pass_key);
  }

  bool onSecurityRequest(){
      ESP_LOGI(LOG_TAG, "On Security Request");
      Serial.println("onSecurityRequest");
    return true;
  }

  void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl){
    ESP_LOGI(LOG_TAG, "Starting BLE work!");
    Serial.println("Starting BLE work!");
    if(cmpl.success){
      uint16_t length;
      esp_ble_gap_get_whitelist_size(&length);
      ESP_LOGD(LOG_TAG, "size: %d", length);
    }
  }
};







class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
      
        Serial.print("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++)
        {
           pxMessage.message+=rxValue[i];
         // Serial.print(rxValue[i]);
          pxMessage.commandid=5;
     }
    
  
   xQueueSend( xQueue, &pxMessage, ( TickType_t ) 0 );
    xSemaphoreGive( xsynchron_mutex);

        Serial.println();
      
      }
    }
};


// LED pins
const int led1 = 2;
const int led2 = 4;

//Le buffer de réception
String RxBuffer;


void streamCallback1(StreamData data)
{
 
 
  pxMessage.commandid=2;
  String cmd=data.jsonData();
  Serial.println("type " + data.dataType());

  if( (byte(cmd[cmd.length()-2])-49) < 11 && (byte(cmd[cmd.length()-2])-49)!=0)
 {
   pxMessage.message="monter\r\n";
   xQueueSend( xQueue, &pxMessage, ( TickType_t ) 0 );
  }
  else if((byte(cmd[cmd.length()-2])-49)==0)
  {
      pxMessage.message="ok";
      xQueueSend( xQueue, &pxMessage, ( TickType_t ) 0 );
    }
 
 
  xSemaphoreGive( xsynchron_mutex);
 

}

void streamTimeoutCallback1(bool timeout)
{
  if (timeout)
  {
    Serial.println();
  
  }
}

void setup() {
  Serial.begin(115200);
  Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);

   xsynchron_mutex = xSemaphoreCreateMutex();
    //xSemaphoreGive( xsynchron_mutex );
   //Création de la queue

   xQueue = xQueueCreate( 1, sizeof( struct queumesg) );
  
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  
  EEPROM.begin(EEPROM_SIZE);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

  Serial.println("------------------------------------");
 

  if (!Firebase.beginStream(firebaseData1, path+"/monter"))
  {
    Serial.println("> FAILED");
    
  }
  else
  {
    Serial.println("> PASSED");
  
  }
  
 
 
  Firebase.setStreamCallback(firebaseData1, streamCallback1, streamTimeoutCallback1);

 

  if (!Firebase.beginStream(firebaseData2, path2 + "/standard/dat1"))
  {
    Serial.println(">> FAILED");
  
  }
  else
  {
    Serial.println(">> PASSED");
  
  }






//configuration BLE

   // Create the BLE Device
  BLEDevice::init("IVY");

BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);

BLEDevice::setSecurityCallbacks(new MySecurity());

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pTxCharacteristic = pService->createCharacteristic(
                    CHARACTERISTIC_UUID_TX,
                    BLECharacteristic::PROPERTY_NOTIFY
                  );
                      
  pTxCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
                       CHARACTERISTIC_UUID_RX,
                      BLECharacteristic::PROPERTY_WRITE
                    
                    );

  pRxCharacteristic->setCallbacks(new MyCallbacks());

  
  pService->start();
 
 setStaticPIN(123456);
  pServer->getAdvertising()->start();

}


void loop()
{
  
    if(xSemaphoreTake( xsynchron_mutex, ( TickType_t ) 0 ) == pdTRUE)
    {
      
        xQueueReceive(xQueue, &pxRxMessage, ( TickType_t ) 1);
    
        if(pxRxMessage.commandid < 6 )
        {
        
        pxMessage.commandid=45;
        pxMessage.message="";
        xQueueSend(xQueue, &pxMessage, ( TickType_t ) 1);
        }
      
      }
    digitalWrite(led1, HIGH);
    delay(1000);
    digitalWrite(led1, LOW);
    delay(1000);
    xSemaphoreGive( xsynchron_mutex);

    while( Serial.available())
    {
    
    
      messageToFirebase=Serial.readString();
      messageToFirebase=messageToFirebase.substring(0,messageToFirebase.length()-1);
      
      Serial.println(messageToFirebase);
    
    Serial.println(">> Update Data 2...");
    
  
  
   if( Firebase.pushString(firebaseData1,"commande/retour/uart",messageToFirebase))
   {
    Serial.println("Ok");
    
    }
    else
    {
       Serial.println("ko");
      }
  
    
    
        
       RxBuffer="";
    }
  

  }
  
 
  

lesept

A force d'essayer on finit par réussir... Donc, plus ça rate, plus on a de chances que ça marche (proverbe Sharduinok).

ravensburger

#4
May 19, 2019, 11:30 pm Last Edit: May 19, 2019, 11:39 pm by ravensburger

Hello, i'm new in programmation of esp32 but i'm programmer of stm32.Actually, i work on the project iot. The goal of the project is to have a BLE(bluetooth low energy) server and wifi to use Firebase(backend of google). I programmed esp32 but i can't to send an information to esp32 of Firebase. When i use just the wifi without BLE, it work.The error that i read in my console is lost connection. I don't know , whta's the problem. Help me
Cordially.

Am also trying to do the same.
Issue is that both BLE and WIFI use same 2.4Ghz RF channel, so you cannot use both at same time. If you let hardware manage it BLE has priority so will disconnect your wifi (see HERE).
Am thinking of managing this via software ... so that I allow this channel sharing, but it is difficult to manage sync with other devices... If I am successfull will tell, but in meantime if some bright guy has an idea on how to resolve this it would be appreciated.



Cheers

Go Up