I want to get data from REST API by an esp32 and turning on and off LED lights(GPIO 26 and 27).
Here is my code :
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFi.h>
const char* ssid = "ssidName";
const char* password = "password";
void setup() {
Serial.begin(115200);
pinMode(26, OUTPUT);
pinMode(27, OUTPUT);
digitalWrite(26, LOW);
digitalWrite(27, LOW);
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("https://retoolapi.dev/XB1y0H/data");
int httpCode = http.GET();
if (httpCode > 0){
String payload = http.getString();
payload.replace('[', ' ');
payload.replace(']', ' ');
char json[500];
payload.toCharArray(json, 500);
StaticJsonDocument<1024> doc;
deserializeJson(doc, json);
String led1 = doc["rele1"];
Serial.print("led1 :");
Serial.println(led1);
if(led1== "1") digitalWrite(26, HIGH);
else digitalWrite(26, LOW);
String led2 = doc["rele2"];
if(led2 == "1") digitalWrite(27, HIGH);
else digitalWrite(27, LOW);
Serial.print("led2 :");
Serial.println(led2);
}
http.end();
}else{
Serial.println("Check your internet connection");
}
}
It works but the problem is , it is so slow ; http.GET() takes approximately 2 seconds to be executed and I dont know why ...
Is it because of API ?
Is there any better solution ? I've heard about webSocket but I'm not sure about it .
Is it good and easy to integrate ?
The request is slow due to the ESP32 having to create the TLS (HTTPS) connection everytime which takes up to 2 seconds.
To resolve this, you can re-use the TLS connection for future requests ("persistent HTTPS connections").
Please see below a snippet of how to re-use connections and speed up requests with ESP32, which has been copied from source
HTTPClient http;
void setup() {
// allow reuse (if server supports it)
http.setReuse(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With