from machine import Pin, I2C
import time
from hcsr04 import HCSR04
from umqtt.simple import MQTTClient
import network

# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# MQTT broker details
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_CLIENT_ID = "clientId-vBpeNeenHSr"
MQTT_TOPIC = "distance-sensor"

# Ultrasonic Sensor setup
sensor = HCSR04(trigger_pin=25, echo_pin=26)

# Connect to WiFi
def connect_to_wifi():
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    if not wifi.isconnected():
        print('Connecting to WiFi...')
        wifi.connect(WIFI_SSID, WIFI_PASSWORD)
        while not wifi.isconnected():
            pass
    print('WiFi connected:', wifi.ifconfig())

# Send data to MQTT broker
def send_to_mqtt(distance):
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
    client.connect()
    client.publish(MQTT_TOPIC, str(distance))
    client.disconnect()

def measure_distance():
    distance = sensor.distance_cm()
    return distance

def main():
    connect_to_wifi()
    while True:
        distance = measure_distance()
        print('Distance:', distance, 'cm')
        send_to_mqtt(distance)
        time.sleep(5)

if __name__ == "__main__":
    main()