#include <WiFi.h>
#include <MQTT.h>
WiFiClient net;
MQTTClient client;
const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 15;
const int pinLED = 13;
void setup() {
  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  pinMode(pinLED, OUTPUT);
  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net );
  client.onMessage(subscribe);
  connect();
}
void loop() {
  client.loop();
  if (!client.connected()) {
    connect();
  }
}
void subscribe(String &topic, String &data ) {
  if ( topic == "kelasiot/led") {
    if (data == "on") {
      digitalWrite(pinLED, 1);
    } else if (data == "off") {
      digitalWrite(pinLED, 0);
    }
  }
}
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(0, 1, 0); //hijau
  while (!client.connect("b1bd726f")) {
    delay(500);
  }
  rgb(0, 0, 1);
  client.subscribe("kelasiot/#", 1); //Suscribe menggunakan QoS 1
}