/*
   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/

   &timezone=America/Sao_Paulo
   formatos: csv, xml, json e txt

   Read last entry in channel with HTTP GET

*/

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

// Substituir id_do_canal pelo número que identifica o canal - Channel ID.
// Substituir sua_chave_leitura pela chave de leitura do canal - Read API Key.
// 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";

HTTPClient cliente;

void setup() {

  Serial.begin(115200);
  while (!Serial)    {     }

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

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

  Serial.println("-----------------------------------------------");
  Serial.print("Endereco IP: ");
  Serial.println(WiFi.localIP());
  Serial.println("-----------------------------------------------");

  delay(1000);

}

void loop() {

  Serial.println("Requisicao: GET");

  cliente.begin(payload);

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

  Serial.print("Status: ");
  Serial.println(statusCode);
  Serial.print("Retorno: ");
  Serial.println(response);
  Serial.println();

  StaticJsonDocument<512> 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-02-12T16:31:19Z"
  int entry_id = doc["entry_id"]; // 11
  const char* field1 = doc["field1"]; // "2110"
  const char* field2 = doc["field2"]; // "685"
  const char* field3 = doc["field3"]; // "3943"
  const char* field4 = doc["field4"]; // "3415"

  Serial.print("Dispositivo : ");
  Serial.println("Objeto Virtual");
  Serial.println("-----------------------------");
  Serial.print("A0 : ");
  Serial.println(field1);
  Serial.print("A1 : ");
  Serial.println(field2);
  Serial.print("A2 : ");
  Serial.println(field3);
  Serial.print("A3 : ");
  Serial.println(field4);
  Serial.println("");

  delay(15000);

}