ESP32 – JsonParsing

Table of Contents

Links

Some testing with ArduinoJson.h

All Code is tested with a ESP32C3!

Starter Code Still in Progress

				
					// https://arduinojson.org/v6/api/json/

#include "ArduinoJson.h"

unsigned int valueJson = 0;
String jsonStart = "{\"SensorType\": \"Temperature\", \"Value\": ";
String jsonEnding = "}";

void setup() {
  Serial.begin(115200);
  Serial.println();
  delay(10);
  Serial.println(F("__________________________________________"));
  Serial.println(F(""));
  Serial.println(F("  _  _ __   v0.1   __     _      _ "));
  Serial.println(F(" | || |\\ \\        / /    | |    (_)"));
  Serial.println(F(" | || |_\\ \\  /\\  / /___  | |__   _ "));
  Serial.println(F(" |__   _|\\ \\/  \\/ // _ \\ | '_ \\ | |"));
  Serial.println(F("    | |   \\  /\\  /| (_) || |_) || |"));
  Serial.println(F("    |_|    \\/  \\/  \\___/ |_.__/ |_|"));
  Serial.println(F(""));
  Serial.println(F("__________________________________________"));
  Serial.println(F(""));
}

void loop() {
  // CREATE JSON MESSAGE
  char b[2];
  String str;
  str = jsonStart + String(valueJson) + jsonEnding;
  str.toCharArray(b, 2);
  valueJson += 1;

  StaticJsonDocument<300> parsed;
  DeserializationError err = deserializeJson(parsed, str);  // CHANGE JSONMessage to "!!NOT JSON!!" for err
  if (err) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(err.c_str());
    delay(5000);
    return;
  }
  Serial.println("JsonObj");
  serializeJsonPretty(parsed, Serial);
  Serial.println();

  const char * sensorType = parsed["SensorType"];
  int value = parsed["Value"];

  printTypeVal(sensorType, value);

  delay(1000);
}

void printTypeVal(const char *type, int val) {
  Serial.println("Parsed");
  Serial.print("Sensor type: ");
  Serial.println(type);
  Serial.print("Sensor value: ");
  Serial.println(val);
  Serial.println();
}
				
			
				
					#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiManager.h>

const String endpoint = "https://api.openweathermap.org/data/2.5/onecall?lat=47.506904&lon=7.732428&exclude=alerts,minutely,daily,hourly&appid=";
const String key = "YOURKEY";
const String unitsSystem = "&units=metric";

void setup() {
  Serial.begin(115200);
  while (!Serial) continue;

  WiFi.mode(WIFI_STA);
  WiFiManager wm;

  // wm.resetSettings();

  bool res;
  res = wm.autoConnect("AutoConnectAP", "password"); // password protected ap
  if (!res) {
    Serial.println("Failed to connect");
    // ESP.restart();
  }
  else {
    Serial.println("connected...yeey :)");
  }
}

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

    HTTPClient http;

    http.begin(endpoint + key + unitsSystem);
    int httpCode = http.GET();
    if (httpCode > 0) {
      // String payload = http.getString();
      // const size_t capacity = JSON_ARRAY_SIZE(5) + 5 * JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + 200;
      // DynamicJsonDocument doc(capacity);

      StaticJsonDocument<512> doc;
      DeserializationError err = deserializeJson(doc, http.getStream() );
      if (err) {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(err.f_str());
      }
      serializeJsonPretty(doc, Serial);
      Serial.println();

      float lat = doc["lat"]; // 47.5069
      float lon = doc["lon"]; // 7.7324
      const char* timezone = doc["timezone"]; // "Europe/Zurich"
      int timezone_offset = doc["timezone_offset"]; // 7200

      JsonObject current = doc["current"];
      long current_dt = current["dt"]; // 1650728898
      long current_sunrise = current["sunrise"]; // 1650687959
      long current_sunset = current["sunset"]; // 1650738510
      float current_temp = current["temp"]; // 15.01
      float current_feels_like = current["feels_like"]; // 14.13
      int current_pressure = current["pressure"]; // 990
      int current_humidity = current["humidity"]; // 60
      float current_dew_point = current["dew_point"]; // 7.32
      float current_uvi = current["uvi"]; // 0.73
      int current_clouds = current["clouds"]; // 75
      int current_visibility = current["visibility"]; // 10000
      float current_wind_speed = current["wind_speed"]; // 5.14
      int current_wind_deg = current["wind_deg"]; // 350

      JsonObject current_weather_0 = current["weather"][0];
      int current_weather_0_id = current_weather_0["id"]; // 803
      const char* current_weather_0_main = current_weather_0["main"]; // "Clouds"
      const char* current_weather_0_description = current_weather_0["description"]; // "broken clouds"
      const char* current_weather_0_icon = current_weather_0["icon"]; // "04d"
      Serial.print("TheTemp: ");
      Serial.print(current_temp);
      Serial.println(" °C");

      Serial.println(doc["lat"].as<float>());
      
    }
    else {
      Serial.println("Error on HTTP request");
    }
    http.end();
  }
  delay(120000);
}
				
			

Leave a Comment