# Callback function for successful connection defon_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribe to a topic, here we take "test/topic" as an example client.subscribe("test/topic")
# Callback function for receiving messages defon_message(client, userdata, msg): print("Topic: " + msg.topic + " Message: " + str(msg.payload))
# Callback function for publishing messages defon_publish(client, userdata, mid): print(f"Message {mid} published.")
# Set up MQTT client client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.on_publish = on_publish
# Connect to MQTT broker, here we take localhost as an example, the default port is 1883 client.connect(host="localhost", port=1883, keepalive=60) # client.username_pw_set("admin", "123456")
# Publish a message to a specified topic client.publish("test/topic", "MQTT test")