knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

Subscribing to two topics #994

Open HaViGit opened 1 year ago

HaViGit commented 1 year ago

As a beginner in using MQTT I run into a problem when I want to subscribe to two topics. Subscribing to one topic is going well with the sketch below, but I can't subscribe to both topics (Energy/timestamp and Energy/power). Not even with the instructions elsewhere in this forum and not even after trying for many hours.

Can someone link to a (complete) demo sketch? Or is someone kind enough to show me how to modify the sketch below?


#include <PubSubClient.h>

const char* ssid = "***";
const char* password = "***";
const char *mqtt_broker = "192.168.2.155";
const char *topic = "Energy/timestamp";
const char *mqtt_username = "";
const char *mqtt_password = "";

const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  bool rlst = false;
  Serial.begin(115200);
  delay(1000);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
  }
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
      String client_id = "nrg-client-";
      client_id += String(WiFi.macAddress());
      if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
          Serial.println("Connecting MQTT");
      } else {
          Serial.print("MQTT error: ");
          Serial.print(client.state());
          delay(2000);
      }
  }
  client.subscribe(topic);
  Serial.println("MQTT Connected");
}

void loop() {
  client.loop();
}

void callback(char *topic, byte *payload, unsigned int length) {
  Serial.print("Message in topic ");
  Serial.print(topic);
  Serial.print(": ");
  for (int i = 0; i < length; i++) {
      Serial.print((char) payload[i]);
  }
  Serial.println();
}
knolleary commented 1 year ago

Without seeing what you have actually tried it is hard to suggest where it may be going wrong.

But it should be a case of calling client.subscribe once for each topic you want to subscribe to:

const char *topic = "Energy/timestamp";
const char *topic2 = "Energy/anotherTopic";

...

  client.subscribe(topic);
  client.subscribe(topic2);
HaViGit commented 1 year ago

Thanks for your help, it does indeed work with just that extra code.