0

I've been trying to find answers or info about this question but without results yet. The idea is to publish the same topic into two different MQTT servers with python. I mean, something like this:

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)

So, the question is about the while statment... how can I do to publish the same topic into MQTT1 and MQTT2? As you can see, I want to have to posibility to publish that payload in MQTT broker that is running in internet, but if I lose internet connection, then I can pub/sub to MQTT broker in my LAN.

hardillb
  • 54,545
  • 11
  • 67
  • 105
ElectroMESH
  • 1
  • 1
  • 6

1 Answers1

1

You can't just connect the same client to 2 different brokers. You need 2 separate instances of the of the client that you connect to the separate brokers.

...
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
hardillb
  • 54,545
  • 11
  • 67
  • 105
  • Sorry if in that moment I didn't say thank you. In that moment I was just a beginner without enough skills in stackoverflow and GitHub, where actually I have well documented all of this answers in order to avoid duplicate questions :) – ElectroMESH Apr 07 '21 at 05:46