import time
import machine
import micropython
import network
from hcsr04 import HCSR04
from machine import Pin
from umqtt.simple import MQTTClient

ssid = 'Wokwi-GUEST'
wifipassword = ''

mqtt_server = "io.adafruit.com"
port = 1883
user = 'Monastery' #falta definir
password = 'aio_oTsU79YgvKPQMCh6LQdLjDiqagX9' #key falta definir
client_id = 'project' #falta definir (unico)

topic_1 = 'Monastery/feeds/ActivacionAlarma'
topic_2 = 'Monastery/feeds/Proximidad'

ALARMA_ON=False

sensor = HCSR04(trigger_pin=12, echo_pin=14)
buzzer = Pin(19,Pin.OUT)

#definimos modo Station (connect to AP remote)
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)

#observamos IP
print(sta_if.ifconfig())

#connect to wifi
sta_if.connect(ssid, wifipassword)
print("conectado")
while not sta_if.isconnected():
    print (".", end="")
    time.sleep(0.1)
print("conectando wifi")
print(sta_if.ifconfig())

def funcion_callback(topic,msg):
    global ALARMA_ON
    dato=msg.decode('utf-8')
    topicrec=topic.decode('utf-8')
    print("mensaje de topico "+topicrec+":"+dato)
    if topicrec == topic_1:
        if "OFF" in dato:
            ALARMA_ON = False
            Buzzer.off()
        elif "ON" in dato:
            ALARMA_ON = True

#conect to broker MQTT

try:
    conexionMQTT = MQTTClient(client_id, mqtt_server, user=user, password=password, port=int(port))
    conexionMQTT.set_callback(funcion_callback)
    conexionMQTT.connect() #connection
    conexionMQTT.subscribe(topic_1) #nos subscribimos a un topico luego del connect
    print("conectando al broker MQTT")
except OSError as e:
    print("error al conectar con el Broker MQTT, procede a reiniciar...")
    time.sleep(5)
    machine.reset()

while True: 
    #ciclo infinito, aca haremos el proceso
    try:
    #verificamos msg del broker
     conexionMQTT.check_msg()
     time.sleep(500)