'(esp 32) http.GET() is so slow
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 ?
Solution 1:[1]
The root of the problem is the TLS handshake in establishing an HTTPS connection and its crypto math, which does tend to take approximately 2 seconds on the little ESP32.
The solution is to not create a new HTTPS connection with each query and close it when done. For this you need persistent HTTPS connections which are supported by the HTTP client library in Espressif ESP IDF or alternatively websockets. Maybe there's a library in Arduino to do this, I don't know. Anyway, once you pick a library then open a connection once and keep it open for subsequent queries.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tarmo |
