#include <WiFi.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include "ThingsBoard.h"
#include "DHTesp.h"

#define pinEcho 12
#define pinTrig 13
#define pinDHT 15

#define CURRENT_FIRMWARE_TITLE "TEST"
#define CURRENT_FIRMWARE_VERSION "1.0.0"

const char* ssid = "Wokwi-GUEST";
const char*  password =  "";

const char* mqtt_server = "thingsboard.cloud";
const char*  tokenTB =  "M5wyprYhcRrkXfGerINO";
const char*  pwdTB =  "";
const char*  topicTB =  "v1/devices/me/telemetry";


#define SERIAL_DEBUG_BAUD 9600

DHTesp dhtSensor;
WiFiClient espClient;
ThingsBoard tb(espClient);
PubSubClient client(espClient);
DynamicJsonDocument dataEncode(1024);

int status = WL_IDLE_STATUS;

unsigned long lastMsg = 0;

float readDistanceCM(){
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(2);

  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrig, LOW);

  int duration = pulseIn(pinEcho,HIGH);
  return duration * 0.0344/2;
}

void setup_wifi(){
 delay(10);
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Wifi Connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect(){
  while(!client.connected()){
    Serial.print("Attemping MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff),HEX);
    if(client.connect(clientId.c_str(), tokenTB, pwdTB)){
      Serial.println("Connected");
      TempAndHumidity  data = dhtSensor.getTempAndHumidity();
      dataEncode["suhu"] = data.temperature;
      dataEncode["kelembapan"] = data.humidity;
      dataEncode["jarak"] = readDistanceCM();

      char buffer[256];
      size_t n = serializeJson(dataEncode, buffer);
      client.publish(topicTB, buffer, n);
    }else{
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println("try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  setup_wifi();
  pinMode(pinTrig, OUTPUT);
  pinMode(pinEcho, INPUT);
  dhtSensor.setup(pinDHT, DHTesp::DHT22);
  client.setServer(mqtt_server, 1883);
}

void loop() {
  delay(1000);
  if(!client.connected()){
      reconnect();
    }
    client.loop();
unsigned long now = millis();
if(now - lastMsg > 2000){
  lastMsg= now;
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
      dataEncode["suhu"] = data.temperature;
      dataEncode["kelembapan"] = data.humidity;
      dataEncode["jarak"] = readDistanceCM();

char buffer[256];
      size_t n = serializeJson(dataEncode, buffer);
      client.publish(topicTB,buffer,n);
}
  
}
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND