from wifi_lib import conecta
import urequests
from umqttsimple import MQTTClient
import time
from defs import *
from machine import Pin
from servo import Servo
import dht


d1 = dht.DHT22(Pin(2))
LED = Pin(5, Pin.OUT)
LED2 = Pin(25, Pin.OUT)
braco = Servo(16)

def recebi(topico, msg):
    if topico.decode() == "iotatp/vent":
        braco.set_angle(int(msg.decode()))
    elif topico.decode() == "iotatp/emergencia":
        if msg.decode() == "LIGA":
            LED2.on()
        else:
            LED2.off()

def lerSensor():
    d1.measure()
    temp = d1.temperature()
    hum = d1.humidity()
    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
      if hum > 70:
        LED.on()
      else:
        LED.off()
      
      if temp < 21:
        client.publish("iotatp/vent", "0")
      elif temp > 21 and temp < 30:
        client.publish("iotatp/vent", "90")
      else:
        client.publish("iotatp/vent", "180")
    

      temp = (b'{0:3.1f}'.format(temp))
      hum =  (b'{0:3.1f}'.format(hum))
      client.publish(topico_temperatura, temp)
      client.publish(topico_umidade, hum)
        
        


print("Conectando...")
station = conecta("Wokwi-GUEST","")
if not station.isconnected():
    print("Falha na conexão")
else:
    print("Conectado wifi")
    print("Conectando Broker MQTT")
    client = MQTTClient(mqtt_client_id,
        mqtt_server,
        mqtt_port,
        mqtt_user,
        mqtt_password)
    client.connect()
    client.set_callback(recebi)
    client.subscribe("iotatp/vent")
    client.subscribe("iotatp/emergencia")

    
    client.publish("iotatp/testes", "Funcionou!")
    
    while True:
        lerSensor()       
        client.sleep(3)

    

    #client.sleep(2)
    #client.publish("iotatp/testes", temp)
    #client.sleep(2)
    #client.publish("iotatp/testes", hum)

    client.disconnect()
    station.disconnect()