Pubsubclient: how to publish on multiple brokers?

Created on 26 Oct 2018  路  9Comments  路  Source: knolleary/pubsubclient

I have an Esp8266 and I control it from my LAN broker, but when I outside I want to control by Cloud broker, how can I do that?

I would like to create two client (LOCAL/CLOUD) in order to publish on each, but the function callback only accept and is connected to one server, it is possible to connect it to two servers, or I have create another client, could you help me?

Most helpful comment

You are calling both of your clients client - which is why it complains you are redefining that variable.

You need to use separate variables:

PubSubClient client1(espClient1);
PubSubClient client2(espClient2);

client1.setServer(mqtt_server_Local, 1883);
client2.setServer(mqtt_server_Cloud, 1883);

All 9 comments

Hi @i17brn,

I think you should be able to create two separate client instances, one connected to each broker. But I have to admit it isn't something I've ever tried, so I cannot claim it will definitely work.

when I try to create two separate client instances, arduino said "error: redefinition PubSubClient client", how would you create two separate client instances?

What exactly did you try? I'm not setup to test any code with this library currently.

WiFiClient espClient1;
WiFiClient espClient2;

PubSubClient client(espClient1);
PubSubClient client(espClient2);

client.setServer(mqtt_server_Local, 1883); =>client 1
client.setServer(mqtt_server_Cloud, 1883); =>client 2

You are calling both of your clients client - which is why it complains you are redefining that variable.

You need to use separate variables:

PubSubClient client1(espClient1);
PubSubClient client2(espClient2);

client1.setServer(mqtt_server_Local, 1883);
client2.setServer(mqtt_server_Cloud, 1883);

Thank you very much, it worked. This library works very well for multiple brokers, multiple subscribers and multiple publishers

Great - glad to hear it.

this sketch to connect two ESPs is uploading to one nodeMCU? could anyone explain in detail. Thank you in advance.

Thanks i got it working, we were able to connect to both local broker raspberrypi and at the same time to ubidots cloud using esp32 and using this concept.

PubSubClient client1(espClient1);
PubSubClient client2(espClient2);

client1.setServer(mqtt_server_Local, 1883);
client2.setServer(mqtt_server_Cloud, 1883);

Was this page helpful?
0 / 5 - 0 ratings