Cloud-Automation / node-modbus

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

createTCPServer() async call caused error #22

Closed NNM11 closed 8 years ago

NNM11 commented 8 years ago

There is a async issue with the jsmodbus.js createTCPServer() call (line 91).

        var server = serialServerModule.create(
        tcpServer,
        handler.Server.RequestHandler,
        handler.Server.ResponseHandler);
    // async - server is unknown as the cb is executed before the create() call completed.
        cb(null, server);

The code will fail if the server create() with port 502.

The serrver code

 modbus.createTCPServer(mbport, mbServer, function(err, modbusServer) {

// addHandler
modbusServer.addHandler(4, rirHandler);
modbusServer.addHandler(5, writeCoilHandler);

// log output
console.log('MBServer is running');
});

The createTCPServer() callbback with invalid 'modbusServer'

modbusServer.addHandler(4, rirHandler);
            ^

TypeError: Cannot read property 'addHandler' of undefined

stefanpoeter commented 8 years ago

Can you confirm that branch v0.5.2 fixes that?

NNM11 commented 8 years ago

The v0.5.2 branch did not fix the problem.

stefanpoeter commented 8 years ago

Ah, I didn't saw that there is a full error description including code. I checked the simpleServer.js example and it works if you set the port to 502. Check the err variable before assigning handler.

NNM11 commented 8 years ago

The sample code with error checking will avoid this problem when port 502 is blocked by default.

 // create Modbus TCP Server
 modbus.createTCPServer(8888, '127.0.0.1', function (err, modbusServer) {
     if (err) { 
               console.log(err);
               process.exit(1);
      }
      // addHandler
      modbusServer.addHandler(4, rirHandler);
      modbusServer.addHandler(5, writeCoilHandler);
});