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

#define DHT_PIN 7    // Pin DHT22
#define RELAY_PIN 5  // Pin relay untuk mist maker

const char ssid[] = "@NUSABOTID";
const char pass[] = "terserah";

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

float humidThres = 0;
bool mode = true;

void connect() {
  Serial.print("Menghubungkan ke WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("Terhubung ke WiFi");
  Serial.print("\nMenghubungkan ke Server");
  while (!client.connect("smart-fungi")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("Terhubung ke Server");

  client.subscribe("jamur/#");
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600);
  WiFi.begin(ssid, pass);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  client.begin("broker.emqx.io", net);
  client.onMessage(messageReceived);
  timer.setInterval(2000, publish);

  connect();
}

void loop() {
  timer.run();
  client.loop();

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

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);

  if(topic == "jamur/relay"){
    if(payload == "on"){
      digitalWrite(RELAY_PIN, 1);
    } else {
      digitalWrite(RELAY_PIN, 0);
    }
  }

  if(topic == "jamur/minThres"){
    humidThres = payload.toFloat();
  }

  if(topic == "jamur/mode"){
    if(payload == "automatic"){
      mode = true;
    } else {
      mode = false;
    }
  }
}

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

  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");

  client.publish("jamur/temp", String(data.temperature, 2), true, 1);
  client.publish("jamur/humid", String(data.humidity, 1), true, 1);

  if(mode == true){
    if(data.temperature < humidThres){
      digitalWrite(RELAY_PIN, 1);
    } else {
      digitalWrite(RELAY_PIN, 0);
    }
  }
}