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

WiFiClient net;
MQTTClient client;

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
const char brokerName[] = "kelasiotdevan.cloud.shiftr.io";
const char usernameBroker[] = "kelasiotdevan";
const char passwordBroker[] = "w4TXjZVczSQ0DyiW";
const char clientID[] = "client-007";
const char topicMQTT[] = "kelasiot/espSatu/status";
const char subTopic[] = "kelasiot/#";

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

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

  WiFi.begin(ssid, pass);
  client.begin(brokerName, net);
  
  client.onMessage(subscribe);
  connect();  
}

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

  delay(1000);
}

void subscribe(String &topic, String &data) {
  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Subscribe Data: ");
  Serial.println(data);
  Serial.println();
}

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

  client.setWill(topicMQTT, "offline", true, 1);

  while (!client.connect(clientID, usernameBroker, passwordBroker)) {
    delay(500);
  }
  delay(1000);
  rgb(0,0,1); // Biru
  
  client.publish(topicMQTT, "online", true, 1);
  client.subscribe(subTopic, 1); // Subscribe dengan QoS 1
}
$abcdeabcde151015202530fghijfghij