#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#endif

#include <WiFi.h>
#include "ThingsBoard.h"
#include <Adafruit_Sensor.h>
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701

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

#define WIFI_SSID    "Wokwi-GUEST"
#define WIFI_PASSWORD ""


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

#define SERIAL_DEBUG_BAUD 115200

WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;

const int trigPin = 5;
const int echoPin = 18;
long duration;
float distanceCm;
float distanceInch;
int distance;

void InitWiFi()
{
  Serial.println("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}
void reconnect(){
  status = WiFi.status();
  if (status !=WL_CONNECTED){
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() !=WL_CONNECTED){
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}

void setup(){
  Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
 pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  InitWiFi();
}

void loop(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance
  distanceCm = duration * SOUND_SPEED/2;
  // Prints the distance in the Serial Monitor
 Serial.print("Distance (cm):  ");
 Serial.println(distanceCm);

  delay(1000);
  if (WiFi.status() !=WL_CONNECTED){
    reconnect();
  }

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

  tb.loop();

  tb.loop();
}