简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM