node-modbus-serial icon indicating copy to clipboard operation
node-modbus-serial copied to clipboard

port not found - modbus tcp

Open barv30 opened this issue 2 years ago • 2 comments

hi, I get this error: /usr/local/bin/node ./proto/modbus_connection.js Uncaught PortNotOpenError PortNotOpenError at processPromiseRejections (undefined:279:13) at processTicksAndRejections (undefined:97:32)

while running this code:
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();
client.connectTCP("192.168.100.195", { port: 502 })
client.setID(2)

client.writeRegister(0, 0)

I have a java program that does the same, and the connection works. I found a solution code that works for me:

const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();
client.connectTCP("192.168.100.195", { port: 502 }, run);

function run(){
    client.setID(2);

    client.readHoldingRegisters(0, 1, function(err, data) {
        console.log(data.data);
    });
}

but I don't want to do the connection in this way.

barv30 avatar Mar 16 '23 12:03 barv30

You are getting this error because the connect action is asynchronous. So you are trying to use writeRegister without waiting for the connectTcp to be established;

Example with TS: ...code constructor() { this.modbusClient = new ModbusRTU(); this.connect(); }

async connect(): Promise {

try {
  await this.modbusClient.connectTCP(ip, { port: port});
  await this.modbusClient.setID(1); 
  console.log('🖥️ Connection established🟢');
} catch (error) {
  if (error['code'] === 'EHOSTUNREACH') {
    console.log(`⛔Inaccessible: ${error['address']}`);
    if (this.connectionAttempts < this.maxConnectionAttempts) {
      this.connectionAttempts++;
      console.log(`🔎Reconnecting(attemp ${this.connectionAttempts} of ${this.maxConnectionAttempts})...`);
      setTimeout(() => this.conectar(), this.reconnectInterval);
    } else {
      console.log('⚠️Finished attemps.');
    }
  } else {
    console.log(error);
  }
}

} ...code


@yaacov [Could you put my example in the readme, I'll be happy to be able to contribute] @barv30

EMiltonDeveloper avatar May 17 '23 19:05 EMiltonDeveloper

hi, thank you for the example, i prefer to put the examples in the examples dir: https://github.com/yaacov/node-modbus-serial/tree/master/examples

can you create a running example and make a pull request adding it to the examples directory ?

yaacov avatar May 18 '23 04:05 yaacov