#! /usr/bin/python3 # =================================================================== # IoT MQTT Test Subscriber # This simulates MQTT subscribing IoT devices # =================================================================== import user_interface as ui import paho.mqtt.client as mqtt import sys broker = '192.168.1.77' topic = 'test/wifi/iot-01' # ------------------------------------------------------------------- # ---- callbacks # ------------------------------------------------------------------- # ---- callback when the client connects to the broker # ---- # ---- 0: Connection successful # ---- 1: Connection refused – incorrect protocol version # ---- 2: Connection refused – invalid client identifier # ---- 3: Connection refused – server unavailable # ---- 4: Connection refused – bad username or password # ---- 5: Connection refused – not authorised # ---- 6-255: Currently unused. # ---- # ---- also subscribe to the topic def on_connect(client, userdata, flags, rc): print(f'Connected with result code {str(rc)}') client.subscribe(topic) # ---- callback when a topic message is received from the broker def on_message(client, userdata, msg): m = str(msg.payload.decode('utf-8')) print(f'received topic:{msg.topic} msg:{m}') # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- # ---- running Python3 if not ui.running_python3(): print() print('Must run Python3 - program exit') print() sys.exit() print() print('==================================================') print(f'broker: {broker}') print(f'topic : {topic}') print('==================================================') print() # Create instance of client with client ID 'iot_mqtt_test' client = mqtt.Client('iot_mqtt_test_sub') # Define callback function for successful connection client.on_connect = on_connect # Define callback function for receipt of messages # client.connect(broker, 1883, 60) # Connect to (broker, port, keepalive-time) client.on_message = on_message client.connect(broker) # Start networking daemon client.loop_forever() print('Disconnect ...') client.disconnect()