import time
import machine
import micropython
import network
import dht
import neopixel
from machine import Pin,PWM
from umqtt.simple import MQTTClient

ssid = 'Wokwi-GUEST'
wifipassword = ''
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'NahuuCava' 
password = 'aio_yKhl139zzzvkT8WCGDjAjVY8eJ6b' 
client_id = 'MiTP'
topic_SensorTEMP = 'NahuuCava/feeds/SensorTEMPDHT22'
topic_SensorHUM = 'NahuuCava/feeds/Sensorhumedad'
topic_RGB = 'NahuuCava/feeds/RGBLEDRING'
RGB_ACTIVO=False
LEDESTADO = Pin(17,Pin.OUT)

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("Conectando")
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print("Conectado a Wifi!")
print(sta_if.ifconfig())

def callback_DHT22(topic, msg):
    global RGB_ACTIVO,LEDESTADO
    dato = msg.decode('utf-8')
    topicrec = topic.decode('utf-8')
    print("Cambio en: "+topicrec+":"+dato)
    if topicrec == topic_RGB and "OFF" in dato:
        RGB_ACTIVO=False
    else:
        RGB_ACTIVO=True  
    LEDESTADO.value(RGB_ACTIVO)

try:
    conexionMQTT = MQTTClient(client_id, mqtt_server,user=user,password=password,port=int(port))
    conexionMQTT.set_callback(callback_DHT22)
    conexionMQTT.connect()
    conexionMQTT.subscribe(topic_RGB)
    print("Conectado con Broker MQTT")
except OSError as e:
    print("Fallo la conexion al Broker, reiniciando...")
    time.sleep(5)
    machine.reset()

sensor = dht.DHT22(Pin(13))
LEDsensor = Pin(12,Pin.OUT)
np = neopixel.NeoPixel(machine.Pin(5), 16)
#Leds en blanco
np[0] =(255, 255, 255) 
np[1] =(255, 255, 255) 
np[2] =(255, 255, 255) 
np[3] =(255, 255, 255) 
np[4] =(255, 255, 255) 
np[5] =(255, 255, 255) 
np[6] =(255, 255, 255) 
np[7] =(255, 255, 255) 
np[8] =(255, 255, 255) 
np[9] =(255, 255, 255) 
np[10] =(255, 255, 255) 
np[11] =(255, 255, 255) 
np[15] =(255, 255, 255) 
np[14] =(255, 255, 255)
np[13] =(255, 255, 255) 
np[12] =(255, 255, 255) 
np.write ()

print("Comenzando monitoreo de sensor")

while True:
    sensor.measure()
    temp = sensor.temperature()
    hum = sensor.humidity()
    
    try:
        conexionMQTT.check_msg()
        time.sleep_ms(500)
        LEDsensor.value(temp)
        if RGB_ACTIVO:
            if sensor.temperature() < 16:
                #Leds en celeste
                np[0] =(0, 255, 255) 
                np[1] =(0, 255, 255) 
                np[2] =(0, 255, 255) 
                np[3] =(0, 255, 255) 
                np[15] =(0, 255, 255)
                np[14] =(0, 255, 255) 
                np[13] =(0, 255, 255) 
                np[12] =(0, 255, 255) 
                np.write ()
              
            else:
                if sensor.temperature() > 28:
                    #Leds en rojo
                    np[0] =(255, 0, 0) 
                    np[1] =(255, 0, 0) 
                    np[2] =(255, 0, 0) 
                    np[3] =(255, 0, 0) 
                    np[15] =(255, 0, 0) 
                    np[14] =(255, 0, 0) 
                    np[13] =(255, 0, 0) 
                    np[12] =(255, 0, 0) 
                    np.write ()
                    
                else:
                    #Leds en amarillo
                    np[0] =(255, 255, 0) 
                    np[1] =(255, 255, 0) 
                    np[2] =(255, 255, 0)
                    np[3] =(255, 255, 0)
                    np[15] =(255, 255, 0)
                    np[14] =(255, 255, 0) 
                    np[13] =(255, 255, 0) 
                    np[12] =(255, 255, 0) 
                    np.write ()
        else:
            #Leds en negro
            np[0] =(0, 0, 0) 
            np[1] =(0, 0, 0) 
            np[2] =(0, 0, 0) 
            np[3] =(0, 0, 0) 
            np[15] =(0, 0, 0) 
            np[14] =(0, 0, 0) 
            np[13] =(0, 0, 0) 
            np[12] =(0, 0, 0) 
            np.write ()
        
        conexionMQTT.publish(topic_SensorTEMP,str(temp))

        if RGB_ACTIVO:
            if hum < 30:
               #Leds en celeste
               np[4] =(0, 255, 255) 
               np[5] =(0, 255, 255) 
               np[6] =(0, 255, 255) 
               np[7] =(0, 255, 255) 
               np[8] =(0, 255, 255)
               np[9] =(0, 255, 255) 
               np[10] =(0, 255, 255) 
               np[11] =(0, 255, 255) 
               np.write ()
              
            else:
                if hum > 60:
                    #Leds en rojo
                    np[4] =(255, 0, 0)
                    np[5] =(255, 0, 0) 
                    np[6] =(255, 0, 0) 
                    np[7] =(255, 0, 0) 
                    np[8] =(255, 0, 0) 
                    np[9] =(255, 0, 0) 
                    np[10] =(255, 0, 0) 
                    np[11] =(255, 0, 0) 
                    np.write ()        
                else:
                    #Leds en amarillo
                    np[4] =(255, 255, 0) 
                    np[5] =(255, 255, 0) 
                    np[6] =(255, 255, 0)
                    np[7] =(255, 255, 0)
                    np[8] =(255, 255, 0)
                    np[9] =(255, 255, 0) 
                    np[10] =(255, 255, 0) 
                    np[11] =(255, 255, 0) 
                    np.write ()
        else:
         #Leds en negro
            np[4] =(0, 0, 0) 
            np[5] =(0, 0, 0) 
            np[6] =(0, 0, 0) 
            np[7] =(0, 0, 0) 
            np[8] =(0, 0, 0) 
            np[9] =(0, 0, 0) 
            np[10] =(0, 0, 0) 
            np[11] =(0, 0, 0) 
            np.write () 

        conexionMQTT.publish(topic_SensorHUM,str(hum))
    except OSError as e:
        print("Error ",e)
        time.sleep(5)
        machine.reset()