#include <PubSubClient.h>
#include <WiFi.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

const char* mqttServer = "your_mqtt_server";
const int mqttPort = 1883;
const char* mqttUsername = "your_mqtt_username";
const char* mqttPassword = "your_mqtt_password";

const char* deviceID = "your_device_id";
const char* authToken = "your_auth_token";
const char* topic = "your_topic";

const int trigPin = D1;
const int echoPin = D2;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }

  client.setServer(mqttServer, mqttPort);
}

void loop() {
  long duration;
  int distance;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 100) {
    if (!client.connected()) {
      reconnect();
    }
    
    char payload[10];
    snprintf(payload, sizeof(payload), "%d", distance);
    client.publish(topic, payload);
  }

  delay(500);
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect(deviceID, mqttUsername, mqttPassword)) {
      // Successful connection
    }
    else {
      delay(5000);
    }
  }
}