#include <WiFi.h>
#include <MQTT.h>

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";

WiFiClient net;
MQTTClient client;

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("pqrstuvqxyz")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");
  client.publish("nusabot/serial_number/pqrstuvqxyz", "Online", true, 1);
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);

  client.begin("broker.emqx.io", net);

  client.setWill("nusabot/serial_number/pqrstuvqxyz", "Offline", true, 1);
  connect();
}

void loop() {
  if (!client.connected()) {
    connect();
  }
  delay(10);  // Khusus di simulator agar kerja simulasi tidak berat
}