// 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();
}