2017-05-24 22 views
0

我一直在试图找到有关此问题的答案或信息,但没有结果。这个想法是用python将相同的主题发布到两个不同的MQTT服务器上。我的意思是,像这样:两个MQTT服务器pub/sub与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) 

所以,问题是关于同时statment ......我该怎么办发布同一主题为MQTT1和MQTT2?正如你所看到的,我想要发布在互联网上运行的MQTT代理中的有效载荷,但是如果我失去了互联网连接,那么我可以将pub/sub发布到我的局域网中的MQTT代理。

回答

1

您不能只将同一个客户端连接到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