# Este código es una modificaión del archivo original main.py.
# Solamente se agragaron lineas de código para utilizar el tópico
# "notification" con distintos valores que permitan encender, apagar
# y hacer parpadear  un led conectado en el pin 2 del ESP32
import machine
import time

def sub_cb(topic, msg):
  print((topic, msg))
  if topic == b'notification' and msg == b'received':
    print('ESP received hello message')

###########################################################
# Código agregado al main.py original
##########################################################
  led = machine.Pin(2, machine.Pin.OUT)
  if topic == b'notification' and msg == b'pin 2 ON':
    led.value(1)
  if topic == b'notification' and msg == b'pin 2 OFF':
    led.value(0)
  if topic == b'notification' and msg == b'pin 2 BLINK':
    for vez in [1,2,3,4,5]:
        led.value(1)
        time.sleep(0.250)
        led.value(0)
        time.sleep(0.250)
###########################################################
def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server)
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe(topic_sub)
  print('Conectado al broker MQTT %s, suscrito al tópico %s' % (mqtt_server, topic_sub))
  return client

def restart_and_reconnect():
  print('Falla al conectar al broker MQTT. Reconectando...')
  time.sleep(10)
  machine.reset()

try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

while True:
  try:
    client.check_msg()
    if (time.time() - last_message) > message_interval:
      msg = b'Hello #%d' % counter
      client.publish(topic_pub, msg)
      last_message = time.time()
      counter += 1
  except OSError as e:
    restart_and_reconnect()
