Search code examples
node.jsasynchronouspromisemodbus

NodeJS Modbus Master Read From multiple IP Adresses


I'm working in a modbus project using the jsmodbus (https://github.com/Cloud-Automation/node-modbus) module and this way, I can use the readHoldingRegister function:

var modbus = require('jsmodbus');

function read(station, callback){
var client = modbus.client.tcp.complete({ 
            'host'              : station.ipAdress, 
            'port'              : station.port, //502
            'autoReconnect'     : true,
            'reconnectTimeout'  : 1000,
            'timeout'           : 5000,
            'unitId'            : 0
        });

client.connect();
    client.on('connect', function () {
        client.readHoldingRegisters(startReg, endReg).then(function (resp) {
            return callback(resp); 
        }).fail(console.log);
    });
    client.on('error', function (err) {
        retrun callback(null);
    });
}

I need to do this for how many IPs I have and push each "resp" result in an array "allResults" and then return it, but I'm not getting the result when I put the code above in a for loop neither async.each.

readAll(ip_adresses, (allResults) => {
     doSomethingWith(allResults);
});

what is the right way to do this ?


Solution

  • Try like below

    var async = require('async');
    ...
    function read(station, callback) {
        ...
    }
    
    async.map(ips, read, function(err, results) {
        if (err)
            return console.log(err);
        ...
        // Process results
    })