Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
466 stars 174 forks source link

Array of Clients Question #166

Closed alexbuczynsky closed 6 years ago

alexbuczynsky commented 6 years ago

Hello! I am enjoying using the jsmodbus client. I am wondering how I could create an array of clients built from a database.

In the example code below, I am pulling in the setup devices in an SQL database and using a for loop am populating the clients. The problem I am facing is that only one client is connecting and not the rest in the array. Any thoughts or suggestions?

function setupConnections(dbRows){
  let clients = [];

  for(let i=0;i<dbRows.length;i++){
    let deviceInfo = dbRows[i];
    if (deviceInfo.type === "SEM3") {continue;}
    let ip_address = deviceInfo.ip_address.split(":")[0];
    clients[i] = modbus.client.tcp.complete({
        'host': ip_address, /* IP or name of server host */
        'port': 502, /* well known Modbus port */
        'unitId': deviceInfo.mbUnitID,
        'timeout': 15000, /* 2 sec */
        'autoReconnect': true, /* reconnect on connection is lost */
        'reconnectTimeout': 15000, /* wait 15 sec if auto reconnect fails to often */
    });
    clients[i].customInfo = dbRows[i];
    //console.log(clients[i]);
  }
  console.log(clients)
  const timesPerMin   = 60;
  const time_interval = 1/timesPerMin*1000*60;
  for(let i=0;i<clients.length;i++){
    clients[i].connect()
    clients[i].on('connect', function () {
      setInterval( function () {
         clients[i].readHoldingRegisters(1, 6).then(function(response) {
           //console.log(JSON.stringify(response.payload, undefined, 2));
           let convertedData = modbusConvert(response.register,"F32",response.register.length)
           console.log(clients[i].customInfo.name,convertedData)
         });
      }, time_interval) /* reading coils every second */
    })
  }

}
alexbuczynsky commented 6 years ago

Never mind. The code works fine, I had an issue on my end. Ignore this issue.