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

WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;

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

void setup() {
  pinMode(27, OUTPUT);
  digitalWrite(27, 0);
  WiFi.begin(ssid, password);
  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);
}

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

void publish(){
  int sensor = random(50);
  client.publish("proyekteknik/data", String(sensor));
}

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("hgyvtydyodgc3")){
    Serial.print(".");
    delay(500);
  }
  Serial.print("Terhubung ke Broker");
  client.subscribe("proyekteknik/#", 0);
}