from umqtt.simple import MQTTClient
import utime as time
import machine
from machine import Timer
import ujson as json
import gc
import network

RY1 = machine.Pin(32,machine.Pin.OUT)
RY2 = machine.Pin(33,machine.Pin.OUT)
RY3 = machine.Pin(25,machine.Pin.OUT)
RY4 = machine.Pin(26,machine.Pin.OUT)

print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")
gc.collect()

tim0 = Timer(0)

def publish_data(connect_and_subscribe):
    try:
        new_message = client.check_msg()
        if new_message != 'None':
          client.publish(b'test_nd', b'25.6,45,13.5,1002.4')
    except OSError as e:
        restart_and_reconnect()
    
        
def sub_cb(topic, msg):
  msg = json.loads(msg)
  print(msg["topic"])
  eval(msg["topic"]).value(int(msg["state"]))

def connect_and_subscribe():
  client = MQTTClient("Mother_board", "picolab.embcircuit.com", 1883, user="picolab", password="ee211101980hunter")
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe('relay_remot')
  print('Connected to MQTT broker, subscribed to %s topic')
  return client

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

try:
  client = connect_and_subscribe()
  tim0.init(period=5000, mode=Timer.PERIODIC, callback=publish_data)
except OSError as e:
  restart_and_reconnect()