from umqtt.simple import MQTTClient # Define the MQTT broker details server = "broker.hivemq.com" port = 1883 topic = "test" # Define the callback function to handle incoming messages def message_handler(topic, message): print("Received message on topic {}: {}".format(topic, message)) # Connect to the MQTT broker client = MQTTClient("client_id", server, port) client.set_callback(message_handler) client.connect() # Subscribe to the topic client.subscribe(topic) # Wait for incoming messages while True: client.wait_msg()
from umqtt.simple import MQTTClient # Define the MQTT broker details server = "broker.hivemq.com" port = 1883 topic = "test" # Connect to the MQTT broker client = MQTTClient("client_id", server, port) client.connect() # Publish a message to the topic message = "Hello, World!" client.publish(topic, message) # Disconnect from the MQTT broker client.disconnect()This example connects to a public MQTT broker, publishes a message to the `test` topic, and disconnects from the broker. The `umqtt.simple` module is part of the `micropython-umqtt` package library.