import network
import time
import urequests
from machine import Pin, ADC
import dht
from broker import *
import ujson
from umqttsimple import MQTTClient

LEDTemp = Pin(5, Pin.OUT)
LEDUmid = Pin(17, Pin.OUT)
dht_sensor = dht.DHT22(Pin(4))

def recebi(topico, msg):
    if msg.decode() == "ACENDE":
        LEDTemp.on()

    else:
        LEDTemp.off()


print("Conectando-se ao Wi-Fi", 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(1)
if sta_if.isconnected():
    print(" Wi-Fi conectado!")
    print("---")


    print("Conectando Broker MQTT...")
    
    client = MQTTClient(
        mqtt_client_id, 
        mqtt_server, 
        mqtt_port)
    client.connect()
    print("---")
    print("Conectado ao broker MQTT")

    client.publish("esp32/temperatura", "20")
    client.publish("esp32/umidade", "80")

    client.set_callback(recebi)
    client.subscribe("pucpr/iotmc/led")
    time.sleep(1)

    for i in range(3*60):
        dht_sensor.measure()
        temperatura = dht_sensor.temperature()
        client.publish(iotmc/temperatura, "20")
        print(temperatura)

   for i in range(3*60):
        dht_sensor.measure()
        umidade = str(dht_sensor.humidity())
        client.publish("pucpr/iotmc/msgnodered/umidade", umidade)
        print(umidade)
        time.sleep(1)