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

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

WiFiClient net;
MQTTClient client;
unsigned long lastMillis = 0;

int pot;

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

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

  Serial.println("\nconnected!");

  client.subscribe("esp32/belajar/#");
  // client.unsubscribe("/hello");
}

void pesanDiterima(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
if(topic == "esp32/belajar/led1"){
  digitalWrite(5, payload.toInt());

}

//   // Note: Do not use the client in the callback to publish, subscribe or
//   // unsubscribe as it may cause deadlocks when other things arrive while
//   // sending and receiving acknowledgments. Instead, change a global variable,
//   // or push to a queue and handle it in the loop after calling `client.loop()`.
 }

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

  // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
  // by Arduino. You need to set the IP address directly.
  client.begin("broker.emqx.io", net);
  client.onMessage(pesanDiterima);

  connect();
  pinMode(5, OUTPUT);
}

void loop() {
 
  client.loop();
  delay(10);  // <- fixes some issues with WiFi stability
  pot = analogRead(32);
  //Serial.println(pot);
  if (!client.connected()) {
    connect();
  }

  // publish a message roughly every second.
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    client.publish("belajar/iot",String (pot)); //data sensor
  }
}