'MQTT.js multiple subscription

I'm playing around with MQTT and MQTT.js. I have running a MQTT broker and now I want to subscribe to multiple topics. One topic is no problem, but multiple.

I have these two topics:

'sensor/esp8266-1/humidity'
'sensor/esp8266-1/temperature'

and I with this piece of code I subscribe on these two topics

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://10.0.0.18');


client.subscribe('sensor/esp8266-1/humidity');
client.subscribe('sensor/esp8266-1/temperature');

client.on('message', function(topic, message, packet) {
    console.log(packet)
});

With this code console.log returns me the following

Packet {
  cmd: 'publish',
  retain: false,
  qos: 0,
  dup: false,
  length: 35,
  topic: 'sensor/esp8266-1/temperature',
  payload: <Buffer 32 31 2e 32 30> }
Packet {
  cmd: 'publish',
  retain: false,
  qos: 0,
  dup: false,
  length: 32,
  topic: 'sensor/esp8266-1/humidity',
  payload: <Buffer 34 31 2e 30 30> }

This looks at the first very good, but how can I get the temperature/humidity data from that?

I tried it with this

console.log(packet.payload.toString())

But now I got every time temperature and humidty without which I know what number means.

In the End I would like to get two variables (temperature/humidity) fill with the right data. Later I want to concat the two variables and store these to an SQL Database.



Solution 1:[1]

You've not said how you want to uses these 2 values but the following is the simplest way to start.

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://10.0.0.18');

var temperature;
var humidity;

client.subscribe('sensor/esp8266-1/humidity');
client.subscribe('sensor/esp8266-1/temperature');

client.on('message', function(topic, message, packet) {
  if (topic === 'sensor/esp8266-1/temperature') {
    temperature = message;
  }

  if (topic === 'sensor/esp8266-1/humidity') {
    humidity = message;
  }
});

You can make it a little simpler by using a single wildcard subscription:

client.subscribe('sensor/esp8266-1/+');

Which will subscribe to all topics that start with sensor/esp8266-1/

EDIT: Now we have finally thrashed out what you wanted to ask (NOT CLEAR IN THE QUESTION)

client.on('message', function(topic, message, packet) {
  if (topic === 'sensor/esp8266-1/temperature') {
    temperature = message;
  }

  if (topic === 'sensor/esp8266-1/humidity') {
    humidity = message;
  }

  if (temperature && humidity) {
     //do database update or print
     console.log("----");
     console.log("temp: %s", temperature);
     console.log("----");
     console.log("humidity: %s", humidity);
     //reset to undefined for next time
     temperature = undefined;
     humidity = undefined;
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1