mobizt / Firebase-ESP32

[DEPRECATED]🔥 Firebase RTDB Arduino Library for ESP32. The complete, fast, secured and reliable Firebase Arduino client library that supports CRUD (create, read, update, delete) and Stream operations.
MIT License
415 stars 118 forks source link

Help me please #3

Closed cruizg closed 5 years ago

cruizg commented 5 years ago

I have a question With Wifi Connection. Do They have Support?.

mobizt commented 5 years ago

I'm not sure I can understand actually what you mean. When you call push/set/get/update/delete, Firebase-ESP32 library just only check the WiFi status and reconnect by call WiFi.reconnect();) using the last connection config if you previousely call Firebase.reconnectWiFi(true).

The library is not handle the WiFi connection setup, unless reconnection for you when you call push/set/get/update/delete or when stream connection is timeout.

cruizg commented 5 years ago

Hi, i Use this post: https://desire.giesecke.tk/index.php/2018/04/06/esp32-wifi-setup-over-ble/ merge with your library, but the message is connection refused, can you help me please:

`#include

include

include

include

//#include

include "FirebaseESP32.h"

FirebaseData firebaseData;

define FIREBASE_HOST ""

define FIREBASE_AUTH ""

include

/* Build time / const char compileDate[] = DATE " " TIME;

/ Unique device name */ char apName[] = "KNOCK-xxxxxxxxxxxx"; /* Selected network true = use primary network false = use secondary network / bool usePrimAP = true; / Flag if stored AP credentials are available */ bool hasCredentials = false; /* Connection status / volatile bool isConnected = false; /* Connection change status / bool connStatusChanged = false;

/**

// List of Service and Characteristic UUIDs

define SERVICE_UUID "0000aaaa-ead2-11e7-80c1-9a214cf093ae"

define WIFI_UUID "00005555-ead2-11e7-80c1-9a214cf093ae"

/* SSIDs of local WiFi networks / String ssidPrim; String ssidSec; /* Password for local WiFi network / String pwPrim; String pwSec;

/ Characteristic for digital output / BLECharacteristic pCharacteristicWiFi; / BLE Advertiser / BLEAdvertising pAdvertising; / BLE Service / BLEService pService; / BLE Server / BLEServer pServer;

/* Buffer for JSON string / // MAx size is 51 bytes for frame: // {"ssidPrim":"","pwPrim":"","ssidSec":"","pwSec":""} // + 4 x 32 bytes for 2 SSID's and 2 passwords StaticJsonBuffer<200> jsonBuffer;

/**

/**

/**

/* Callback for receiving IP address from AP / void gotIP(system_event_id_t event) { isConnected = true; connStatusChanged = true; }

/* Callback for connection loss / void lostCon(system_event_id_t event) { isConnected = false; connStatusChanged = true; }

/** scanWiFi Scans for available networks and decides if a switch between allowed networks makes sense

@return bool True if at least one allowed network was found */ bool scanWiFi() { / RSSI for primary network */ int8_t rssiPrim; /* RSSI for secondary network / int8_t rssiSec; / Result of this function */ bool result = false;

Serial.println("Start scanning for networks");

WiFi.disconnect(true); WiFi.enableSTA(true); WiFi.mode(WIFI_STA);

// Scan for AP int apNum = WiFi.scanNetworks(false,true,false,1000); if (apNum == 0) { Serial.println("Found no networks?????"); return false; }

byte foundAP = 0; bool foundPrim = false;

for (int index=0; index<apNum; index++) { String ssid = WiFi.SSID(index); Serial.println("Found AP: " + ssid + " RSSI: " + WiFi.RSSI(index)); if (!strcmp((const char) &ssid[0], (const char) &ssidPrim[0])) { Serial.println("Found primary AP"); foundAP++; foundPrim = true; rssiPrim = WiFi.RSSI(index); } if (!strcmp((const char) &ssid[0], (const char) &ssidSec[0])) { Serial.println("Found secondary AP"); foundAP++; rssiSec = WiFi.RSSI(index); } }

switch (foundAP) { case 0: result = false; break; case 1: if (foundPrim) { usePrimAP = true; } else { usePrimAP = false; } result = true; break; default: Serial.printf("RSSI Prim: %d Sec: %d\n", rssiPrim, rssiSec); if (rssiPrim > rssiSec) { usePrimAP = true; // RSSI of primary network is better } else { usePrimAP = false; // RSSI of secondary network is better } result = true; break; } return result; }

/**

}

void setup() { // Create unique device name createName();

// Initialize Serial port Serial.begin(115200); // Send some device info Serial.print("Build: "); Serial.println(compileDate);

Preferences preferences; preferences.begin("WiFiCred", false); bool hasPref = preferences.getBool("valid", false); if (hasPref) { ssidPrim = preferences.getString("ssidPrim",""); ssidSec = preferences.getString("ssidSec",""); pwPrim = preferences.getString("pwPrim",""); pwSec = preferences.getString("pwSec","");

if (ssidPrim.equals("") 
    || pwPrim.equals("")
    || ssidSec.equals("")
    || pwPrim.equals("")) {
  Serial.println("Found preferences but credentials are invalid");
} else {
  Serial.println("Read from preferences:");
  Serial.println("primary SSID: "+ssidPrim+" password: "+pwPrim);
  Serial.println("secondary SSID: "+ssidSec+" password: "+pwSec);
  hasCredentials = true;
}

} else { Serial.println("Could not find preferences, need send data over BLE"); } preferences.end();

// Start BLE server initBLE();

if (hasCredentials) { // Check for available AP's if (!scanWiFi) { Serial.println("Could not find any AP"); } else { // If AP was found, start connection connectWiFi(); } } } int n = 0;

void loop() {

} void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }`

cruizg commented 5 years ago

This is the message:

:31:12.683 -> Start connection to esp8266 12:31:27.371 -> Connected to wifi 12:31:27.371 -> SSID: esp8266 12:31:27.371 -> IP Address: 192.168.43.18 12:31:27.371 -> signal strength (RSSI):-45 dBm 12:31:27.418 -> ----------------------------------- 12:31:27.418 -> ----------Path Exist Test---------- 12:31:27.418 -> ----------------------------------- 12:31:27.418 -> 12:31:31.487 -> Path /ESP32_Test is not exist 12:31:31.487 -> 12:31:31.487 -> ----------------------------------- 12:31:31.487 -> ----------Begin Set Test----------- 12:31:31.487 -> ----------------------------------- 12:31:31.487 -> 12:31:33.742 -> ----------Can't set data-------- 12:31:33.742 -> REASON: connection refused 12:31:33.742 -> --------------------------------

mobizt commented 5 years ago

The return error is due to internet connection which returns from WiFiClientSecure class of ESP32 core library, everything seems to ok but can't establish the network connection.

You may need to check the log message which available in ESP32 Dev Module.

In Arduino IDE, from menu Tools, please try to change Board: -> ESP32 Dev Module and Partition Scheme: -> Huge App (3 MB No OTA) and Core Debug Level: -> Verbose.

Compile and upload

if you see the message like this in Serial monitor.

[E][WiFiGeneric.cpp:658] hostByName(): DNS Failed for xxxxxxxx.firebaseio.com
[E][WiFiClientSecure.cpp:118] connect(): start_ssl_client: -1

That's the internet connection problem. Please try other access points or routers.

Your sketch in above post was truncated by GitHub code formatter then I try the below code and it works without problem.

// Default Arduino includes
#include <Arduino.h>
#include <WiFi.h>
#include <nvs.h>
#include <nvs_flash.h>

// Includes for JSON object handling
// Requires ArduinoJson library
// https://arduinojson.org
// https://github.com/bblanchon/ArduinoJson
#include <ArduinoJson.h>

// Includes for BLE
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLEDevice.h>
#include <BLEAdvertising.h>
#include <Preferences.h>

#include "FirebaseESP32.h"

#define FIREBASE_HOST "YOUR_FIREBASE_PROJECT.firebaseio.com"
#define FIREBASE_AUTH "YOUR_FIREBASE_DATABASE_SECRET"

//Define FirebaseESP32 data object
FirebaseData firebaseData;

/* Build time */
const char compileDate[] = __DATE__ " " __TIME__;

/* Unique device name */
char apName[] = "ESP32-xxxxxxxxxxxx";
/* Selected network
    true = use primary network
    false = use secondary network
*/
bool usePrimAP = true;
/* Flag if stored AP credentials are available */
bool hasCredentials = false;
/* Connection status */
volatile bool isConnected = false;
/* Connection change status */
bool connStatusChanged = false;

/*
   Create unique device name from MAC address
 **/
void createName() {
  uint8_t baseMac[6];
  // Get MAC address for WiFi station
  esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
  // Write unique name into apName
  sprintf(apName, "ESP32-%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
}

// List of Service and Characteristic UUIDs
#define SERVICE_UUID  "0000aaaa-ead2-11e7-80c1-9a214cf093ae"
#define WIFI_UUID     "00005555-ead2-11e7-80c1-9a214cf093ae"

/* SSIDs of local WiFi networks */
String ssidPrim;
String ssidSec;
/* Password for local WiFi network */
String pwPrim;
String pwSec;

/** Characteristic for digital output */
BLECharacteristic *pCharacteristicWiFi;
/** BLE Advertiser */
BLEAdvertising* pAdvertising;
/** BLE Service */
BLEService *pService;
/** BLE Server */
BLEServer *pServer;

/** Buffer for JSON string */
// MAx size is 51 bytes for frame:
// {"ssidPrim":"","pwPrim":"","ssidSec":"","pwSec":""}
// + 4 x 32 bytes for 2 SSID's and 2 passwords
StaticJsonBuffer<200> jsonBuffer;

/**
   MyServerCallbacks
   Callbacks for client connection and disconnection
*/
class MyServerCallbacks: public BLEServerCallbacks {
    // TODO this doesn't take into account several clients being connected
    void onConnect(BLEServer* pServer) {
      Serial.println("BLE client connected");
    };

    void onDisconnect(BLEServer* pServer) {
      Serial.println("BLE client disconnected");
      pAdvertising->start();
    }
};

/**
   MyCallbackHandler
   Callbacks for BLE client read/write requests
*/
class MyCallbackHandler: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string value = pCharacteristic->getValue();
      if (value.length() == 0) {
        return;
      }
      Serial.println("Received over BLE: " + String((char *)&value[0]));

      // Decode data
      int keyIndex = 0;
      for (int index = 0; index < value.length(); index ++) {
        value[index] = (char) value[index] ^ (char) apName[keyIndex];
        keyIndex++;
        if (keyIndex >= strlen(apName)) keyIndex = 0;
      }

      /** Json object for incoming data */
      JsonObject& jsonIn = jsonBuffer.parseObject((char *)&value[0]);
      if (jsonIn.success()) {
        if (jsonIn.containsKey("ssidPrim") &&
            jsonIn.containsKey("pwPrim") &&
            jsonIn.containsKey("ssidSec") &&
            jsonIn.containsKey("pwSec")) {
          ssidPrim = jsonIn["ssidPrim"].as<String>();
          pwPrim = jsonIn["pwPrim"].as<String>();
          ssidSec = jsonIn["ssidSec"].as<String>();
          pwSec = jsonIn["pwSec"].as<String>();

          Preferences preferences;
          preferences.begin("WiFiCred", false);
          preferences.putString("ssidPrim", ssidPrim);
          preferences.putString("ssidSec", ssidSec);
          preferences.putString("pwPrim", pwPrim);
          preferences.putString("pwSec", pwSec);
          preferences.putBool("valid", true);
          preferences.end();

          Serial.println("Received over bluetooth:");
          Serial.println("primary SSID: " + ssidPrim + " password: " + pwPrim);
          Serial.println("secondary SSID: " + ssidSec + " password: " + pwSec);
          connStatusChanged = true;
          hasCredentials = true;
        } else if (jsonIn.containsKey("erase")) {
          Serial.println("Received erase command");
          Preferences preferences;
          preferences.begin("WiFiCred", false);
          preferences.clear();
          preferences.end();
          connStatusChanged = true;
          hasCredentials = false;
          ssidPrim = "";
          pwPrim = "";
          ssidSec = "";
          pwSec = "";

          int err;
          err = nvs_flash_init();
          Serial.println("nvs_flash_init: " + err);
          err = nvs_flash_erase();
          Serial.println("nvs_flash_erase: " + err);
        } else if (jsonIn.containsKey("reset")) {
          WiFi.disconnect();
          esp_restart();
        }
      } else {
        Serial.println("Received invalid JSON");
      }
      jsonBuffer.clear();
    };

    void onRead(BLECharacteristic *pCharacteristic) {
      Serial.println("BLE onRead request");
      String wifiCredentials;

      /** Json object for outgoing data */
      JsonObject& jsonOut = jsonBuffer.createObject();
      jsonOut["ssidPrim"] = ssidPrim;
      jsonOut["pwPrim"] = pwPrim;
      jsonOut["ssidSec"] = ssidSec;
      jsonOut["pwSec"] = pwSec;
      // Convert JSON object into a string
      jsonOut.printTo(wifiCredentials);

      // encode the data
      int keyIndex = 0;
      Serial.println("Stored settings: " + wifiCredentials);
      for (int index = 0; index < wifiCredentials.length(); index ++) {
        wifiCredentials[index] = (char) wifiCredentials[index] ^ (char) apName[keyIndex];
        keyIndex++;
        if (keyIndex >= strlen(apName)) keyIndex = 0;
      }
      pCharacteristicWiFi->setValue((uint8_t*)&wifiCredentials[0], wifiCredentials.length());
      jsonBuffer.clear();
    }
};

/**
   initBLE
   Initialize BLE service and characteristic
   Start BLE server and service advertising
*/
void initBLE() {
  // Initialize BLE and set output power
  BLEDevice::init(apName);
  BLEDevice::setPower(ESP_PWR_LVL_P7);

  // Create BLE Server
  pServer = BLEDevice::createServer();

  // Set server callbacks
  pServer->setCallbacks(new MyServerCallbacks());

  // Create BLE Service
  pService = pServer->createService(BLEUUID(SERVICE_UUID), 20);

  // Create BLE Characteristic for WiFi settings
  pCharacteristicWiFi = pService->createCharacteristic(
                          BLEUUID(WIFI_UUID),
                          // WIFI_UUID,
                          BLECharacteristic::PROPERTY_READ |
                          BLECharacteristic::PROPERTY_WRITE
                        );
  pCharacteristicWiFi->setCallbacks(new MyCallbackHandler());

  // Start the service
  pService->start();

  // Start advertising
  pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

/** Callback for receiving IP address from AP */
void gotIP(system_event_id_t event) {
  isConnected = true;
  connStatusChanged = true;
}

/** Callback for connection loss */
void lostCon(system_event_id_t event) {
  isConnected = false;
  connStatusChanged = true;
}

/**
   scanWiFi
   Scans for available networks
   and decides if a switch between
   allowed networks makes sense

   @return <code>bool</code>
          True if at least one allowed network was found
*/
bool scanWiFi() {
  /** RSSI for primary network */
  int8_t rssiPrim;
  /** RSSI for secondary network */
  int8_t rssiSec;
  /** Result of this function */
  bool result = false;

  Serial.println("Start scanning for networks");

  WiFi.disconnect(true);
  WiFi.enableSTA(true);
  WiFi.mode(WIFI_STA);

  // Scan for AP
  int apNum = WiFi.scanNetworks(false, true, false, 1000);
  if (apNum == 0) {
    Serial.println("Found no networks?????");
    return false;
  }

  byte foundAP = 0;
  bool foundPrim = false;

  for (int index = 0; index < apNum; index++) {
    String ssid = WiFi.SSID(index);
    Serial.println("Found AP: " + ssid + " RSSI: " + WiFi.RSSI(index));
    if (!strcmp((const char*) &ssid[0], (const char*) &ssidPrim[0])) {
      Serial.println("Found primary AP");
      foundAP++;
      foundPrim = true;
      rssiPrim = WiFi.RSSI(index);
    }
    if (!strcmp((const char*) &ssid[0], (const char*) &ssidSec[0])) {
      Serial.println("Found secondary AP");
      foundAP++;
      rssiSec = WiFi.RSSI(index);
    }
  }

  switch (foundAP) {
    case 0:
      result = false;
      break;
    case 1:
      if (foundPrim) {
        usePrimAP = true;
      } else {
        usePrimAP = false;
      }
      result = true;
      break;
    default:
      Serial.printf("RSSI Prim: %d Sec: %d\n", rssiPrim, rssiSec);
      if (rssiPrim > rssiSec) {
        usePrimAP = true; // RSSI of primary network is better
      } else {
        usePrimAP = false; // RSSI of secondary network is better
      }
      result = true;
      break;
  }
  return result;
}

/**
   Start connection to AP
*/
void connectWiFi() {
  // Setup callback function for successful connection
  WiFi.onEvent(gotIP, SYSTEM_EVENT_STA_GOT_IP);
  // Setup callback function for lost connection
  WiFi.onEvent(lostCon, SYSTEM_EVENT_STA_DISCONNECTED);

  WiFi.disconnect(true);
  WiFi.enableSTA(true);
  WiFi.mode(WIFI_STA);

  Serial.println();
  Serial.print("Start connection to ");
  if (usePrimAP) {
    Serial.println(ssidPrim);
    WiFi.begin(ssidPrim.c_str(), pwPrim.c_str());
  } else {
    Serial.println(ssidSec);
    WiFi.begin(ssidSec.c_str(), pwSec.c_str());
  }

  uint32_t startTime = millis();
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    if (millis() - startTime > 30000) { // wait maximum 30 seconds for a connection
      Serial.println("Failed to connect to WiFI");
      Serial.println("Rebooting in 30 seconds");
      delay(30000);
      esp_restart();
    }
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);
  String path = "/ESP32_Test";
  String jsonStr;

  Serial.println();
  Serial.println("-----------------------------------");
  Serial.println("----------Begin Set Test-----------");
  Serial.println("-----------------------------------");
  Serial.println();

  for (uint8_t i = 0; i < 10; i++) {
    if (Firebase.setInt(firebaseData, path + "/Int/Data" + (i + 1), (i + 1) * 10)) {
      Serial.println("----------Set result-----------");
      Serial.println("PATH: " + firebaseData.dataPath());
      Serial.println("TYPE: " + firebaseData.dataType());
      Serial.print("VALUE: ");
      if (firebaseData.dataType() == "int") Serial.println(firebaseData.intData());
      else if (firebaseData.dataType() == "float") Serial.println(firebaseData.floatData());
      else if (firebaseData.dataType() == "string") Serial.println(firebaseData.stringData());
      else if (firebaseData.dataType() == "json") Serial.println(firebaseData.jsonData());
      Serial.println("--------------------------------");
      Serial.println();
    } else {
      Serial.println("----------Can't set data--------");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println("--------------------------------");
      Serial.println();
    }
  }

}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void setup() {
  // Create unique device name
  createName();

  // Initialize Serial port
  Serial.begin(115200);
  // Send some device info
  Serial.print("Build: ");
  Serial.println(compileDate);

  Preferences preferences;
  preferences.begin("WiFiCred", false);
  bool hasPref = preferences.getBool("valid", false);
  if (hasPref) {
    ssidPrim = preferences.getString("ssidPrim", "");
    ssidSec = preferences.getString("ssidSec", "");
    pwPrim = preferences.getString("pwPrim", "");
    pwSec = preferences.getString("pwSec", "");

    if (ssidPrim.equals("")
        || pwPrim.equals("")
        || ssidSec.equals("")
        || pwPrim.equals("")) {
      Serial.println("Found preferences but credentials are invalid");
    } else {
      Serial.println("Read from preferences:");
      Serial.println("primary SSID: " + ssidPrim + " password: " + pwPrim);
      Serial.println("secondary SSID: " + ssidSec + " password: " + pwSec);
      hasCredentials = true;
    }
  } else {
    Serial.println("Could not find preferences, need send data over BLE");
  }
  preferences.end();

  // Start BLE server
  initBLE();

  if (hasCredentials) {
    // Check for available AP's
    if (!scanWiFi) {
      Serial.println("Could not find any AP");
    } else {
      // If AP was found, start connection
      connectWiFi();
    }
  }

}

void loop() {
  if (connStatusChanged) {
    if (isConnected) {
      Serial.print("Connected to AP: ");
      Serial.print(WiFi.SSID());
      Serial.print(" with IP: ");
      Serial.print(WiFi.localIP());
      Serial.print(" RSSI: ");
      Serial.println(WiFi.RSSI());
    } else {
      if (hasCredentials) {
        Serial.println("Lost WiFi connection");
        // Received WiFi credentials
        if (!scanWiFi) { // Check for available AP's
          Serial.println("Could not find any AP");
        } else { // If AP was found, start connection
          connectWiFi();
        }
      }
    }
    connStatusChanged = false;
  }
}
cruizg commented 5 years ago

Hi, I was try your sketch and this is the result:

10:30:02.157 -> Build: Feb 5 2019 10:29:05 10:30:02.157 -> Read from preferences: 10:30:02.190 -> primary SSID: esp8266 password: Admin123 10:30:02.190 -> secondary SSID: cruiz password: $Admin123#8 10:30:02.829 -> [D][BLEDevice.cpp:444] setPower(): >> setPower: 7 10:30:02.829 -> [D][BLEDevice.cpp:449] setPower(): << setPower 10:30:02.829 -> [D][BLEDevice.cpp:70] createServer(): >> createServer 10:30:02.829 -> [D][BLEServer.cpp:305] registerApp(): >> registerApp - 0 10:30:02.829 -> [D][BLEDevice.cpp:96] gattServerEventHandler(): gattServerEventHandler [esp_gatt_if: 4] ... ESP_GATTS_REG_EVT 10:30:02.863 -> [D][BLEUtils.cpp:1647] dumpGattServerEvent(): GATT ServerEvent: ESP_GATTS_REG_EVT 10:30:02.863 -> [D][BLEUtils.cpp:1791] dumpGattServerEvent(): [status: ESP_GATT_OK, app_id: 0] 10:30:02.863 -> [D][BLEServer.cpp:177] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_REG_EVT 10:30:02.863 -> [D][BLEServer.cpp:309] registerApp(): << registerApp 10:30:02.896 -> [D][BLEServer.cpp:295] handleGATTServerEvent(): << handleGATTServerEvent 10:30:02.896 -> [D][BLEDevice.cpp:77] createServer(): << createServer 10:30:02.896 -> [D][BLEServer.cpp:76] createService(): >> createService - 0000aaaa-ead2-11e7-80c1-9a214cf093ae 10:30:02.896 -> [D][BLEDevice.cpp:96] gattServerEventHandler(): gattServerEventHandler [esp_gatt_if: 4] ... ESP_GATTS_CREATE_EVT 10:30:02.896 -> [D][BLEUtils.cpp:1647] dumpGattServerEvent(): GATT ServerEvent: ESP_GATTS_CREATE_EVT 10:30:02.930 -> [D][BLEUtils.cpp:1716] dumpGattServerEvent(): [status: ESP_GATT_OK, service_handle: 40 0x28, service_id: [uuid: 0000aaaa-ead2-11e7-80c1-9a214cf093ae, inst_id: 0]] 10:30:02.930 -> [D][BLEServer.cpp:177] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_CREATE_EVT 10:30:02.930 -> [D][BLEService.cpp:211] setHandle(): >> setHandle - Handle=0x28, service UUID=0000aaaa-ead2-11e7-80c1-9a214cf093ae) 10:30:02.964 -> [D][BLEService.cpp:217] setHandle(): << setHandle 10:30:02.964 -> [D][BLEService.cpp:90] executeCreate(): << executeCreate 10:30:02.964 -> [D][BLEServer.cpp:295] handleGATTServerEvent(): << handleGATTServerEvent 10:30:02.964 -> [D][BLEServer.cpp:94] createService(): << createService 10:30:02.964 -> [D][BLEService.cpp:239] addCharacteristic(): >> addCharacteristic() 10:30:02.964 -> [D][BLEService.cpp:242] addCharacteristic(): Adding characteristic: uuid=00005555-ead2-11e7-80c1-9a214cf093ae to service: UUID: 0000aaaa-ead2-11e7-80c1-9a214cf093ae, handle: 0x28 10:30:02.998 -> [D][BLEService.cpp:254] addCharacteristic(): << addCharacteristic() 10:30:02.998 -> [D][BLECharacteristic.cpp:592] setCallbacks(): >> setCallbacks: 0x3ffef6dc 10:30:02.998 -> [D][BLECharacteristic.cpp:594] setCallbacks(): << setCallbacks 10:30:02.998 -> [D][BLEService.cpp:148] start(): >> start(): Starting service (esp_ble_gatts_start_service): UUID: 0000aaaa-ead2-11e7-80c1-9a214cf093ae, handle: 0x28 10:30:03.032 -> [D][BLECharacteristic.cpp:83] executeCreate(): >> executeCreate() 10:30:03.032 -> [D][BLECharacteristic.cpp:94] executeCreate(): Registering characteristic (esp_ble_gatts_add_char): uuid: 00005555-ead2-11e7-80c1-9a214cf093ae, service: UUID: 0000aaaa-ead2-11e7-80c1-9a214cf093ae, handle: 0x28 10:30:03.032 -> [D][BLEDevice.cpp:96] gattServerEventHandler(): gattServerEventHandler [esp_gatt_if: 4] ... ESP_GATTS_ADD_CHAR_EVT 10:30:03.065 -> [D][BLEUtils.cpp:1647] dumpGattServerEvent(): GATT ServerEvent: ESP_GATTS_ADD_CHAR_EVT 10:30:03.065 -> [D][BLEUtils.cpp:1669] dumpGattServerEvent(): [status: ESP_GATT_OK, attr_handle: 42 0x2a, service_handle: 40 0x28, char_uuid: 00005555-ead2-11e7-80c1-9a214cf093ae] 10:30:03.065 -> [D][BLEServer.cpp:177] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_ADD_CHAR_EVT 10:30:03.099 -> [D][BLECharacteristic.cpp:609] setHandle(): >> setHandle: handle=0x2a, characteristic uuid=00005555-ead2-11e7-80c1-9a214cf093ae 10:30:03.099 -> [D][BLECharacteristic.cpp:611] setHandle(): << setHandle 10:30:03.099 -> [D][BLECharacteristic.cpp:209] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_ADD_CHAR_EVT 10:30:03.099 -> [D][BLECharacteristic.cpp:461] handleGATTServerEvent(): << handleGATTServerEvent 10:30:03.133 -> [D][BLECharacteristic.cpp:135] executeCreate(): << executeCreate 10:30:03.133 -> [D][BLEServer.cpp:295] handleGATTServerEvent(): << handleGATTServerEvent 10:30:03.133 -> [D][BLEDevice.cpp:96] gattServerEventHandler(): gattServerEventHandler [esp_gatt_if: 4] ... ESP_GATTS_START_EVT 10:30:03.133 -> [D][BLEUtils.cpp:1647] dumpGattServerEvent(): GATT ServerEvent: ESP_GATTS_START_EVT 10:30:03.167 -> [D][BLEUtils.cpp:1805] dumpGattServerEvent(): [status: ESP_GATT_OK, service_handle: 0x28] 10:30:03.167 -> [D][BLEServer.cpp:177] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_START_EVT 10:30:03.167 -> [D][BLEService.cpp:174] start(): << start() 10:30:03.167 -> [D][BLECharacteristic.cpp:209] handleGATTServerEvent(): >> handleGATTServerEvent: ESP_GATTS_START_EVT 10:30:03.167 -> [D][BLEAdvertising.cpp:174] start(): >> start: customAdvData: 0, customScanResponseData: 0 10:30:03.201 -> [D][BLECharacteristic.cpp:461] handleGATTServerEvent(): << handleGATTServerEvent 10:30:03.201 -> [D][BLEAdvertising.cpp:194] start(): - no services advertised 10:30:03.201 -> [D][BLEServer.cpp:295] handleGATTServerEvent(): << handleGATTServerEvent 10:30:03.201 -> [D][BLEAdvertising.cpp:231] start(): << start 10:30:03.201 -> [D][BLEUtils.cpp:1091] dumpGapEvent(): Received a GAP event: ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT 10:30:03.234 -> [D][WiFiGeneric.cpp:345] _eventCallback(): Event: 2 - STA_START 10:30:03.234 -> [D][WiFiGeneric.cpp:345] _eventCallback(): Event: 0 - WIFI_READY 10:30:03.234 -> 10:30:03.234 -> Start connection to esp8266 10:30:03.234 -> [D][BLEUtils.cpp:1099] dumpGapEvent(): [status: 0] 10:30:03.234 -> [D][BLEServer.cpp:135] handleGAPEvent(): BLEServer ... handling GAP event! 10:30:03.267 -> [D][BLEUtils.cpp:1091] dumpGapEvent(): Received a GAP event: ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT 10:30:03.267 -> [D][BLEUtils.cpp:1285] dumpGapEvent(): [status: 0] 10:30:03.267 -> [D][BLEServer.cpp:135] handleGAPEvent(): BLEServer ... handling GAP event! 10:30:03.267 -> [D][BLEUtils.cpp:1091] dumpGapEvent(): Received a GAP event: ESP_GAP_BLE_ADV_START_COMPLETE_EVT 10:30:03.267 -> [D][BLEUtils.cpp:1123] dumpGapEvent(): [status: 0] 10:30:03.301 -> [D][BLEServer.cpp:135] handleGAPEvent(): BLEServer ... handling GAP event! 10:30:04.142 -> [D][WiFiGeneric.cpp:345] _eventCallback(): Event: 4 - STA_CONNECTED 10:30:04.209 -> [D][WiFiGeneric.cpp:345] _eventCallback(): Event: 7 - STA_GOT_IP 10:30:04.209 -> [D][WiFiGeneric.cpp:389] _eventCallback(): STA IP: 192.168.43.18, MASK: 255.255.255.0, GW: 192.168.43.1 10:30:04.242 -> Connected to wifi 10:30:04.242 -> SSID: esp8266 10:30:04.242 -> IP Address: 192.168.43.18 10:30:04.242 -> signal strength (RSSI):-30 dBm 10:30:04.242 -> 10:30:04.242 -> ----------------------------------- 10:30:04.242 -> ----------Begin Set Test----------- 10:30:04.242 -> ----------------------------------- 10:30:04.276 -> 10:30:04.276 -> [V][ssl_client.cpp:53] start_ssl_client(): Free heap before TLS 32720 10:30:04.276 -> [V][ssl_client.cpp:55] start_ssl_client(): Starting socket 10:30:04.882 -> [V][ssl_client.cpp:88] start_ssl_client(): Seeding the random number generator 10:30:04.882 -> [V][ssl_client.cpp:97] start_ssl_client(): Setting up the SSL/TLS structure... 10:30:04.916 -> [I][ssl_client.cpp:121] start_ssl_client(): WARNING: Use certificates for a more secure communication! 10:30:04.916 -> [V][ssl_client.cpp:145] start_ssl_client(): Setting hostname for TLS session... 10:30:04.916 -> [E][ssl_client.cpp:33] handle_error(): SSL - Memory allocation failed 10:30:04.916 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code: -32512 10:30:04.916 -> [E][WiFiClientSecure.cpp:109] connect(): start_ssl_client: -32512 10:30:04.950 -> [V][ssl_client.cpp:211] stop_ssl_socket(): Cleaning SSL connection. 10:30:05.016 -> ----------Can't set data-------- 10:30:05.049 -> REASON: connection refused 10:30:05.049 -> -------------------------------- 10:30:05.049 -> 10:30:05.049 -> [V][ssl_client.cpp:211] stop_ssl_socket(): Cleaning SSL connection. 10:30:05.049 -> [V][ssl_client.cpp:53] start_ssl_client(): Free heap before TLS 32048 10:30:05.049 -> [V][ssl_client.cpp:55] start_ssl_client(): Starting socket 10:30:05.183 -> [V][ssl_client.cpp:88] start_ssl_client(): Seeding the random number generator 10:30:05.216 -> [V][ssl_client.cpp:97] start_ssl_client(): Setting up the SSL/TLS structure... 10:30:05.216 -> [I][ssl_client.cpp:121] start_ssl_client(): WARNING: Use certificates for a more secure communication! 10:30:05.216 -> [V][ssl_client.cpp:145] start_ssl_client(): Setting hostname for TLS session... 10:30:05.216 -> [E][ssl_client.cpp:33] handle_error(): SSL - Memory allocation failed 10:30:05.250 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code: -32512 10:30:05.250 -> [E][WiFiClientSecure.cpp:109] connect(): start_ssl_client: -32512 10:30:05.250 -> [V][ssl_client.cpp:211] stop_ssl_socket(): Cleaning SSL connection.

cruizg commented 5 years ago

Thank you very much, the problem was that since the ESP32 repository was updated (now works from the Arduino IDE and not the manual installation), in the Arduino IDE you have to update the board, do that and now it works fine. (close)

mobizt commented 5 years ago

The error caused by low internal memory (RAM) due to both BLE and WiFi (mbedTLS) use large memory.

Your free heap is only about 32K before start SSL connection which mbedTLS required more memory to work (may be > 100K), which cause SSL connection to failed.

If you write your code that uses more memory, the WiFi connection may failed again.

I recommend to check the preference for saved WiFi credentials (ssid and password) at the begining and start BLE server only when no preference found or WiFi connection attemp failed.

Once BLE device was connected and some WiFi config was received then save and restart to begin the device with more memory (without BLE sever start).