import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "esp32-parking-system"
MQTT_BROKER = "test.mosquitto.org" # Using a reliable public broker
MQTT_PORT = 1883 # Standard MQTT port
MQTT_TOPIC = "parking/status"
# Define IR sensors on GPIO pins
ir_sensor_1 = Pin(15, Pin.IN)
ir_sensor_2 = Pin(23, Pin.IN)
ir_sensor_3 = Pin(16, Pin.IN)
# Threshold for detecting obstacle (1 = detected, 0 = vacant)
THRESHOLD = 1
def connect_to_wifi():
"""Connect to WiFi network."""
print("Connecting to WiFi...", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Open WiFi in Wokwi
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Connected! IP:", sta_if.ifconfig()[0])
def connect_to_mqtt():
"""Connect to the MQTT broker."""
while True:
try:
print("Connecting to MQTT broker...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT)
client.connect()
print("Connected to MQTT!")
return client
except Exception as e:
print("Failed to connect to MQTT:", e)
time.sleep(5) # Retry every 5 seconds
def get_parking_status(sensor):
"""Check if parking space is occupied or vacant."""
return "Occupied" if sensor.value() >= THRESHOLD else "Vacant"
# Connect to WiFi and MQTT
connect_to_wifi()
client = connect_to_mqtt()
# Store previous states to detect changes
prev_status = {"parking_space_1": "", "parking_space_2": "", "parking_space_3": ""}
while True:
print("Checking parking status...")
# Read sensor values and determine statuses
current_status = {
"parking_space_1": get_parking_status(ir_sensor_1),
"parking_space_2": get_parking_status(ir_sensor_2),
"parking_space_3": get_parking_status(ir_sensor_3),
}
# Publish if there is a change in status
if current_status != prev_status:
message = ujson.dumps(current_status)
print(f"Status changed! Publishing: {message}")
client.publish(MQTT_TOPIC, message)
prev_status = current_status # Update previous status
else:
print("No change in status.")
time.sleep(2) # Check every 2 seconds