Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
471 stars 175 forks source link

ReadHoldingRegisters for multiple IPs #35

Closed lfernando-silva closed 8 years ago

lfernando-silva commented 8 years ago

Actually your module are great and isn't really an issue.

I need to read multiple IP adresses and then, for each one, do a readHoldingRegisters and save results/errors in an array, like this:

var results = [ ];

for(var i in ips){
//connect to this IP
//on connect, readHoldingRegisters from this device and push the values
          results.push(registers);
//on error, push other value, say, { }
         results.push({ })
}
//finally return all reads
return callback(results);

How can I do this?

stefanpoeter commented 8 years ago

Answered or unanswered? What is it? :-)

lfernando-silva commented 8 years ago

Oh actually I reopen it because, after examinate the code in #19, seems my problem is kind different. I need to iterate over many IPs, acumulating its results... I tried with, for example, async.each loop, but it doesn't work. Blocking loop, like for... in also failure.

myFunction(IP_ADRESSES, callback){

var results = [ ];
async.each(IP_ADRESSES,
         function(IP, next){
                //open connection to this IP
               readHoldingRegisters(from,to). then(function(result){
               results.push(result);
               next();  //calls next iteration
               })
          },
         function(err){
          //return the results array, it is executed before the iteration above and returns an empty array.
                  return callback(results);
         });
}
stefanpoeter commented 8 years ago

I would assume that you connect to all clients first. When this is done, you call the readHoldingRegisters function from the clients (you can do this in an synchronous loop and store the returned promisses in an array). Then you wait for the promisses to finish with Q.all for example.

I hope that helps.

lfernando-silva commented 8 years ago

I didn't use promise.all, but actually solved it separating the create connection moment from the readHoldingRegisters moment as you sugested and it works well. Only in the connection failure it take a long time, but this is another problem. Thank you ;)