// Complete project details: https://RandomNerdTutorials.com/esp32-https-requests/
// Based on the BasicHTTPSClient.ino example found at Examples > BasicHttpsClient
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
String url = "https://www.services-rte.com/cms/open_data/v1/tempoLight";
WiFiClientSecure clientSecuRTE;
void setup() {
Serial.begin(115200);
Serial.println();
// Initialize Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
String getFormatedDate() {//DD/MM/YYYY
time_t timestamp = time(NULL) - 21600; //Decallage début période couleur RTE de 6h.
struct tm* pTime = localtime(×tamp);
if (timestamp < (30UL * 365 * 24 * 60 * 60 )) return String(); // an > 2000 = 30years in seconds
Serial.println(timestamp);
Serial.printf("Day of the week %d\n", pTime->tm_wday);
//strftime(buffer, MAX_SIZE_T, "%Y-%m-%d", pTime);
char buffer[12];
strftime(buffer, 12, "%d/%m/%Y", pTime);
return String(buffer);
}
String askTempo() {
String payload = "-";
WiFiClientSecure *client = new WiFiClientSecure;
if(client) {
client->setInsecure();// set secure client without certificate
HTTPClient https;//create an HTTPClient instance
//Initializing an HTTPS communication using the secure client
//Serial.printf("[HTTPS] begin ... %s\n",url.c_str());
if (https.begin(*client, url.c_str())) { // HTTPS
https.useHTTP10(true);
//Serial.print("[HTTPS] GET...\n");
// start connection and send HTTP header
int httpCode = https.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
//Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
payload = https.getString();
//Serial.println(payload);// print server response payload
}
} else {
Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
https.end();
} else {
Serial.printf("Problem during https.begin('%s')\n",url.c_str());
}
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
payload = payload.substring(payload.indexOf("{"));
payload = payload.substring(0,payload.indexOf("}}")+2);
delete client;
return payload;
}
// url attendu pour un port !=80 en http ou != 443 en https : le numero de port doit être après le host
// http://host:8080/uri
String httpGet(String url, String from = "", String until = "") {
String payload = "-";
WiFiClient *client = new WiFiClient;
WiFiClientSecure *clientSecur = new WiFiClientSecure;
bool https = url.indexOf("https") == 0;
HTTPClient http;//create an HTTPClient instance
//Initializing an HTTP communication
http.useHTTP10(true);
//Serial.printf("[HTTP] begin ... %s\n",url.c_str());
bool beginOk = false;
if (https) {
clientSecur->setInsecure();// set secure client without certificate
beginOk = http.begin(*clientSecur, url.c_str());
} else {
beginOk = http.begin(*client, url.c_str());
}
if (beginOk) {
//Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
//Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
payload = http.getString();
//Serial.println(payload);// print server response payload
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.printf("Problem during http.begin('%s')\n",url.c_str());
}
if (from != "" & payload.indexOf(from) >=0 ) payload = payload.substring(payload.indexOf(from));
if (until != "" & payload.indexOf(until) >=0 ) payload = payload.substring(0,payload.indexOf(until) + until.length());
delete clientSecur;
delete client;
return payload;
}
void loop() {
const char* adr_RTE_Host = "www.services-rte.com";
String Host = String(adr_RTE_Host);
String urlJSON = "/cms/open_data/v1/tempoLight";
String RTEdata = "";
clientSecuRTE.setInsecure(); //skip verification
//--------------------------
if (!clientSecuRTE.connect(adr_RTE_Host, 443, 3000)) {
clientSecuRTE.stop();
delay(100);
Serial.println("Connection failed to RTE server :" + Host);
} else {
clientSecuRTE.print(String("GET ") + urlJSON + " HTTP/1.1\r\n" + "Host: " + Host + "\r\n" + "Connection: close\r\n\r\n");
Serial.println("Request vers RTE Envoyé");
unsigned long timeout0 = millis();
while (clientSecuRTE.available() == 0) {
if (millis() - timeout0 > 5000) {
clientSecuRTE.stop();
delay(100);
Serial.println(">>> clientSecuRTE RTE Timeout !");
return;
}
}
while (clientSecuRTE.available() && (millis() - timeout0 < 5000)) {
RTEdata += char(clientSecuRTE.read());
}
Serial.printf("\n!%s!\n",RTEdata.c_str());
RTEdata = "";
}
//-----------------------------
if (!clientSecuRTE.connect(adr_RTE_Host, 443, 3000)) {
clientSecuRTE.stop();
delay(100);
Serial.println("Connection failed to RTE server :" + Host);
} else {
clientSecuRTE.print(String("GET ") + urlJSON + " HTTP/1.1\r\n" + "Host: " + Host + "\r\n" + "Connection: close\r\n\r\n");
Serial.println("Request vers RTE Envoyé");
unsigned long timeout = millis();
while (clientSecuRTE.available() == 0) {
if (millis() - timeout > 5000) {
clientSecuRTE.stop();
delay(100);
Serial.println(">>> clientSecuRTE RTE Timeout !");
return;
}
}
timeout = millis();
// Lecture de l'entête
int sizeOfContent = 0;
int dataLoad = 0;
while (clientSecuRTE.available() && (millis() - timeout < 5000)) {
String Reponse = clientSecuRTE.readStringUntil('\n');
if (Reponse.startsWith("Content-Length:")) sizeOfContent = Reponse.substring(16).toInt();
if (Reponse.startsWith("Transfer-Encoding: chunked")) sizeOfContent = -1; // plusieurs paquet de données commençant par leur taille CRLF
if (Reponse == "\r") break; // le ligne précédente finisait par \n, la ligne courante finie par \n et c'est la premier fois qu'on rencontre \r seul : on est au separateur entête/payload
}
Serial.printf("\nTaille selon entête: %d\n",sizeOfContent);
// Lecture des données brutes distantes
int fin = 0;
String line = "";
while (clientSecuRTE.connected() && (millis() - timeout < 5000) && fin < 2) {
line = clientSecuRTE.readStringUntil('\n');
dataLoad += line.length() + 1;
RTEdata += line;
if (line.indexOf("}}") >= 0) fin = 2;
}
Serial.println(sizeOfContent);
Serial.println(dataLoad);
Serial.println(RTEdata.length());
Serial.println(RTEdata);
clientSecuRTE.stop();
}
//--------------------------
WiFiClient *client = new WiFiClient;
WiFiClientSecure *clientSecur = new WiFiClientSecure;
HTTPClient http;//create an HTTPClient instance
String payload = "";
bool beginOk = false;
bool https = url.indexOf("https") == 0;
if (https) {
clientSecur->setInsecure();// set secure client without certificate
beginOk = http.begin(*clientSecur, url.c_str());
} else {
beginOk = http.begin(*client, url.c_str());
}
if (beginOk) {
//Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
//Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
payload = http.getString();
//Serial.println(payload);// print server response payload
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.printf("Problem during http.begin('%s')\n",url.c_str());
}
//------------------------
delete clientSecur;
delete client;
Serial.printf("\n***\n!%s!\n***\n",payload.c_str());// print server response payload
Serial.printf("Free mem : %d\n", esp_get_free_heap_size());
// Serial.println("AskTempo");
// Serial.println(askTempo());
Serial.println();
Serial.println("httpGet simple");
Serial.println(httpGet("http://arduinojson.org/example.json"));
Serial.println("httpGet vers un server https");
Serial.println(httpGet("https://www.services-rte.com/cms/open_data/v1/tempoLight"));
Serial.println();
Serial.println("httpGet et debut & fin");
Serial.println(httpGet("http://arduinojson.org:80/example.json", "time", "["));
Serial.println();
Serial.println(httpGet("http://arduinojson.org/example.json", "xyz", "["));
Serial.println();
Serial.println(httpGet("http://arduinojson.org:80/example.json", "time", "abcd"));
Serial.println();
Serial.println(httpGet("http://arduinojson.org:80/example.json", "xyz", "abcd"));
Serial.println("Waiting before the next round...");
delay(30000);
}
/*
// https://www.services-rte.com/cms/open_data/v1/tempoLight
char buffer[MAX_SIZE_T];
const char* adr_RTE_Host = "www.services-rte.com";
String Host = String(adr_RTE_Host);
String urlJSON = "/cms/open_data/v1/tempoLight";
String RTEdata = "";
String line = "";
String DateRTE = ""; //an-mois-jour
String DateRTE2 = ""; //an-mois-jour lendemain
*/