/*
   Código demonstrativo para a aula de Sistemas Embarcados,
   Curso de Ciência da Computação e Engenharia da Computação
   EEP.

   https://arduinojson.org/v6/assistant/

*/

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

// Substituir nome_dispositivo pelo nome do seu dispositivo.
// const String payload = "http://api.thingspeak.com/channels/id_do_canal/feeds/last.json?api_key=sua_chave_leitura";

const String payload = "http://api.thingspeak.com/channels/id_do_canal/feeds/last.json?api_key=sua_chave_leitura";

LiquidCrystal_I2C lcd(0x27, 16, 2);

HTTPClient cliente;

void setup() {

  WiFi.begin("Wokwi-GUEST", "");

  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print(" Escola de Eng. ");
  lcd.setCursor(0, 1);
  lcd.print(" de  Piracicaba ");

  delay(3000);

  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("    Sistemas    ");
  lcd.setCursor(0, 1);
  lcd.print("   Embarcados   ");

  delay(3000);

  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("   Exercicio    ");
  lcd.setCursor(0, 1);
  lcd.print("----------------");

  delay(3000);

}

void loop() {

  cliente.begin(payload);

  int statusCode = cliente.GET();
  String response = cliente.getString();

  StaticJsonDocument<192> doc;

  DeserializationError error = deserializeJson(doc, response);

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  const char* created_at = doc["created_at"]; // "2024-05-06T23:35:41Z"
  int entry_id = doc["entry_id"]; // 9
  const char* with_0_content_TempC = doc["field1"]; // "745"
  const char* with_0_content_TempF = doc["field2"]; // "60"
  const char* with_0_content_Cen = doc["field3"]; // "3487"
  const char* with_0_content_Pol = doc["field4"]; // "2001"

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temperatura (C) ");
  lcd.setCursor(0, 1);
  lcd.print(with_0_content_TempC);

  delay(3000);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Temperatura (F) ");
  lcd.setCursor(0, 1);
  lcd.print(with_0_content_TempF);

  delay(3000);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Distancia (Cm) ");
  lcd.setCursor(0, 1);
  lcd.print(with_0_content_Cen);

  delay(3000);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Distancia (Pol) ");
  lcd.setCursor(0, 1);
  lcd.print(with_0_content_Pol);

  delay(3000);

}