from machine import Pin, ADC, time_pulse_us
import time
import network
import ujson
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID = "testwaterhouse1"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "TestWater"
MQTT_PASSWORD = "testwaterpassword"
MQTT_HOUSE_TOPIC = "neighborhood/1/house/1/sensor/ultrassom_and_pressure"

trig_pin = Pin(26, Pin.OUT)
echo_pin = Pin(27, Pin.IN)

house = {
    "ultrassom": "1m",
    "pressure": "1013.25hPa",
}


print("Conectando ao WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
print("Conectado!")


try:
    print("Conectando ao servidor MQTT... ", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()
    print("Conectado!")

    while True:
        message1 = ujson.dumps({"Ultrassom": house["ultrassom"], "Pressure": house["pressure"]})
        client.publish(MQTT_HOUSE_TOPIC, message1)
        time.sleep(3)

except Exception as e:
    print(f"Erro: {e} Aqui")

finally:
    if 'client' in locals():
        client.disconnect()