#include <WiFi.h>
#include <PubSubClient.h>

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

WiFiClient espClient;
PubSubClient client(espClient);

const char* relayTopic = "roomone";
int relayPins[] = {2, 3, 4, 5};
int numRelays = 4;

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

  for (int i = 0; i < numRelays; i++) {
    pinMode(relayPins[i], OUTPUT);
  }
}

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

void callback(char* topic, byte* payload, unsigned int length) {
  String relayCommand = String(payload[0]);
  int relayNum = relayCommand.toInt();

  if (relayNum >= 1 && relayNum <= numRelays) {
    digitalWrite(relayPins[relayNum - 1], !digitalRead(relayPins[relayNum - 1]));
    Serial.print("Toggled Relay ");
    Serial.println(relayNum);
  }
}

void setupWiFi() {
  delay(10);
  Serial.println("\nConnecting to WiFi");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");
}

void reconnect() {
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    if (client.connect("ESP32Client","HomeS","serverone")) {
      Serial.println("Connected to MQTT");
      client.subscribe(relayTopic);
    } else {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println(" Trying again in 5 seconds...");
      delay(5000);
    }
  }
}