#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 kirim(){
  pot = analogRead(27);
  client.publish("palopo/nama-masing/pot", String(pot));
}

void diterima(String &topic, String &data){
  if(topic == "palopo/nama-masing/lampu"){
    if(data == "on"){
      digitalWrite(26, 1);
    } else {
      digitalWrite(26, 0);
    }
  }
}

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

  pinMode(26, OUTPUT);
  pinMode(27, INPUT);

  client.onMessage(diterima);
  timer.setInterval(1000, kirim);

  connect();
}

void loop() {
  timer.run();
  client.loop();
  if(!client.connected()){
    connect();
  }

  delay(10);
}

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

  Serial.println("Menghubungkan ke Server");
  while(!client.connect("cvleruirvb")){ //client id tidak boleh sama
    Serial.println("menghubungkan ke Server");
  }
  Serial.println("Terhubung ke Server");
  client.subscribe("palopo/nama-masing/#");
}