Skip to content

Instantly share code, notes, and snippets.

@Ugbot
Created June 21, 2022 16:29
Show Gist options
  • Save Ugbot/fc2ebc17f7dfcf7973f6b441d90f3766 to your computer and use it in GitHub Desktop.
Save Ugbot/fc2ebc17f7dfcf7973f6b441d90f3766 to your computer and use it in GitHub Desktop.
simple python paho mqtt example, using hub data
import paho.mqtt.client as mqtt
import logging
def create_logger():
logger = logging.getLogger('mqtt debug')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
host = 'mqtt.ably.io'
port = 1883
channel = '[product:flight-data/flight-data]flight'
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(channel)
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
api_key = os.environ.get('ABLY_API_KEY', '')
username, passwd = api_key.split(':')
print(username)
mqttc = mqtt.Client(client_id="Test", clean_session=True, userdata=None)
mqttc.enable_logger(logger=create_logger())
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.username_pw_set(username, passwd)
mqttc.connect(host, port=port, keepalive=15)
mqttc.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment