esp32_client_resp_api_webserver
/* 
  Get the price of bitcoin from the Kraken API to an ESP32 platform and webserve it 
*/
 
#include <WiFi.h>
#include <HTTPClient.h>
#include <WebServer.h>
#include <ArduinoJson.h>
 
WebServer server(80);
 
void handleRoot() {
  server.send(200, "text/plain", "BTC");
}
 
void handleNotFound() {
  server.send(404, "text/plain", "File Not Found");
}
 
void setup() {
 
  Serial.begin(115200);
  while (!Serial) delay(100);
 
  WiFi.begin("ssid", "p4ssw0rd");
 
  Serial.print("Connecting to WiFi... ");
  while (WiFi.status() != WL_CONNECTED) delay(500);
  Serial.println("Ok.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
 
  server.on("/", handleRoot);
 
  server.onNotFound(handleNotFound);
 
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop() {
 
  /*
    freely inspired by:
    - BasicHTTPClient.ino from Espressif ESP32 Dev Module
    - https://arduinojson.org/v6/example/parser/
  */
 
  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");
    Serial.print("Send request... ");
 
    // start connection and send HTTP header
    int httpCode = http.GET();
 
    // httpCode will be negative on error
    if (httpCode > 0) {
 
      Serial.println(httpCode);
 
      // file found at server
      if (httpCode == HTTP_CODE_OK) {
        String response = http.getString();
        Serial.println(response);
 
        // Use arduinojson.org/v6/assistant to compute the capacity.
        //DynamicJsonDocument doc(2048);
        JsonDocument doc;
        DeserializationError error = deserializeJson(doc, response);
        if (error) {
          // F -> https://www.locoduino.org/spip.php?article131 [FR]
          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: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
  } else {
    Serial.println("Network unreachable");
  }
 
  server.handleClient();
  delay(5000);
}
esp32_client_resp_api_webserver.txt · Last modified: 2025/03/19 09:48 by bruno