#include <PubSubClient.h>
#include <WiFi.h>
#include "DHTesp.h"
#include <ESP32Servo.h>

Servo myservo;

const char* mqttServer    = "armadillo.rmq.cloudamqp.com";
const int mqttPort        = 1883;
const char* mqttUser      = "qodzxomh:qodzxomh";
const char* mqttPassword  = "OrRU5nkIkEjZ7lUmyQp_yEhT4uuofkmq";

WiFiClient espClient;
PubSubClient client(espClient);

const int ledg    = 13;
const int ledy    = 12;
const int ledr    = 14;
const int DHT_PIN = 27;
const int LDR     = 26;

DHTesp dhtSensor;

int stattopic,statlampu,statpintu;
 
void setup() 
{
 
  Serial.begin(115200); 

  pinMode(ledg, OUTPUT); 
  pinMode(ledy, OUTPUT); 
  pinMode(ledr, OUTPUT);

  pinMode(LDR,  INPUT);

  myservo.attach(25);

  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
 
  WiFi.begin("Wokwi-GUEST", "", 6);
 
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) 
  {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP8266Client", mqttUser, mqttPassword )) 
    {
      Serial.println("connected");  
    } else
     {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
  // client.publish("esp/test", "hello aku udin"); //Topic name
  stattopic = client.subscribe("esp/Lampu");
  statpintu = client.subscribe("esp/Pintu");
}
 
void callback(char* topic, byte* payload, unsigned int length) 
{
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) 
  {
    stattopic = (char)payload[i];
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------");
}
 
void loop() 
{
  
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  // Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  // Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  // Serial.println("---");

  if (digitalRead(LDR) == LOW) 
  {
    client.publish("esp/Cahaya", "Terang");
  } 
  if (digitalRead(LDR) == HIGH)
  {
    client.publish("esp/Cahaya", "Gelap");
  }

  //Serial.println(stattopic);
  if (stattopic == 48) 
  {
    digitalWrite(ledg, 0);
    client.publish("esp/Statlampu", "Mati");
  } 
  if (stattopic == 49)
  {
    digitalWrite(ledg, 1);
    client.publish("esp/Statlampu", "Nyala");
  }

  if (stattopic == 52) 
  {
    digitalWrite(ledy, 0);
    myservo.write(0);
    client.publish("esp/Statpintu", "Kunci");
  } 
  if (stattopic == 51)
  {
    digitalWrite(ledy, 1);
    myservo.write(90);
    client.publish("esp/Statpintu", "Buka");
  }
  
  delay(1);

  

  client.publish("esp/Temperatur", String(data.temperature).c_str(), true);
  client.publish("esp/Humidity", String(data.humidity).c_str(), true);
  client.loop();
  
}