/**
   ESP32 + ThingSpeak + AppInventor Example for Wokwi
   
   https://wokwi.com/projects/397905228576420865
*/

// Incluir as bibliotecas...
#include  <WiFi.h>
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros

// Configuração de parâmetros do WiFi
char ssid[] = "Wokwi-GUEST";
char pass[] =  "1234567890abc";
int keyIndex = 0;
WiFiClient  client;

// Declarar o ID do canal
unsigned long channel = 1353120;
unsigned int campo = 3;

// Definição de pinos
#define pinLed 4

//Prototipo de funções
void reconectWiFi();
void leituraCanalThingSpeak();

//Função de Setup
void setup() {
  Serial.begin(115200);
  
  pinMode(pinLed, OUTPUT);
  digitalWrite(pinLed, 0);
  
  WiFi.mode(WIFI_STA);   
  
  ThingSpeak.begin(client);  // Initialize ThingSpeak
  
  //WiFi.begin(ssid, pass);
   
  WiFi.begin("Wokwi-GUEST", "", 6);
  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print("Tentando conectar-se ao SSID WPA: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.println("Você está conectado à rede");
  //printCurrentNet();
  //printWifiData();
}

// Função principal do programa
void loop() {
  reconectWiFi();
  leituraCanalThingSpeak();
    
}


// Funções....
void reconectWiFi(){
  // Connect or reconnect to WiFi
  if(WiFi.status() != WL_CONNECTED){
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    while(WiFi.status() != WL_CONNECTED){
      WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network
      Serial.print(".");
      delay(5000);     
    } 
    Serial.println("\nConnected.");
  }
}

void leituraCanalThingSpeak(){
//Configuração do estado do led
  int led_1 = ThingSpeak.readFloatField(channel, campo);
  if(led_1 == 1){
    digitalWrite(pinLed, 1);
    Serial.println("led ligado..!");
  }
  else if(led_1 == 0){
    digitalWrite(pinLed, 0);
    Serial.println("led desligado..!");
  }
    
  Serial.println(led_1);
  delay(5000);

}