我目前正在尝试在面向对象的上下文中使用 Python3 中的 paho mqtt 库。 但是,由于某种原因,回调函数没有被调用。
import paho.mqtt.client as mqtt
import time
import logging
logger = logging.getLogger("IDS_LOGGER.refining")
logging.basicConfig(level=logging.INFO)
class refiner(object):
def __init__(self,configpath="./sampleconfig.xml"):
try:
self.CONFIGPATH = configpath
self.BROKER_IP = "localhost"
self.parse_config()
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(self.BROKER_IP)
logging.info("Connected to {0}, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print("error")
def on_message(self,client,userdata,msg):
"""MQTT Callback function for handling received messages"""
print("message received!")
def on_connect(self,client,userdata,msg):
print("connected!")
self.client.subscribe("TRACED")
为什么?
最佳答案
将 on_connect()
定义替换为:
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
此外,出于调试目的,请考虑在异常处理程序中打印实际异常,而不是仅打印“error”
:
try:
...
except Exception as e:
print(e)
通过上述修复,我通过连接到 test.mosquitto.org
测试了您的代码:
class refiner(object):
def __init__(self):
try:
self.BROKER_IP = "test.mosquitto.org"
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.connect(self.BROKER_IP, 1883, 60)
logging.info("Connected to {0}, starting MQTT loop".format(self.BROKER_IP))
self.client.loop_forever()
except Exception as e:
print(e)
def on_connect(self, client, userdata, flags, rc):
print("connected!")
self.client.subscribe("TRACED")
x = refiner()
它成功输出:
INFO:root:Connected to test.mosquitto.org, starting MQTT loop
connected!
关于OOP 中的 Python MQTT 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361993/