Home > Enterprise >  MQTT.js how to transfer message into discrete variables
MQTT.js how to transfer message into discrete variables

Time:01-02

I have some code on a small microcontroller that publishes sensor readings using MQTT under the topic "motorbeta" the format is JSON and looks like this: {temperature:257.00, pressure:100.00}. On my webserver, I have a script that subscribes to the same MQTT topic. The javascript is posted below.

On the webserver I want to take the received message and create two variables in this script (temperature and pressure) and set each variable equal to its corresponding value. For example, temperature=257 and pressure=100 how can I do this? My end goal is to then push the temperature and pressure readings into a MYSQL database under columns with the respective variable names.

////////////////////////////////////////////////////////////////////////////////
//setup
var mqtt    = require('mqtt'); //for client use
const fs = require('fs');
var count =0; //connected to an end script function
var caFile = fs.readFileSync("filepath/ca.crt");
var topic = "motorbeta";


var options={
    port:8883,
    clientId:"dev",
    username:"user",
    password:"password",
    protocol: 'mqtts',
    clean:true,
    rejectUnauthorized: false,
    retain:false, 
    ca:caFile
};


var client  = mqtt.connect("http://dns",options);


//handle incoming messages
client.on('message',function(topic, message, packet){
    console.log("message is "  message);
    console.log("topic is "  topic);
});

//connection dialog
client.on("connect",function(){
    client.subscribe(topic, {qos:1});
});

//handle errors
client.on("error",function(error){
    process.exit(1);
});

CodePudding user response:

I believe you are asking to take a two variable JSON string and create two variables temperature and pressure. This can be done using mostly the code that is posted in the question except the client.on('message',function(topic, message, packet) should be expanded.

Assuming the input looks like: {"temperature":257.00,"pressure":115}

The desired code would be:

//handle incoming messages
client.on('message',function(topic, message, packet){
    var raw = "" message;
    console.log(raw);
    var obj = JSON.parse(raw);
    var temp = obj.temperature; 
    var press = obj.pressure;
    console.log(temp);
    console.log(press);

});

Keep in mind the console logs are just for error validation purposes.

  • Related