/**
   ESP32 + DHT22 Example for Wokwi
   
   https://wokwi.com/arduino/projects/322410731508073042
*/
#include <WiFi.h>
#include "ThingSpeak.h"
#include <DHT.h>

#define DHTTYPE DHT22

const int DHT_PIN = 15;
const int LED_PIN = 13;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2568494;
const char* myApiKey = "2FAASIFFLK5MMJOK";
const char* server = "api.thingspeak.com";

DHT dhtSensor(DHT_PIN, DHTTYPE);
WiFiClient client;

void setup() { //
  Serial.begin(115200);
  //dhtSensor.setup(DHT_PIN, DHT::DHT22);
  pinMode(LED_PIN, OUTPUT);
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Wifi not connected");
  }
  Serial.println("Wifi connected !");
  Serial.println("Local IP: " + String(WiFi.localIP()));
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);
  Serial.println("Toshko Tzvetkov");
  Serial.println(String(__DATE__) + "\t" + String(__TIME__));
}

void loop() {
  //TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  float h = dhtSensor.readHumidity();
  float t = dhtSensor.readTemperature();
  ThingSpeak.setField(1,t);
  ThingSpeak.setField(2,h);
  if (t > 35 || t < 12 || h > 70 || h < 40) {
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
  
  int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);
  
  Serial.println("Temp: " + String(t, 2) + "°C");
  Serial.println("Humidity: " + String(h, 1) + "%");
  
  if(x == 200){
    Serial.println("Data pushed successfull");
  }else{
    Serial.println("Push error" + String(x));
  }
  Serial.println("---");

  delay(30000);
}