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

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


house = {
    "ultrassom": "0.2m",
    "pressure": "200hPa",
}


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:
        message = ujson.dumps({"Ultrassom": house["ultrassom"], "Pressure": house["pressure"]})
        client.publish(MQTT_HOUSE_TOPIC, message)
        time.sleep(3)

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

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