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

WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;

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

int pot;

void setup() {
  pinMode(27, OUTPUT);
  pinMode(26, INPUT);

  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net);
  Serial.begin(9600);

  client.onMessage(subscribe);
  timer.setInterval(1000, publish);

  connect();
}

void loop() {
  client.loop();
  timer.run();
  if(!client.connected()){
    connect();
  }
  delay(10); // this speeds up the simulation
}

void subscribe(String &topic, String &data){
  if(topic == "kelasiot/led"){
    if(data == "nyala"){
      digitalWrite(27, 1);
    } else {
      digitalWrite(27, 0);
    }
  }
}

void publish(){
  pot = analogRead(26);
  client.publish("kelasiot/data", String(pot));
}

void connect(){
  Serial.print("Menghubungkan ke WiFi");
  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.println("Berhasil terhubung ke WiFi!");

  Serial.print("Menghubungkan ke Broker");
  while(!client.connect("iniunikxxxxxxx")){
    Serial.print(".");
    delay(500);
  }
  Serial.println("Berhasil terhubung ke Broker");
  client.subscribe("kelasiot/#", 1);
}