简体   繁体   中英

How To Send Multiple Data and Store in multiple variables in Mysql Database Using MQTT Broker Node js

i Want to Send Multiple Data Publisher to Broker and Store it Mysql Database, i am Using MQTT Broker But only Send Single Message in all Field, i Want to store Different data in all mysql Database Field Using Node JS. Please Give Solution.

Publisher code

var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://192.168.0.92');
client.on('connect', function () {
    setInterval(function () {
        var a = " messege";
        var b = "time";
        var c = "address";
        client.publish('myTopic',  `${a}`);
        client.publish('myTopic1', `${b}`);
        client.publish('myTopic1', `${c}`);

console.log('Message Sent');
}, 5000);
});

Broker code

var mosca = require('mosca');
var settings = { port: 1883}
var broker = new mosca.Server(settings)

var mysql = require('mysql');
var db = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: 'root@123',
      database: 'abc'
});

db.connect(() => { 
    console.log("db connect");
})

broker.on('ready', () => { 
    console.log("broker is ready");
})

broker.on('published', (packet) => { 
    message = packet.payload.toString()
    time = packet.payload.toString()
    add = packet.payload.toString()
    console.log(message);
    if (message.slice(0, 1) != '{' && message.slice(0, 4) != 'mqtt') {
        
        var dbSet = 'insert into broker set ?'
        // var dbSet =`INSERT INTO mqttjs (message, time) VALUES ("a","b")`;
        var data = {
            message: message,
            time: time,
            add:add
        }
        db.query(dbSet,data, (error, output) => {
            if (error) {
                console.log(error);

            } else {
                console.log("data saved");
            }

        })
    }

})

Short answer: You don't.

Slightly longer answer:

Each message is totally independent of any other.

This means you have 2 choices

  1. Have the publishing client bundle all the values into a single message
  2. Add an identifier to each message so the code doing the insert can work out when it has a full set of values before doing the insert.

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