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

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

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

void rgb(bool red, bool green, bool blue){
  digitalWrite(25, red);
  digitalWrite(26, green);
  digitalWrite(27, blue);
}

void setup() {
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  dhtSensor.setup(15, DHTesp::DHT22);
  servo.attach(18, 500, 2400);

  WiFi.begin(ssid, pass);
  client.begin("broker.emqx.io", net);
  lcd.init();
  lcd.backlight();

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

  connect();
}

void loop() {
  timer.run();
  client.loop();
  delay(10);
}

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


  client.setWill("nusabot/276899", "Offline", true, 1);

  //Broker
  while (!client.connect("276899")) {
    delay(500);
  }
  rgb(0,0,1);
  client.subscribe("nusabot/#");
  client.publish("nusabot/276899", "Online", true, 1);
}

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

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

void subscribe(String &topic, String &data){
  if(topic == "nusabot/servo"){
    servo.write(data.toInt());
  }
  if(topic == "nusabot/lcd"){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(data);
  }
}