http-sous-esp32 | Last modified: 1751485384 | Edit | Home

Requête HTTP (JSON)

Le cour du Bitcoin est disponible via l'API de Kraken (notamment) à l'adresse suivante: https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR. La doc nous aide à lire ces informations et l'on déduit que la valeur qui nous intéresse, c'est Last trade closed disponible par le chemin result -> XXBTZEUR -> c -> 0.

Cette information est sous le format JSON, on va donc utiliser la bibliothèque AdruinoJson qu'il faudra importer dans Arduino-API via le menu Stetch → Include libraries → Manage Libraries → Recherche par mot clef → Install. Concernant ce format, l'assistant sur le site de la lib est très sympa, ca permet de comprendre la structure JSON et il nous explique même comment récupérer les donner.

Avant cela, il faut aller chercher cette information à travers internet et la rapatrier sur le microcontrôleur. Et donc, on doit se connecter au Wifi (par exemple). Mais, bien entendu, avant tout, on a envie que le microcontrôleur puisse nous envoyer des messages pour voir que tout va bien. Et on veut l'info toutes les 5 sec, ce serait pas drôle.

On se mets en route:

Dans tous les exemples disponibles sur l'interface Arduino API, j'ai pas trouvé d'exemple simple de requête HTTP via le Wifi. J'ai alors mixé plusieurs codes. Voici mon résultat:

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);
  while (!Serial) delay(100);

  WiFi.begin("SSID", "P4ssw0rd");
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.println("Connected.");
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {

    HTTPClient http;

    // https://docs.kraken.com/api/docs/rest-api/get-ticker-information
    http.begin("https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR");

    int httpCode = http.GET();

    if (httpCode == HTTP_CODE_OK) {

      String response = http.getString();

      JsonDocument doc;
      DeserializationError error = deserializeJson(doc, response);
      if (error) {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.f_str());
      } else {
        Serial.print("BTC: ");
        Serial.println(doc["result"]["XXBTZEUR"]["c"][0].as<double>());
      }

    } else {

      Serial.printf("failed, error: %i %s\n", httpCode, http.errorToString(httpCode).c_str());

    }

    http.end();

  } else {

    Serial.println("Network unreachable");

  }

  delay(5000);
}

Le Wifi

Le Wifi est géré par la lib WiFi. Une session démarre avec Wifi.begin("your SSID", "p4sswOrd");. La fonction WiFi.status() == WL_CONNECTED permet de vérifier la connexion. La ligne while (Wifi.status() != WL_CONNECTED) delay(500); attend que la connexion soit effective. La plateforme s'est connectée en DHCP; la fonction WiFi.localIP() permet de connaître l'IP.

La requête HTTP

Pour la requête HTTP, on a besoin de la lib HTTPClient. Dès lors que la connexion est établie, on crée une instance HTTPClient qu'on fait démarrer avec la méthode begin("URL"). La méthode GET() renvoie le code HTTP qui, si égal à HTTP_CODE_OK, soit 200, annonce que tout va bien. La méthode getString() renvoie la réponse du serveur. Celle-ci est dans la plupart des cas une page Html, ou du texte, ou des données sous format Json. Si le code HTTP n'est pas 200, on a une erreur. Ne pas oublier de fermer l'objet http.

Dans notre cas, nous recevons un format JSON. On le désérialise, ca crée un tableau que l'on parcourt doc["result"]["XXBTZEUR"]["c"][0].as(); pour aller chercher la valeur attendue et on transforme le résultat en réel (c'est pas forcément indispensable, ca dépend de que que l'on veut faire de cette information). Puis il reste à l'imprimer dans la sortie série

on attend 5 secondes en ca recommence

Client Wifi / Server HTTP

#include <WiFi.h>
#include <WebServer.h>
//#include <ESPmDNS.h>

const char *ssid = "Your SSID";
const char *password = "P4sswOrd";

WebServer server(80);

void handleRoot() {
  String html = "<!DOCTYPE html>";
  html += "<html>\n";
  html += "<head>\n";
  html += "<title>Server ESP32</title>\n";
  html += "</head>\n";
  html += "<body>\n";
  html += "<h1>Hello world</h1>\n";
  html += "</body>\n";
  html += "</html>";
  server.send(200, "text/html", html);
}

void setup(void) {

  Serial.begin(115200);
  while (!Serial) continue;

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // URL esp32.local
  //if (MDNS.begin("esp32")) {
  //  Serial.println("MDNS responder started");
  //}

  server.on("/", handleRoot);

  server.onNotFound([]() {
    server.send(404, "text/plain", "Not Found");
  });

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void) {
  server.handleClient();
}

Hotspot

#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

/* Put your SSID & Password */
const char* ssid = "ESP32";  // Enter SSID here
const char* password = "12345678";  //Enter Password here

/* Put IP Address details */
IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

WebServer server(80);

void handleRoot() {
  String html = "<!DOCTYPE html>";
  html += "<html>\n";
  html += "<head>\n";
  html += "<title>Server ESP32</title>\n";
  html += "</head>\n";
  html += "<body>\n";
  html += "<h1>Hello world</h1>\n";
  html += "</body>\n";
  html += "</html>";
  server.send(200, "text/html", html);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

void setup() {
  Serial.begin(115200);

  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  delay(100);

  // URL esp32.local
  if (MDNS.begin("esp32")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}
void loop() {
  server.handleClient();
}