#include <WiFi.h>
#include <ThingsBoard.h>

#define		trigpin		4
#define		echopin		2

float duration;  
float distance;
float water;

#define WIFI_AP "Wokwi-GUEST"
#define WIFI_PASS ""

#define TB_SERVER "thingsboard.cloud" 
#define TOKEN "jntz26sdwr6awkqszkti"


WiFiClient espClient;
ThingsBoard tb(espClient);

void setup()
{
  Serial.begin(9600);
  pinMode(trigpin, OUTPUT);
  pinMode(echopin, INPUT);
  initWifi();
}

void loop()
{
  if(WiFi.status() !=  WL_CONNECTED){
	initWifi();
  }

  digitalWrite(trigpin, LOW);
  delayMicroseconds(6);
  
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigpin, LOW);
  
  
  duration = pulseIn(echopin, HIGH);
  distance = (duration/ 59);
  
  Serial.print(" Distance = ");
  Serial.print(distance);
  Serial.println (" cm");

  if(!tb.connected()){
    Serial.println("Connect to server");
    if(!tb.connect(TB_SERVER, TOKEN)){
      Serial.println("Failed. Try again..");
      return;
      
      
    }
  }
  else{
    Serial.println("Connected...");
  }


tb.sendTelemetryFloat("Ultrasonic data = ", distance);
Serial.println("Sending data");

delay(1000);

tb.loop();


}

void initWifi(){
Serial.println("Connect WiFi");
WiFi.begin(WIFI_AP, WIFI_PASS, 4);
  while(WiFi.status() != WL_CONNECTED){

    Serial.print(".");
    delay(500);
    }

Serial.println("CONNECTED");
}

    


  
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
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
ntc1:GND
ntc1:VCC
ntc1:OUT