ESP32 with Rest Api in Cloud Firestore - c++

I'm working with ESP32 with Cloud Firestore. I'm attempting to make a request to get the data from a certain collection and document.
I have been able to access a single collection but, I'm having problems accessing a subcollection.
This is my ESP32 code to get the collection data:
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#define lamp 13
const char* ssid = "SSID";
const char* password = "Ok";
void setup() {
Serial.begin(115200);
pinMode(lamp, OUTPUT);
WiFi.begin(ssid, password);
delay(5000);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("stuff.net/app/api/read/5j5UF0lFovW8g5QSXXymWYsz0QB2");
int httpCode = http.GET();
if (httpCode > 0){
String payload = http.getString(); //ISSO É PARA GET REQUEST
Serial.println(httpCode);
Serial.println(payload);
char json[500];
payload.toCharArray(json, 500);
StaticJsonDocument<1024> doc;
deserializeJson(doc, json);
String device0 = doc["device0"];
}
http.end();
}else{
Serial.println("Erro com conexão, chekar conexão ao WiFi");
}
delay(1000);
}
This is how my Firestore looks:
I have attempted:
https://stuff.net/app/api/read/5j5UF0lFovW8g5QSXXymWYsz0QB2/buttons/button0
Won't work

Related

Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url), How can i solve this issue?

I run this code and get the massage:
Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
what can I do?
//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP8266 library and board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
//----------------------------------------
#define ON_Board_LED 2 //--> Defining an On Board LED (GPIO2 = D4), used for indicators when the process of connecting to a wifi router
#define LED_D8 15 //--> Defines an LED Pin. D8 = GPIO15
//---------------------------------------SSID and Password of your WiFi router.
const char* ssid = "*wifi name*"; //--> Your wifi name or SSID.
const char* password = "*Wfif password*"; //--> Your wifi password.
//----------------------------------------
//----------------------------------------Web Server address / IPv4
// If using IPv4, press Windows key + R then type cmd, then type ipconfig (If using Windows OS).
const char *host = "https://localhost/";
//----------------------------------------
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
pinMode(LED_D8,OUTPUT); //--> LED port Direction output
digitalWrite(LED_D8, LOW); //--> Turn off Led
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
//----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
}
void loop() {
// put your main code here, to run repeatedly:
HTTPClient http; //--> Declare object of class HTTPClient
WiFiClient WiFiClient;
//----------------------------------------Getting Data from MySQL Database
String GetAddress, LinkGet, getData;
int id = 0; //--> ID in Database
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress; //--> Make a Specify request destination
getData = "ID=" + String(id);
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
http.begin("LinkGet");
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCodeGet = http.POST(getData); //--> Send the request
String payloadGet = http.getString(); //--> Get the response payload from server
Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Serial.println(httpCodeGet); //--> Print HTTP return code
Serial.print("Returned data from Server : ");
Serial.println(payloadGet); //--> Print request response payload
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH); //--> Turn off Led
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW); //--> Turn off Led
}
//----------------------------------------
Serial.println("----------------Closing Connection----------------");
http.end(); //--> Close connection
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000); //--> GET Data at every 5 seconds
}
I want my esp8266 to connect to my database(MySql) and get a value to turn on/off a led light.
The esp im using is the NodeMCU epp8266.
Apart from the actual issue that causes the compile error there are several other things wrong with this code. I fixed the most obvious ones. See the explanations for the callouts below the code.
// <1>
#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
//#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
//#include <ESP8266WebServer.h>
//#include <ESP8266HTTPClient.h>
//#include <WiFiClientSecureBearSSL.h>
#define ON_Board_LED 2
#define LED_D8 15
const char* ssid = "********";
const char* password = "********";
// <2>
// <3>
const char* host = "http://192.168.1.1/";
// <4>
String GetAddress, LinkGet, getData;
int id = 0;
// <5>
HTTPClient http;
WiFiClient client;
// <6>
void connectWiFi() {
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH);
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(500);
// <7>
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress;
getData = "ID=" + String(id);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
pinMode(ON_Board_LED, OUTPUT);
digitalWrite(ON_Board_LED, HIGH);
pinMode(LED_D8, OUTPUT);
digitalWrite(LED_D8, LOW);
}
void loop() {
// <8>
// // put your main code here, to run repeatedly:
// HTTPClient http; //--> Declare object of class HTTPClient
// WiFiClient WiFiClient;
// <9>
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
// <10>
http.begin(client, LinkGet);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCodeGet = http.POST(getData);
String payloadGet = http.getString();
Serial.print("Response Code : ");
Serial.println(httpCodeGet);
Serial.print("Returned data from Server : ");
Serial.println(payloadGet);
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH);
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW);
}
Serial.println("----------------Closing Connection----------------");
http.end();
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000);
}
Clean up the includes such that only those remain which you actually need.
With this sketch your host cannot be (and likely is not) reachable using SSL/TLS encryption (https -> http).
localhost is wrong as this would point to the ESP8266 itself (loopback). You need the PC IP address or possibly its hostname here.
Declare global variables globally i.e. outside loop().
Declare and initialize the HTTPClient and WiFiClient globally rather than inside the loop(). See my answer here https://stackoverflow.com/a/59701884/131929 for more.
Put the WiFi-connecting code in a separate function - you'll need it later.
Initialize the global variables in setup() rather than loop(); goes along with <4>.
Don't instantiate those over and over again; goes along with <5>.
Verify the device is still connected to WiFi every time loop() is invoked and re-connect if not.
Compile error: http.begin() takes a WiFiClient plus that actual HTTP address. This is what the compile error message tells you.

Problem in Django cooperation with esp 8266

Hello i need help with my django project . I want to run program on ESP 8266 from django website. To test I create simple program with blink diode on ESP and I made button on my django website and it works but I use "webbrowser()" in views.py and it is not looks perfect (I need to stay on this webiste, a webiste made in django, not open a new one). I need help to create something what will work like:
I click the button on my django website, program in "views.py" send something to esp what runs program on it or change something in the ESP code, which is only going to run the code, and it won't open web browser.
my views.py:
def espON(request):
on = On.objects.all()
off = Off.objects.all()
menu = menu.objects.all()
webbrowser.open("http://my_ip/turnOn")
d = {'on':on, 'off':off, 'menu':menu,}
return render(request, 'on/index.html', d)
ESP code:
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <Math.h>
const char* ssid = "my_ssid"; //nazwa ssid sieci
const char* password = "my_password"; //haslo
#define LED 5
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(LED, OUTPUT);
//Laczenie z siecia wifi
Serial.println();
Serial.println();
Serial.print("Laczenie z: ");
Serial.println(ssid);
IPAddress ip(my_ip); //ip
IPAddress gateway(my_ip2);
IPAddress subnet(my_ip3);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi polaczone");
// Start
server.begin();
Serial.println("Serwer uruchomiony");
}
void loop() {
while (WiFi.status() == WL_CONNECTED){
WiFiClient client = server.available();
if (!client) {
return;
}
String request = client.readStringUntil('\r');
client.flush();
//condition
if (request.indexOf("/turnOn") > 0)
{
digitalWrite(LED, HIGH); //work
}
if (request.indexOf("/turnOff") > 0) //not
{
digitalWrite(LED, LOW);
}
}
}

Guru Meditation Error Core 0 panic'ed (LoadProhibited). Exception was unhandled

error project
Guru Meditation Error in project
Core 0 panic'ed (LoadProhibited). Exception was unhandled.
I have project using pulsesensor with ESP32, Data from ESP32 is saved in database.
I tried many times but could not
help me
#include <ssl_client.h>
#include <WiFiClientSecure.h>
#include <WiFi.h>
#include <SPI.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
/* Konfigurasi pada SSID dan Password Wifi */
const char* ssid = "berdikari";
const char* password = "alfian24";
/* Konfigurasi koneksi ke server */
char server[] = "192.168.43.108"; // Ganti dengan IP Address komputer aplikasi
int port = 81;
/*konfigurasi*/
int PulseSensorPurplePin = 34; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED21 = 21; // The on-board Arduion LED
int Signal; // holds the incoming raw data. Signal value can range from 0-102
float pulse=0;
WiFiClient client;
void setup() {
USE_SERIAL.begin(115200); // Baudrate/kec. komunikasi pengiriman data ke serial terminal
delay(10);
Serial.println('\n');
WiFi.begin(ssid, password);
USE_SERIAL.print("Terhubung ke ");
USE_SERIAL.print(ssid);
// WiFi.config(local_IP, gateway, subnet, dns);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
USE_SERIAL.print('.');
}
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas ESP-32");
USE_SERIAL.print("IP Address:\t");
USE_SERIAL.println(WiFi.localIP()); // IP Address ESP-32
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas Web Server");
USE_SERIAL.println("IP Address:");
USE_SERIAL.print(server);
USE_SERIAL.print("\tport:\t");
USE_SERIAL.print(port);
}
void loop() {
Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor’s value.
// Send the Signal value to Serial Plotter.
delay(1000);
pulse = Signal;
USE_SERIAL.println(pulse);
if(WiFi.status() == WL_CONNECTED){
//URL target untuk menyimpan data sensor Pulse ke database
String url = "http://192.168.43.108:81/";
url += "sistem_monitoring/Monitoring/simpan/";
url += String(pulse);
HTTPClient http;
USE_SERIAL.print("[HTTP] begin...\n");
http.begin(url);
USE_SERIAL.print("[HTTP] GET...\n");
int httpCode = http.GET();
if(httpCode > 0) {
USE_SERIAL.printf("[HTTP] GET... code: %d\n",
httpCode);
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();
}
}
please help me.
What should I do??
I've seen this question asked a few times but never got a good answer.

ESP32 to ESP32 AP/client WiFi connection problem

Trying to communicate from one ESP32 to another ESP32 ,with one acting as a AP and another acting as Client but cant seem to connect the esp client to the esp AP, but connecting to AP using my smartphone works.Sorry if this seems to be a simple questions, I am new to esp32s and WiFI communication.
Code for the Access-point
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
Serial.print("MAC address: ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client)
{ Serial.println("New Client.");
while (client.connected())
{
Serial.println(client.connected());
Serial.println("Client connected.");
Serial.println("");
}
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Code for the Client
#include <WiFi.h>
#include <SPI.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
scanNetworks();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
}
void scanNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");
byte numSsid = WiFi.scanNetworks();
// print the list of networks seen:
Serial.print("SSID List:");
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(") Network: ");
Serial.println(WiFi.SSID(thisNet));
}
}
As #juraj mentions, in the Arduino code for ESP32, you cannot initiate a scan while an attempt to connect to AP is already ongoing.
Call scanNetworks() before attempting to connect (before the WiFi.begin(ssid, password);).
or
Call scanNetworks() after the connection to the AP has been established (after the while (WiFi.status() != WL_CONNECTED){}).
I don't see any point to scan networks while trying to connect to a known WiFi AP anyway.
ESPnow (see example here ) is easy for ESP to ESP communication. (also ESP8266 etc)

ESP32 to ESP32 WiFi Server/Client Problem

I've got one ESP32 acting as client and another ESP32 acting as an access-point for direct communication and outdoor use.
I have set up a server on the AP end and would like the client to communicate with it but I can't seem to make this work.
I would like to know two things:
How do I send or write data to the server from the client?
How do I read and display the data that was sent to the server from the client?
I have attached the code below:
Code for AP/Server
//SERVER
//Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
//Set web server port number to 80
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address ");
Serial.println(IP);
Serial.print("MAC address ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop(){
WiFiClient client = server.available(); //Listen for incoming clients
if (client)
{ //If a new client connects,
Serial.println("New Client."); //print a message out in the serial port
while (client.connected())
{
Serial.println("Client connected.");
Serial.println(client.available());
if (client.available() > 0)
{
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
client.stop();
Serial.println("Client disconnected.");
Serial.println();
}
}
Code for Client
//Client
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
WiFiClient client;
IPAddress server(192, 168, 4, 1);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
if(client.connect(server, 80))
{
Serial.println("connected to server");
client.write("Data");
}
else
{
Serial.println("failed to connect to server");
}
}
void loop()
{
}
Alternatively to the previous answer, you could use espnow as a protocol between various esp32. Here an example.
You must implement some sort of protocol like TCP, UDP to exchange data.
Example Project using TCP
https://www.instructables.com/id/WiFi-Communication-Between-Two-ESP8266-Based-MCU-T/
Example Project using UDP
https://circuits4you.com/2018/01/01/esp-to-esp-communication/
Look at this very handy function:
void SetWifi(const char *name, const char *password) { // Turn on wifi with server
Serial.println("Starting server");
WiFi.disconnect();
WiFi.softAP(name, password);
delay(2000);
IPAddress IP = WiFi.softAPIP();
Serial.print("Server IP : ");
Serial.println(IP);
server.begin();
server.setNoDelay(true);
Serial.println("Server started");
}
You can write data with this function :
void sendDataTCP(String message) { // function to send message back to client
if (client && client.connected()) { //check if client is there
client.println(message);
}
client.flush();
}
Receive data with this function:
void availableMessage() {
if (client.available()) {//check if client is there
while (client.available()) {
String message = client.readStringUntil('\n'); //read string until enter (end of message)
Serial.println("Received: " + message);
message.toCharArray(buffer, BUFFER); // put message in char array (buffer)
client.flush(); // discard all bytes that have been read
}
}
}
Check if someone has connected:
void connectClient() {
if (server.hasClient()) // if server has a client
{
if (client = server.available()) { // if client is connected
Serial.println("Connected");
}
}
}
I think this will get you in the direction of accomplishing your goal, good luck!