led = Pin(15, Pin.OUT)
# Timer Object
tim = Timer(-1)
# MQTT Server Parameters
MQTT_CLIENT_ID = "qqlalang"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "/SIGMASIGMABOY/actuate_lamp"
# Connection to MQTT Server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Callback funcion for Topic Subscription
# def sub_cb(topic, msg):
# print(str(topic,'UTF-8'))
# print(str(msg,'UTF-8'))
def sub_cb(topic, msg):
print(f"Message received on topic {topic.decode()}: {msg.decode()}")
if msg == b"ON":
led.value(1) # Turn LED on
print("LED turned ON")
elif msg == b"OFF":
led.value(0) # Turn LED off
print("LED turned OFF")
else:
print("Unknown command")
# Callback funcion for Publish Data
def pub_topic(tim,topic:str,msg=""):
msg = str(random.randint(0,1000))
client.publish(topic, msg)
# Timer for Periodic Data Publish
tim.init(period=5000, mode=Timer.PERIODIC,callback=lambda pub: pub_topic(tim,MQTT_TOPIC))
# MQTT Subcribtion details
client.set_callback(sub_cb)
client.subscribe(MQTT_TOPIC)
while True:
client.check_msg()