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

// Konfigurasi Wi-Fi
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Konfigurasi broker MQTT
const char* mqtt_server = "broker.emqx.io";  // Ganti dengan alamat broker EMQ X yang digunakan
const char* mqtt_topic = "LEDxComputerVision";

WiFiClient espClient;
PubSubClient client(espClient);

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

  // Koneksi ke Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Koneksi ke broker MQTT
  client.setServer(mqtt_server, 1883);

  // Callback ketika pesan diterima
  client.setCallback(callback);
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.println("Message arrived in topic: " + String(topic));

  // Proses pesan yang diterima di sini
  String message = "";
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  Serial.println("Message: " + message);
}

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

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