2017-05-24 59 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