// Publisher 
#include <WiFi.h>
#include <PubSubClient.h>     // Library untuk mengkoneksikan ESP32 ke MQTT broker
#include <DHT.h>              // Library DHT

#define DHTPIN 22             // Pin DHT
#define DHTTYPE DHT22         // Type DHT

DHT dht(DHTPIN, DHTTYPE);     // Membuat DHT objek disebut "dht"pada pin dan dengan jenis sensor DHT

WiFiClient wifiClient;                // Membuat objek wifiClient
PubSubClient mqttClient(wifiClient);  // Membuat  objek mqttClient dengan konstruktor objek WiFiClient (Permintaan dari Lib)

const char* ssid = "Wokwi-GUEST";
const char* password = "";

char *mqttServer = "broker.mqttdashboard.com";
int mqttPort = 1883;

int Bbutton = 4; //Menghidupkan Pompa
int Mbutton = 5; //Menghidupkan Lampu
int Hbutton = 18; //Untuk Mode Otomatis

void setupMQTT() {
  mqttClient.setServer(mqttServer, mqttPort); // Mengatur detail broker target  yang digunakan
  mqttClient.setCallback(callback);           // jika kita ingin menerima pesan untuk langganan yang dibuat oleh klien
}

// ESP32 Reconnect to broker
void reconnect() {
  Serial.println("Connecting to MQTT Broker...");
  while (!mqttClient.connected()) {
      Serial.println("Reconnecting to MQTT Broker..");
      String clientId = "ESP32Client-";
      clientId += String(random(0xffff), HEX);
      
      if (mqttClient.connect(clientId.c_str())) {
        Serial.println("Connected.");
      }      
  }
}


void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Callback - ");
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
  }
}


void setup() {
  Serial.begin(115200);

  dht.begin();  // Deklarasi DHT
  WiFi.begin(ssid, password);   // Mencoba connect ke Wifi

  pinMode(Bbutton, INPUT);
  pinMode(Mbutton, INPUT);
  pinMode(Hbutton, INPUT);

  // Melakukan pengecekan terhadap status koneksi ke WI-Fi
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    } 
    Serial.println("");
    Serial.println("Connected to Wi-Fi");

  setupMQTT(); // setup koneksi ke broker
}


void loop() {
  //Memastikan koneksi ke MQTT
  if (!mqttClient.connected()){
    reconnect();   // Try to connect with broker
  }
  else {
    float temperature = dht.readTemperature();
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);  //Convert float to String
    Serial.print("Temperature: ");
    Serial.println(tempString);
    mqttClient.publish("Latihanmqtt1/permanalingga1/Suhu", tempString);
  
    float humidity = dht.readHumidity();;
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    mqttClient.publish("Latihanmqtt1/permanalingga1/kelembapan", humString);

    /*float humidity = dht.readHumidity();;
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    mqttClient.publish("Latihanmqtt1/permanalingga1/Suhukelembapan", humString);
    */
    delay(2000);

  }

}

/*void readsensor(){
    Bbutton1 = digitalRead(Bbutton);
    Mbutton1 = digitalRead(Mbutton);
    Hbutton1 = digitalRead(Hbutton);
}*/