// DHT Temperature & Humidity Sensor
// Unified Sensor Library Example
// Written by Tony DiCola for Adafruit Industries
// Released under an MIT license.

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include <Arduino.h>
#include "DHTesp.h"
#include <WiFi.h>
#include <EspMQTTClient.h>
#include "ThingSpeak.h"

#define SECRET_MQTT_USERNAME "JxIgDhkeDA0yLCoeATQHBAs"
#define SECRET_MQTT_CLIENT_ID "JxIgDhkeDA0yLCoeATQHBAs"
#define SECRET_MQTT_PASSWORD "/YXK1S00wj6wNAfrywYqUDGe"

#define SECRET_WIFI_NAME "Wokwi-GUEST"           // YOUR_WIFI_NAME
#define SECRET_WIFI_PASSWORD ""   // YOUR_WIFI_PASSWORD
#define CHANNEL_ID "2388350"                // YOUR_CHANNEL_ID

EspMQTTClient client(
  SECRET_WIFI_NAME,
  SECRET_WIFI_PASSWORD,
  "mqtt3.thingspeak.com",
  SECRET_MQTT_USERNAME,
  SECRET_MQTT_PASSWORD,
  SECRET_MQTT_CLIENT_ID
);

const int DHT_PIN = 15;

unsigned long lastTime = 0;
unsigned long delayTime = 10000; // set a period of sending data.

DHTesp dhtSensor;
// // WiFiClient client;

void setup() {
  Serial.begin(921600);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT11);
}

void onConnectionEstablished() {
  Serial.println("MQTT Client is connected to Thingspeak!");
}

void publishData(){
  if (client.isConnected() && (millis() - lastTime > delayTime)){
    TempAndHumidity data = dhtSensor.getTempAndHumidity();
    float t = data.temperature;
    float h = data.humidity;
    if (isnan(h) || isnan(t)) {
      Serial.println(F("Failed to read from DHT sensor!"));
      return;
    }
    Serial.print(F("\nTemperature: "));
    Serial.print(t);
    Serial.print(F("°C "));
    Serial.print(F("Humidity: "));
    Serial.print(h);
    Serial.println(F("%  "));

    Serial.println(F("\nPublising data to Thingspeak"));
    
    String MY_TOPIC = "channels/" + String(CHANNEL_ID) + "/publish";  // build your topic: channels/<channelID>/publish
    String payload = "field1=" + String(t) + "&field2=" + String(h);  // build your payload: field1=<value1>&field2=<value2>
    client.publish(MY_TOPIC, payload);

    Serial.println("Data published");
    lastTime = millis();
  }
}

void loop() {
  client.loop();
  publishData();
} 
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
led1:A
led1:C