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

I can't use wifimanager with firebase and use esp-now communication #319

Closed Manuel-Savyak closed 7 months ago

Manuel-Savyak commented 7 months ago

Is there any way i can connect to the internet without hardcoding the ssid?

I have been trying to use WifiManager to connect to Wifi and after it connects i need to send data to Firebase RealtimeDatabase. But at the same time i need to be using Esp-Now communication. If I try both at the same time in the best case scenario my master (the one that is connected to the firebase) always sends with sucess and the slave only receives for a short period of time (4-5min) and then just gives delivery fail for no reason. I have tried to connect them to the same wifi network using WifiManager but it didnt work. Note that i really cant hardcode the SSID and the Password.

Board: Esp32 Dev Module Esp-32 Devkitc_v4 arduino ide 2.3.2

This is the master code:

include

include

include

include "BluetoothSerial.h"

include

include

include

include "time.h"

// Provide the token generation process info.

include "addons/TokenHelper.h"

// Provide the RTDB payload printing info and other helper functions.

include "addons/RTDBHelper.h"

// Insert Firebase project API Key

define API_KEY "AIzaSyDbzGBJzR7CRkLbPw-YBPxKz7-jdO5XDYQ"

// Insert Authorized Email and Corresponding Password

define USER_EMAIL "fantapicante910@gmail.com"

define USER_PASSWORD "ornitorringo"

// Insert RTDB URLefine the RTDB URL

define DATABASE_URL "https://esp1-69542-default-rtdb.europe-west1.firebasedatabase.app/"

// init Class: BluetoothSerial ESP_BT;

// Define Firebase objects FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig config;

// Variable to save USER UID String uid;

// Database main path (to be updated in setup with the user UID) String databasePath; // Database child nodes String golos = "/golos"; String bolas = "/bolas"; String timePath = "/timestamp";

// Parent Node (to be updated in every loop) String parentPath;

int timestamp; FirebaseJson json;

const char *ntpServer = "pool.ntp.org";

// Define variables to store BME280 readings to be sent int ze;

// Define variables to store incoming readings int zerecebe;

// Variable to store if sending data was successful String success;

uint8_t broadcastAddress[] = { 0x10, 0x97, 0xBD, 0xD4, 0xE8, 0x18 };

esp_err_t result1;

//Structure example to send data //Must match the receiver structure typedef struct struct_message { int ze; } struct_message;

// Create a struct_message called BME280Readings to hold sensor readings struct_message mensagem_enviada;

// Create a struct_message to hold incoming sensor readings struct_message mensagem_recebida;

esp_now_peer_info_t peerInfo;

// Function that gets current epoch time unsigned long getTime() { time_t now; struct tm timeinfo; if (!getLocalTime(&timeinfo)) { //Serial.println("Failed to obtain time"); return (0); } time(&now); return now; }

// callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { char macStr[18]; Serial.print("Packet to: "); // Copies the sender mac address to a string snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); Serial.print(macStr); Serial.print(" send status:\t"); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); }

void OnDataRecv(const uint8_t mac, const uint8_t incomingData, int len) { memcpy(&mensagem_recebida, incomingData, sizeof(mensagem_recebida)); Serial.print("Bytes received: "); Serial.println(len); zerecebe = mensagem_recebida.ze; Serial.print("ze"); Serial.println(zerecebe); }

void setup() { // put your setup code here, to run once: Serial.begin(115200); WiFi.mode(WIFI_STA); WiFiManager wm; bool res; res = wm.autoConnect("ESPMaster");

ESP_BT.begin("ESP32_Control");

configTime(0, 0, ntpServer);

// Assign the api key (required) config.api_key = API_KEY;

// Assign the user sign in credentials auth.user.email = USER_EMAIL; auth.user.password = USER_PASSWORD;

// Assign the RTDB URL (required) config.database_url = DATABASE_URL;

Firebase.reconnectWiFi(true); fbdo.setResponseSize(4096);

// Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h

// Assign the maximum retry of token generation config.max_token_generation_retry = 5;

// Initialize the library with the Firebase authen and config Firebase.begin(&config, &auth);

// Getting the user UID might take a few seconds Serial.println("Getting User UID"); while ((auth.token.uid) == "") { Serial.print('.'); delay(1000); } // Print user UID uid = auth.token.uid.c_str(); Serial.print("User UID: "); Serial.println(uid);

// Update database path databasePath = "/UsersData/" + uid + "/readings";

if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; }

esp_now_register_send_cb(OnDataSent);

// register peer peerInfo.channel = 0; peerInfo.encrypt = false; // register first peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } // Register for a callback function that will be called when data is received esp_now_register_recv_cb(OnDataRecv); }

void loop() { // put your main code here, to run repeatedly:// Send message via ESP-NOW mensagem_enviada.ze = 24; esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&mensagem_enviada, sizeof(mensagem_enviada)); if (result == ESP_OK) { Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); } if (Firebase.ready()) { //Get current timestamp timestamp = getTime(); Serial.print("time: "); Serial.println(timestamp);

parentPath = databasePath + "/" + String(timestamp);
json.set(golos.c_str(), String(13));
json.set(timePath, String(timestamp));
Serial.printf("Set json... %s\n", Firebase.RTDB.setJSON(&fbdo, parentPath.c_str(), &json) ? "ok" : fbdo.errorReason().c_str());

} delay(5000); }

And this is the slave code:

include

include

include

// Define variables to store BME280 readings to be sent int ze;

// Define variables to store incoming readings int zerecebe;

// Variable to store if sending data was successful String success;

uint8_t broadcastAddress[] = { 0x10, 0x97, 0xBD, 0xD4, 0xDF, 0x48 };

esp_err_t result1;

//Structure example to send data //Must match the receiver structure typedef struct struct_message { int ze; } struct_message;

// Create a struct_message called BME280Readings to hold sensor readings struct_message mensagem_enviada;

// Create a struct_message to hold incoming sensor readings struct_message mensagem_recebida;

esp_now_peer_info_t peerInfo;

// callback when data is sent void OnDataSent(const uint8_t mac_addr, esp_now_send_status_t status) { char macStr[18]; Serial.print("Packet to: "); // Copies the sender mac address to a string snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); Serial.print(macStr); Serial.print(" send status:\t"); Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); } void OnDataRecv(const uint8_t mac, const uint8_t *incomingData, int len) { memcpy(&mensagem_recebida, incomingData, sizeof(mensagem_recebida)); Serial.print("Bytes received: "); Serial.println(len); zerecebe = mensagem_recebida.ze; Serial.print("ze"); Serial.println(zerecebe); } void setup() { // put your setup code here, to run once: Serial.begin(115200); WiFi.mode(WIFI_STA); WiFiManager wm; bool res; res = wm.autoConnect("ESPSlave");

if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; }

esp_now_register_send_cb(OnDataSent);

// register peer peerInfo.channel = 0; peerInfo.encrypt = false; // register first peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } // Register for a callback function that will be called when data is received esp_now_register_recv_cb(OnDataRecv); }

void loop() { // put your main code here, to run repeatedly:// Send message via ESP-NOW mensagem_enviada.ze = 24; esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&mensagem_enviada, sizeof(mensagem_enviada)); if (result == ESP_OK) { Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); } delay(5000); }

Am i doing anything wrong or is it the hardware that doesnt allow me to use both at the same time?

mobizt commented 7 months ago

You should post in the discussion instead.

You should remove this function. Firebase.reconnectWiFi(true);

In the recent version, this function was renamed, and you will see this comment in the examples. https://github.com/mobizt/Firebase-ESP32/blob/01ad533f93c8dc18c53fbe05e3d0bedbffdc46d8/examples/Basic/Basic.ino#L81-L82