been trying to figure out a code for an ESP32 to send a POST API every 10seconds.
The code sucessfully connects to the Wifi and receive status 200 for every POST it does on the first connection. However, if I force the wifi off and turn it on again sometimes I receive a “HTTPClient initialized, Error code: -1” everytime, and then cannot make it work again.
Only method to make it work again is if I reupload the code to the ESP. Then it reconnects again and succeeds on the API calls.
*Important to say that at some reconnections it works also, but at some they get bugged with no return.
Code im using:
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <base64.h>
const char* ssid = "ssid";
const char* password = "pass";
const char* url = "https://url";
const char* stringconn = "user:password";
unsigned long lastRequestTime = 0;
const unsigned long requestInterval = 10000; // 10 seconds
const unsigned long maxBackoffInterval = 600000; // 10 minutes
unsigned long lastWifiCheckTime = 0;
unsigned long backoffInterval = 1000; // Initial backoff interval
const int maxConnectionAttempts = 5; // Maximum connection attempts
void setup() {
Serial.begin(115200);
connectToWiFi();
}
void loop() {
unsigned long currentTime = millis();
if (currentTime - lastWifiCheckTime >= backoffInterval) {
lastWifiCheckTime = currentTime;
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected, attempting to reconnect...");
connectToWiFi();
}
}
if (currentTime - lastRequestTime >= requestInterval) {
sendPostRequest();
lastRequestTime = currentTime;
}
}
void connectToWiFi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < maxConnectionAttempts) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connected!");
// Reset backoff interval on successful connection
backoffInterval = 1000;
} else {
Serial.println("Connection failed.");
// Exponential backoff
if (backoffInterval < maxBackoffInterval) {
backoffInterval *= 2;
}
}
}
// Function to send POST request
void sendPostRequest() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http; // Create a new HTTPClient instance
Serial.println("HTTPClient initialized");
http.begin(url); // Initialize the HTTP client instance
// Create JSON data
StaticJsonDocument<200> jsonDoc;
jsonDoc["device"] = "ESP_TST";
String jsonString;
serializeJson(jsonDoc, jsonString);
// Set headers
http.addHeader("Content-Type", "application/json");
// Set Basic Authentication
String encodedAuth = base64::encode(stringconn);
String authHeader = "Basic " + encodedAuth;
http.addHeader("Authorization", authHeader);
// Send the request only if connected
int httpResponseCode = http.POST(jsonString);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
} else {
Serial.println("WiFi not connected, cannot send POST request");
}
}
Tried several ways of reconnection, didnt work.
also tried chatgpt to seek for a solution: sugested delay, but doesnt seem to be the problem (or resolve the problem).
Filipe Herzer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.