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

const int pin_red = 27;
const int pin_green = 26;
const int pin_blue = 25;
const int pin_dht = 33;
const int pin_lampu = 14;

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

WiFiClient net;
MQTTClient client;
DHTesp dhtSensor;
NusabotSimpleTimer timer;
LiquidCrystal_I2C lcd(0x27, 16, 2);

void publishDHT(){
  String temp, humid;
  TempAndHumidity data = dhtSensor.getTempAndHumidity();
  temp = String(data.temperature);
  humid = String(data.humidity);

  client.publish("nusabot/suhu", temp, true, 1);
  client.publish("nusabot/kelembapan", humid, true, 1);
}

void subscribe(String &topic, String &data){
  if(topic == "nusabot/lampu"){
    if(data == "on"){
      digitalWrite(pin_lampu, 1);
    } else {
      digitalWrite(pin_lampu, 0);
    }
  }

  if(topic == "nusabot/textLCD"){
    lcd.clear();
    lcd.print(data);
  }
}

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

  while(!client.connect("clientID Unik")){ // CLIENT ID JANGAN SAMA
    delay(500);
  }
  rgb(0,0,1);
  client.subscribe("nusabot/#");
  client.publish("nusabot/12345A", "Terhubung", true, 1);
}

void setup() {
  pinMode(pin_red, OUTPUT);
  pinMode(pin_green, OUTPUT);
  pinMode(pin_blue, OUTPUT);
  pinMode(pin_lampu, OUTPUT);
  dhtSensor.setup(pin_dht, DHTesp::DHT22);
  lcd.init();
  lcd.backlight();

  timer.setInterval(2000, publishDHT);
  client.onMessage(subscribe);

  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net);
  client.setWill("nusabot/12345A", "Terputus", true, 1);
  connect();

  lcd.setCursor(0, 0);
}

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

void rgb(bool red, bool green, bool blue){
  digitalWrite(pin_red, red);
  digitalWrite(pin_green, green);
  digitalWrite(pin_blue, blue);
}
$abcdeabcde151015202530fghijfghij