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

# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "TestWater"
MQTT_PASSWORD = "testwaterpassword"
MQTT_TOPIC1 = "discente/joao_emanuel/sensor/DHT22/variavel/humidity"
MQTT_TOPIC2 = "discente/joao_emanuel/sensor/DHT22/variavel/temperature"

dht22 = dht.DHT22(Pin(13))

pastHumidityValue = 0
pastTemperatureValue = 0

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!")

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:
    dht22.measure()
    humidityValue = dht22.humidity()
    temperatureValue = dht22.temperature()

    if(humidityValue != pastHumidityValue):
        pastHumidityValue = humidityValue
        message1 = ujson.dumps({"Humidade": humidityValue})
        client.publish(MQTT_TOPIC1, message1)
    
    if(temperatureValue != pastTemperatureValue):
        pastTemperatureValue = temperatureValue
        message2 = ujson.dumps({"Temperatura": temperatureValue})
        client.publish(MQTT_TOPIC2, message2)

    time.sleep(1)