import network, time, urequests, _thread
from machine import Pin, PWM
from utime import sleep, sleep_ms, ticks_us
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04

# MQTT Server Parameters
MQTT_CLIENT_ID = "cindy22222&&&5454"#cambiar siempre
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "chat/caja/alerta/"
MQTT_TOPIC_SUB   = "chat/caja/apertura/"

sensor_caja = HCSR04(trigger_pin=13, echo_pin=12)
servo = PWM(Pin(16), freq=50)

info=""

def sub_cb(topic, msg):
            global info
            dato=msg.decode()
            #dato=ujson.loads(msg.decode())
            print(f'Recibido:{dato}')
            info = dato
            #print(dato["Temperatura"])
            #print(info)


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())

    print("Conectando a  MQTT server... ",MQTT_BROKER,"...", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()
    
    print("Conectado al Broker!")

    

    while True:

        client.set_callback(sub_cb)
        client.subscribe(MQTT_TOPIC_SUB)
        print ("esperando")
        #client.wait_msg()
        
        
        distancia = sensor_caja.distance_cm()
        print(distancia)
        sleep(3)
       
        print("Revisando Condiciones ...... ")
        
        if distancia < 50: 
            message = ujson.dumps({
            "Alerta":1,
            })
            
            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)

        else: 
            message = ujson.dumps({
            "Alerta":0,
            })
            
            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)
        
        if info =="Open":
            m = map_servo(180)
            servo.duty(m)
            message = ujson.dumps({
            "Estado":"Caja Abierta",
            })

            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)

        elif info =="Close":
            m = map_servo(0)
            servo.duty(m)
            message = ujson.dumps({
            "Estado":"Caja Cerrada",
            })

            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)


            

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