#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include "ThingsBoard.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

#define WIFI_AP       "Wokwi-GUEST"
#define WIFI_PASSWORD ""

#define TOKEN               "hDuUMv9UPnbpvT6Jeo2y"
#define THINGSBOARD_SERVER  "thingsboard.cloud"

#define SERIAL_DEBUG_BAUD 115200


#define led 2
#define echo 12
#define trig 13


WiFiClient espClient;
ThingsBoard tb(espClient);

int status = WL_IDLE_STATUS;

void setup() {
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(SERIAL_DEBUG_BAUD);
  WiFi.begin(WIFI_AP, WIFI_PASSWORD);
  initWiFi();
}

float readDistanceCM() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  int duration = pulseIn(echo, HIGH);
  return duration * 0.034 / 2;
}

void loop() {
  delay(1000);

  float distance = readDistanceCM();

  if (distance >= 400 || distance <= 2){
    distance = 0;
  }


  if (distance<200) {
  digitalWrite(led, HIGH);
  delay(500);
  digitalWrite(led, LOW);
  delay(500);
  } else {
  digitalWrite(led, LOW);
  }
  
  if(WiFi.status() != WL_CONNECTED) {
    reconnect();
  }

  if(!tb.connected()) {
    Serial.print("Connecting to : ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.print(TOKEN);
    if(!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
      Serial.println("Failed to connect");
      return;
    }
  }

  Serial.println("Sending data...");
  Serial.print("Distance : ");
  Serial.println(distance);

  tb.sendTelemetryFloat("Jarak", distance);
  tb.loop();
}

void initWiFi()
{
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_AP, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  // Loop until we're reconnected
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    WiFi.begin(WIFI_AP, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}