1#!/usr/local/bin/python3.8 2# -*- coding: utf-8 -*- 3 4# Copyright (c) 2010-2013 Roger Light <roger@atchoo.org> 5# 6# All rights reserved. This program and the accompanying materials 7# are made available under the terms of the Eclipse Distribution License v1.0 8# which accompanies this distribution. 9# 10# The Eclipse Distribution License is available at 11# http://www.eclipse.org/org/documents/edl-v10.php. 12# 13# Contributors: 14# Roger Light - initial implementation 15# Copyright (c) 2010,2011 Roger Light <roger@atchoo.org> 16# All rights reserved. 17 18# This shows a simple example of an MQTT subscriber using connect_srv method. 19 20import context # Ensures paho is in PYTHONPATH 21import paho.mqtt.client as mqtt 22 23def on_connect(mqttc, obj, flags, rc): 24 print("Connected to %s:%s" % (mqttc._host, mqttc._port)) 25 26def on_message(mqttc, obj, msg): 27 print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload)) 28 29def on_publish(mqttc, obj, mid): 30 print("mid: "+str(mid)) 31 32def on_subscribe(mqttc, obj, mid, granted_qos): 33 print("Subscribed: "+str(mid)+" "+str(granted_qos)) 34 35def on_log(mqttc, obj, level, string): 36 print(string) 37 38# If you want to use a specific client id, use 39# mqttc = mqtt.Client("client-id") 40# but note that the client id must be unique on the broker. Leaving the client 41# id parameter empty will generate a random id for you. 42mqttc = mqtt.Client() 43mqttc.on_message = on_message 44mqttc.on_connect = on_connect 45mqttc.on_publish = on_publish 46mqttc.on_subscribe = on_subscribe 47# Uncomment to enable debug messages 48#mqttc.on_log = on_log 49mqttc.connect_srv("mosquitto.org", 60) 50mqttc.subscribe("$SYS/broker/version", 0) 51 52 53rc = 0 54while rc == 0: 55 rc = mqttc.loop() 56 57print("rc: "+str(rc)) 58