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

WiFiClient net;
MQTTClient client;
NusabotSimpleTimer timer;
DHTesp dhtSensor;

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

// Nomor pin GPIO
const int pinRed = 2;
const int pinGreen = 4;
const int pinBlue = 16;
const int pinDHT = 25;

void setup() {
  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  dhtSensor.setup(pinDHT, DHTesp::DHT22);
  
  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net);

  timer.setInterval(2000, publishDHT);

  connect();
}

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

  delay(10);
}

void publishDHT(){
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();

  client.publish("ucic/suhu", String(data.temperature, 2), true, 1);
  client.publish("ucic/kelembaban", String(data.humidity, 1), true, 1);
}

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("clientid-unik", "kelasiot", "vwt5TSCSrqqSuqPR")){
    delay(500);
  }
  rgb(0,0,1); // Biru
}
$abcdeabcde151015202530fghijfghij