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

// Ultrasonic Sensor Pins
const int trigPin = 5;
const int echoPin = 18;

// LED Pin
const int ledPin = 2;

// MQTT Broker details
const char* mqtt_server = "broker.emqx.io"; // Public MQTT broker for testing
const char* topic = "smartparking/slot1";

// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Variables for distance measurement
long duration;
int distance;

// Timer for blinking
unsigned long previousMillis = 0;
const long interval = 500; // Blink interval in milliseconds
bool ledState = HIGH; // LED state for blinking

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  
  // Initialize sensor and LED pins
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to Wi-Fi...");
  }
  Serial.println("Connected to Wokwi Wi-Fi!");

  // Initialize MQTT
  client.setServer(mqtt_server, 1883);
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    if (client.connect("ESP32Client")) {
      Serial.println("Connected to MQTT Broker!");
    } else {
      Serial.print("Failed MQTT Connection, rc=");
      Serial.print(client.state());
      delay(2000);
    }
  }
}

void loop() {
  // Trigger the ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the duration of the echo pulse
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance in centimeters
  distance = duration * 0.034 / 2;

  // Print the distance
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Parking Slot Logic
  String status;
  if (distance < 10) {
    // Slot occupied: LED OFF
    digitalWrite(ledPin, LOW);
    status = "Occupied";
    Serial.println("Slot Occupied");
  } else {
    // Slot available: LED BLINK
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      ledState = !ledState; // Toggle LED state
      digitalWrite(ledPin, ledState);
    }
    status = "Available";
    Serial.println("Slot Available");
  }

  // Publish status to MQTT
  // if (client.connected()) {
  //   client.publish(topic, status.c_str());
  // }
  if (client.connected()) {
  client.publish(topic, status.c_str());
  Serial.println("Published: " + status);
} else {
  Serial.println("MQTT not connected");
}


  delay(1000); // Adjust delay as needed
}