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

WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
const char brokerName[] = "broker.emqx.io";
const char clientID[] = "client-004";
const char topicMQTT[] = "kelasiot/potentiometer";
const char subTopic[] = "kelasiot/#";

const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 16;
const int pinPot = 33;

int pot, oldPot = 0;

void setup() {
  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  pinMode(pinPot, INPUT);
  Serial.begin(9600);

  WiFi.begin(ssid, pass);
  client.begin(brokerName, net);
  
  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) {
  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Subscribe Data: ");
  Serial.println(data);
  Serial.println();
}

void publish(){
  pot = analogRead(pinPot);

  if (pot != oldPot) {
    client.publish(topicMQTT, String(pot), false, 1);
    oldPot = pot;
    Serial.println("Publish Data: "+String(pot));
  }
}

void rgb(bool red, bool green, bool blue) {
  digitalWrite(pinRed, red);
  digitalWrite(pinGreen, green);
  digitalWrite(pinBlue, blue);
}

void connect() {
  rgb(1,0,0); // Merah
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    rgb(1,0,0); rgb(0,1,0); // Kuning
  }
  delay(1000);
  rgb(0,1,0); // Hijau

  while (!client.connect(clientID)) {
    delay(500);
  }
  delay(1000);
  rgb(0,0,1); // Biru
  
  client.subscribe(subTopic, 1); // Subscribe dengan QoS 1
}
$abcdeabcde151015202530fghijfghij