import network, time, urequests, _thread, gc
from machine import Pin, PWM, ADC
from dht import DHT22
from utime import sleep
from utelegram import Bot

# Reemplaza con tu token de bot
TOKEN = '6978940856:AAESQpR5BafX3rsvZbJZ2lVRRSh0JCrUak8'
#CHAT_ID = '1333605182'  # Reemplaza con el chat_id obtenido

bot = Bot(TOKEN)
ldr = ADC(Pin(34))
servo = PWM(Pin(16), freq=50)
sensor_dht = DHT22(Pin(4))
rele = Pin(14, Pin.OUT)

bajo = Pin(18, Pin.IN)
medio = Pin(19, Pin.IN)
alto= Pin(21, Pin.IN)



def map_servo(x):
    return int((x - 0) * (125 - 25) / (180 - 0) + 25)

def conectaWifi(red, password):
    global miRed
    miRed = network.WLAN(network.STA_IF)
    if not miRed.isconnected():
        miRed.active(True)
        miRed.connect(red, password)
        print('Conectando a la red', red + "…")
        timeout = time.time()
        while not miRed.isconnected():
            if (time.time() - timeout) > 10:
                return False
    return True

if conectaWifi("Wokwi-GUEST", ""):
    print("Conexión exitosa!")
    print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())

    @bot.add_command_handler('Inicio')
    def inicio(update):
        update.reply('''Menu:  
                        \n   Abrir Comedero: On  \U0001F601
                        \n   Cerrar  Comedero: Off \U0001F601
                        \n   Temperatura: Tem  \U0001F601
                        \n   Humedad: Hum  \U0001F601
                        \n   Nivel de agua: Niv  \U0001F601
                        ''')

    @bot.add_command_handler('On')
    def abrir_caja(update):
        m = map_servo(90)
        servo.duty(m)
        update.reply("Abriendo Comedero")

    @bot.add_command_handler('Off')
    def cerrar_caja(update):
        m = map_servo(0)
        servo.duty(m)
        update.reply("Cerrando Comedero")

    @bot.add_message_handler("Tem")
    def sensor_temperatura(update):
        sensorDHT.measure()
        temp = sensorDHT.temperature()
        hum = sensorDHT.humidity()              
        update.reply("Temperatura: "+ str(temp) )
        print("ok Tem", temp)
        time.sleep(2)
    

    @bot.add_message_handler("Hum")
    def sensor_huemedad(update):
        sensorDHT.measure()
        hum = sensorDHT.humidity()              
        update.reply("Humedad: " + str(hum))
        print("ok Humedad",hum)
        time.sleep(2)

    @bot.add_message_handler("Niv")
    def sensor_huemedad(update):
        n_bajo= bajo.value()
        n_medio= medio.value()
        n_alto= alto.value()

        if n_alto==0 and n_medio==0 and n_bajo==1:
            update.reply("Nivel Bajo")
        
        elif n_alto==0 and n_medio==1 and n_bajo==1:
            update.reply("Nivel Medio")
        
        elif n_alto==1 and n_medio==1 and n_bajo==1:
            update.reply("Nivel Alto")

        else:
            update.reply("Error")





    def monitor_luz():
        while True:
            ldr_read = ldr.read()
            #print(ldr_read)
            if ldr_read < 1000 :
                rele.on()
            else:
                rele.off()
            
    _thread.start_new_thread(monitor_luz, ())

    bot.start_loop()
else:
    print("Imposible conectar")
    miRed.active(False)

NOCOMNCVCCGNDINLED1PWRRelay Module