from machine import Pin
from time import sleep

#led = Pin(14, Pin.OUT)    # 22 number in is Output
push_button = Pin(13, Pin.IN)  # 23 number pin is input


def sub_cb(topic, msg):
  print((topic, msg))
  if topic == b'status' and msg == b'Light is On':
    print('ESP received Light is On message')

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('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

while True:
  try:
      client.check_msg()
      logic_state = push_button.value()
      if logic_state == True:
          msg = 'ON'
          client.publish(topic_pub, msg)
      else:
          msg = 'OFF'
          client.publish(topic_pub, msg)
  except OSError as e:
      restart_and_reconnect()
