#! /usr/bin/python3 # =================================================================== # MQTT Client Demo # # From: https://www.youtube.com/watch?v=Pb3FLznsdwI # Raspberry Pi - Getting started with MQTT # =================================================================== import paho.mqtt.client as mqtt # ------------------------------------------------------------------- # ---- callback # ---- The callback for when the client receives a COMEBACK response # ---- from the server # ------------------------------------------------------------------- def on_connect(client, userdata, flags, rc): print(f'Connected with results code {rc}') # subscribing in on_connect() - if we loose the connection # and reconnect, then subscriptions will be renewed client.subscribe('CoreElectronics/test') client.subscribe('CoreElectronics/topic') # ------------------------------------------------------------------- # ---- callback # ---- The callback for when a PUBLISH message is received # ---- from the server # ------------------------------------------------------------------- def on_message(client, userdata, msg): print(f'Topic: {msg.topic}, Payload: {msg.payload}') if msg.payload == b'Hello': print('Received message #1 do something') # do something if msg.payload == b'World!': print('Received message #2 do something else') # do something else # ------------------------------------------------------------------- # --- main # ------------------------------------------------------------------- # Create an MQTT client and attach our routines to it client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect('test.mosquitto.org', 1883, 60) # process network traffic and dispatch callbcks. This will also # handle reconnecting. There are other loop() functions made # available. Check the documentation at # https://github.com/eclipse/paho.mqtt.python client.loop_forever()