#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with your network credentials
const char* ssid = "Dispenduk Kecamatan Balung";
const char* password = "iyainaja";

// Update the MQTT server to your broker's address
const char* mqtt_server = "192.168.43.27";

WiFiClient espClient;
PubSubClient client(espClient);

const int relayPin = D1; // GPIO5 pada D1 Mini

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW); // Matikan relay pada awal
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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

  if (String(topic) == "home/switch/status") {
    if (message == "Off") {
      digitalWrite(relayPin, LOW); // Hidupkan relay
      Serial.println("Relay turned Off");
    } else if (message == "On") {
      digitalWrite(relayPin, HIGH); // Matikan relay
      Serial.println("Relay turned On");
    } else {
      Serial.println("Invalid message");
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("home/switch/status");
      Serial.println("Subscribed to home/switch/status");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
