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

// Substituir nome_dispositivo pelo nome do seu dispositivo.
const String payload = "http://dweet.io/get/latest/dweet/for/nome_dispositivo";

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* this_ = doc["this"]; // "succeeded"
  const char* by_ = doc["by"]; // "getting"
  const char* the_ = doc["the"]; // "dweets"

  JsonObject with_0 = doc["with"][0];
  const char* with_0_thing = with_0["thing"]; // "nome_dispositivo"
  const char* with_0_created = with_0["created"]; // "2022-11-16T13:25:09.710Z"

  JsonObject with_0_content = with_0["content"];
  int with_0_content_A0 = with_0_content["A0"]; // 1000
  int with_0_content_A1 = with_0_content["A1"]; // 2000
  int with_0_content_A2 = with_0_content["A2"]; // 3000
  int with_0_content_A3 = with_0_content["A3"]; // 4000

  Serial.print("Dispositivo : ");
  Serial.println(with_0_thing);
  Serial.println("-----------------------------");
  Serial.print("A0 : ");
  Serial.println(with_0_content_A0);
  Serial.print("A1 : ");
  Serial.println(with_0_content_A1);
  Serial.print("A2 : ");
  Serial.println(with_0_content_A2);
  Serial.print("A3 : ");
  Serial.println(with_0_content_A3);
  Serial.println("");
  
  delay(15000);

}