import paho.mqtt.client as mqtt# Define MQTT broker detailsbroker = 'my-broker-host' # Replace with your broker's addressport = 1883 # Typically 1883 for non-SSL, 8883 for SSLtopic = 'mytopic' # Topic to subscribe/publishusername = 'myuser' # Replace with your usernamepassword = 'mypasswrd' # Replace with your password# Define callback for connectiondef on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") client.subscribe(topic) # Subscribe to the topic upon successful connection else: print(f"Connection failed with code {rc}")# Define callback for received messagesdef on_message(client, userdata, msg): print(f"Message received: {msg.payload.decode()} on topic {msg.topic}")# Initialize the MQTT clientclient = mqtt.Client()# Set username and passwordclient.username_pw_set(username, password)# Attach callbacksclient.on_connect = on_connectclient.on_message = on_message# Connect to the brokerclient.connect(broker, port, 60)# Function to publish a messagedef publish_message(client, topic, message): client.publish(topic, message) print(f"Message '{message}' published on topic '{topic}'")# Start the MQTT client loop to handle reconnects, subscriptions, etc.client.loop_start()# Example of publishing a messagepublish_message(client, topic, "Hello, MQTT!")# Keep the script running for a while to receive messagestry: while True: passexcept KeyboardInterrupt: print("Disconnecting from broker") client.loop_stop() client.disconnect()