Search code examples
javascriptnode.jsmqttiotesp8266

Mqtt.js how to handle multiple topics


I'm using multiple ESP8266 to monitor multiple rooms around my house. And I was wondering what is the best way to handle the incoming data if for each room I'm waiting for a specific temperature level to turn on the AC or Heater.

Do I handle all the data and the turning off and on the AC/Heater in a global .on message method or do I create for each room a .on message? I'm using MQTT.js (https://www.npmjs.com/package/mqtt)

this.client.on("message", (topic, message) => {
  console.log(`Received ${message}`);
  const roomId = JSON.parse(message);
  this.onReceiveMessage(topic, message);
});

Thank you


Solution

  • There will only ever be one event when a message is delivered to the client, if you add more than one on message event listener they will all be called with the same topic and message values for a given message.

    So there is no value in registering more than 1 on message client, you should then filter on the supplied topic, how you then choose to organise the code is entirely up to you and what actions you wish to take.