两个 MQTT 服务器 pub/sub 和 python

Two MQTT server pub/sub with python

我一直在努力寻找关于这个问题的答案或信息,但还没有结果。这个想法是将相同的主题发布到两个不同的 MQTT 服务器 python。我的意思是,像这样:

import paho.mqtt.client as paho
import datetime, time

mqttc = paho.Client()

host1 = "broker.hivemq.com" # the address of 1st mqtt broker
host2 = "192.168.1.200" # the address of 2nd mqtt broker
topic= "testingTopic"
port = 1883

def on_connect(mosq, obj, rc):
   print("on_connect() "+str(rc))

mqttc.on_connect = on_connect

print("Connecting to " + host)
mqttc.connect(host1, port, 60)
mqttc.connect(host2, port, 60)

while 1:
    # publish some data at a regular interval
    now = datetime.datetime.now()
    mqttc.publish(topic, now.strftime('%H:%M:%S')) #Publishing to MQTT1
    mqttc.publish(topic, now.strftime('%H:%M:%S')) #Publishing to MQTT2
    time.sleep(1)

所以,问题是关于 while 语句...我怎样才能将相同的主题发布到 MQTT1 和 MQTT2 中? 如您所见,我希望能够在互联网上 运行 的 MQTT 代理中发布有效负载,但如果我失去互联网连接,那么我可以 pub/sub 到我局域网中的 MQTT 代理。

您不能只将同一个客户端连接到 2 个不同的代理。您需要连接到单独代理的客户端的 2 个单独实例。

...
mqttc1 = paho.Client()
mqttc2 = paho.Client()
...
mqttc1.connect(host1, port, 60)
mqttc2.connect(host2, port, 60)
...
mqttc1.publish(topic, now.strftime('%H:%M:%S')) #Publishing to MQTT1
mqttc2.publish(topic, now.strftime('%H:%M:%S')) #Publishing to MQTT2