#! /usr/bin/python3 # =================================================================== # MQTT Publish # ------------------------------------------------------------------- # Python Client Documentation # //www.eclipse.org/paho/index.php?page=clients/python/docs/index.php # ------------------------------------------------------------------- # Simple Python MQTT Publish and Subscribe Example Script # http://www.steves-internet-guide.com/python-mqtt-publish-subscribe/ # ------------------------------------------------------------------- # Python MQTT Client Connections– Working with Connections # http://www.steves-internet-guide.com/client-connections-python-mqtt/ # =================================================================== import paho.mqtt.client as mqtt import time import sys broker = '192.168.1.77' topic = 'sensors/sensor2' # ---- define callbacks def on_message(client, userdata, message): time.sleep(1) m = str(message.payload.decode("utf-8")) print(f"received message = {m}") def on_connect(client, userdata, flags, rc): if rc==0: print(f"connected OK Returned code={rc}") else: print(f"Bad connection Returned code={rc}") sys.exit() # ---- main print(f"broker: {broker}") print(f"topic : {topic}") print() print("Create client ...") client = mqtt.Client("mqtt-client") print("Bind on_message callback ...") client.on_message=on_message print("Bind on_connect callback ...") client.on_connect=on_connect print("Connect to broker ...") client.connect(broker) #print("Subscribe to topic ...") #client.subscribe(topic) print("Start loop to procss messages ...") client.loop_start() print("Subscribe to topic ...") client.subscribe(topic) print("Sleep ...") time.sleep(4) print("Disconnect ...") client.disconnect() print("Stop loop ...") client.loop_stop()