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

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

WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;

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

  // Menghubungkan ke Broker
  Serial.print("Menghubungkan ke Broker");
  while(!client.connect("bedaclientid")){ // Client ID tidak boleh sama
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.println("Berhasil Terhubung ke Server");
  
  client.subscribe("bpvp/iot/#", 1); // subcribe dengan QoS 1
}

void subscribeData(String &topic, String &data){
  if(topic == "bpvp/iot/led1"){
    digitalWrite(26, data.toInt());
  }

  if(topic == "bpvp/iot/led2"){
    digitalWrite(27, data.toInt());
  }

  if(topic == "bpvp/iot/led3"){
    digitalWrite(14, data.toInt());
  }
}

void publish1(){
  int pot1 = analogRead(33);
  client.publish("bpvp/iot/pot1", String(pot1), true, 1); // publish variabel pot1 ke topic bpvp/iot/pot1 dengan QoS 1
}

void publish2(){
  int pot2 = analogRead(32);
  client.publish("bpvp/iot/pot2", String(pot2), true, 1); // publish variabel pot2 ke topic bpvp/iot/pot1 dengan QoS 1
}

void setup() {
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(33, INPUT);
  pinMode(32, INPUT);
  Serial.begin(9600);
  WiFi.begin(ssid, pass);

  client.begin("broker.emqx.io", net);
  client.onMessage(subscribeData);
  timer.setInterval(1000, publish1);
  timer.setInterval(1000, publish2); 

  connect();
}

void loop() {
  client.loop();
  timer.run();

  delay(10);
}