JSON client - ESP32 - Arduino

martinius96
Posts: 16
Joined: Thu Dec 13, 2018 1:39 am

JSON client - ESP32 - Arduino

Postby martinius96 » Fri Jan 08, 2021 12:46 pm

Today I would like to post you there JSON client code for ESP32 microcontroller that I have used in my own Thermometer project based on WiFi platforms ESP8266 or ESP32: https://martinius96.github.io/WiFi-termostat/ that can distribute values of Hysteresis, Target temperature and Actual temperature from DS18B20 sensor at OneWire bus via JSON page that is hosted on webserver that is microcontroler running. It is really easy to use and helpful for many projects. For isntnace you can have in JSON string configuration for your microcontroller with system datas like: date, time, IP address, netmask, domain where to connect, etc...

JSON client (other ESP) can connected to thermostat via websocket (HTTP GET request) and download its JSON payload which can be deserialized and values parsed from it.

JSON payload (that server is sending in response) looks like:

Code: Select all

{
"Hysteresis":0.25,
"Target_Temperature":21.75,
"Actual_Temperature":21.43
}
JSON payload in Google Chrome window:
Image

Deserialization and parsing can be done via ArduinoJson library (i have used latest stable version 6.17.2).
As you can see at JSON output above, we will get values based on keys - "Hysteresis", "Target_Temperature" and "Actual_Temperature".

Full code (compatible for Thermostat project):

Code: Select all

/*|-------------------------------------------------|*/
/*|Projekt: JSON client - ESP32                     |*/
/*|Popis: Pripojenie k WiFi termostatu v LAN sieti  |*/
/*|stiahnutie JSON dat, vyparsovanie hodnot, vypis  |*/
/*|Autor: Martin Chlebovec                          |*/
/*|E-mail: martinius96@gmail.com                    |*/
/*|Revízia: 1. Januar 2021                          |*/
/*|-------------------------------------------------|*/

#include <WiFi.h>
#include <ArduinoJson.h>
const char* ssid = "MOJE SSID"; //SSID vasej WiFi siete
const char* password = "MOJE HESLO"; //HESLO vasej WiFi siete
const char* host = "192.168.1.XX"; //IP adresa WiFi termostatu
const int httpPort = 80;
WiFiClient client;
unsigned long timer = 0;
int interval = 15000;
void setup() {
  Serial.begin(115200); //rychlost seriovej linky
  Serial.println();
  Serial.print("Pripajanie na WiFi siet: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom
  while (WiFi.status() != WL_CONNECTED) { 
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wifi pripojene s IP:");
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  if ((millis() - timer) >= interval || timer == 0) {
    timer = millis();
    client.stop();
    if (client.connect(host, httpPort)) {
      String url = "/get_data.json";
      Serial.println("Pripojenie uspesne, nacitavam JSON data");
      client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: NodeMCU\r\n" + "Connection: close\r\n\r\n");
      while (client.connected()) {
        String line = client.readStringUntil('\n'); //HTTP HEADER
        //Serial.println(line);
        if (line == "\r") {
          break;
        }
      }
      DynamicJsonDocument doc(512);
      String line = client.readString(); //PAYLOAD
      Serial.println(line);
      deserializeJson(doc, line);
      JsonObject obj = doc.as<JsonObject>();
      float hystereza = obj[String("Hysteresis")];
      float cielova_teplota = obj[String("Target_Temperature")];
      float actual_temperature = obj[String("Actual_Temperature")];
      Serial.print("Hystereza: ");
      Serial.println(hystereza);
      Serial.print("Cielova teplota: ");
      Serial.println(cielova_teplota);
      Serial.print("Namerana (aktualna) teplota: ");
      Serial.println(actual_temperature);
    } else if (!client.connect(host, httpPort)) {
      Serial.println("Nepodarilo sa pripojenie k termostatu, ani nacitanie JSON data");
    }
  }
}
Output of JSON client
Image

Full code to parse Static string (EN language included):

Code: Select all

#include <ArduinoJson.h>
void setup() {
Serial.begin(115200);
Serial.println();
DynamicJsonDocument doc(512);
String line = "{\n";
line += F("\"Hysteresis\":");
line += F("0.25");
line += F(",\n");
line += F("\"Target_Temperature\":");
line += F("20.25");
line += F(",\n");
line += F("\"Actual_Temperature\":");
line += F("21.44");
line += F("\n");
line += F("}\n");
Serial.println(line);
deserializeJson(doc, line);
JsonObject obj = doc.as<JsonObject>();
float hystereza = obj[String("Hysteresis")];
float cielova_teplota = obj[String("Target_Temperature")];
float actual_temperature = obj[String("Actual_Temperature")];
Serial.print("Hysteresis from JSON: ");
Serial.println(hystereza);
Serial.print("Target temperature from JSON: ");
Serial.println(cielova_teplota);
Serial.print("Actual temperature from JSON: ");
Serial.println(actual_temperature);
}
void loop() {
}

Who is online

Users browsing this forum: No registered users and 5 guests