import network                      #wi-fi
import time                         #delay
from machine import Pin             #contrale portas esp32
import dht                          #sensor dht22
import ujson                        #Json
from umqtt.simple import MQTTClient #protocolo MQTT

# Publish - MQTT (Conexão com broker)
MQTT_CLIENT_ID = "Esp32_Temp_Umid"
MQTT_BROKER    = "mqtt.eclipseprojects.io" #broker
MQTT_USER      = "user"
MQTT_PASSWORD  = "123456"
MQTT_TOPIC     = "server-iot3"

sensor = dht.DHT22(Pin(15))

#import network (wi-fi)
print("Connecting to 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(" Connected!")

print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()

print("Connected!")

dados = ""
while True:
  print("Measuring weather conditions... ", end="")
  sensor.measure() 
  message = ujson.dumps([
    {
        "variable": "Temperatura",
        "value": sensor.temperature()
    },
    {
        "variable": "Umidade",
        "value": sensor.humidity()
    }
])
  if message != dados:
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
    client.publish(MQTT_TOPIC, message)
    dados = message
  else:
    print("No change")
  time.sleep(5)