MQTT 订阅在多线程中无法正常工作
MQTT subscribing does not work properly in Multithreading
我有如下代码
threads = []
t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start)
t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start)
threads.append(t)
threads.append(t1)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
我的主题每 5 分钟 发送一次数据。
当我使用上面的代码时,它不能正常工作,有时它发送数据有时不发送数据。
但是当我在没有 thread 的情况下使用一个主题时,它工作正常并且每 5 分钟就会完美地接收一次数据。
我该如何解决这个问题?我想同时订阅两个主题。
我正在为 MQTT
使用 Paho
我的订阅class是
class Subscribe:
def __init__(self, username, passowrd, topic, host, port):
self.username = username
self.password = passowrd
self.topic = topic
self.host = host
self.port = port
def start(self):
self.mqttc = mqtt.Client(client_id="Python")
self.connected = False
self.mqtt_message = ""
self.mqttc.username_pw_set(self.username, self.password)
self.mqttc.on_connect = self.on_connect
self.mqttc.on_message = self.on_message
self.mqttc.connect(self.host, self.port)
self.mqttc.loop_forever()
def on_message(self, client, userdata, message):
"""
Fetch data when data coming to Broker
"""
topic = message.topic
m = json.loads(message.payload.decode("utf-8"))
print(m)
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Connected to broker", self.topic)
self.mqttc.subscribe(self.topic)
self.connected = True
else:
print("could not connect", self.topic)
我不得不为 Client
的两个实例提供两个不同的 client_id
,它解决了问题。
我有如下代码
threads = []
t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start)
t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start)
threads.append(t)
threads.append(t1)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
我的主题每 5 分钟 发送一次数据。
当我使用上面的代码时,它不能正常工作,有时它发送数据有时不发送数据。
但是当我在没有 thread 的情况下使用一个主题时,它工作正常并且每 5 分钟就会完美地接收一次数据。
我该如何解决这个问题?我想同时订阅两个主题。
我正在为 MQTT
使用 Paho我的订阅class是
class Subscribe:
def __init__(self, username, passowrd, topic, host, port):
self.username = username
self.password = passowrd
self.topic = topic
self.host = host
self.port = port
def start(self):
self.mqttc = mqtt.Client(client_id="Python")
self.connected = False
self.mqtt_message = ""
self.mqttc.username_pw_set(self.username, self.password)
self.mqttc.on_connect = self.on_connect
self.mqttc.on_message = self.on_message
self.mqttc.connect(self.host, self.port)
self.mqttc.loop_forever()
def on_message(self, client, userdata, message):
"""
Fetch data when data coming to Broker
"""
topic = message.topic
m = json.loads(message.payload.decode("utf-8"))
print(m)
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Connected to broker", self.topic)
self.mqttc.subscribe(self.topic)
self.connected = True
else:
print("could not connect", self.topic)
我不得不为 Client
的两个实例提供两个不同的 client_id
,它解决了问题。