servers/servertcp.js
/**
 * Helper function for creating callback functions.
 *
 * @param {int} unitID - Id of the requesting unit
 * @param {int} functionCode - a modbus function code
 * @param {function} sockWriter - write buffer (or error) to tcp socket
 * @returns {function} - a callback function
 * @private
 */
Helper function for creating callback functions.
Helper function for creating callback functions .
function _callbackFactory(unitID, functionCode, sockWriter) {
    return function cb(err, responseBuffer) {
        var crc;
        if (err) {
            var errorCode = 0x04; 
            if (!isNaN(err.modbusErrorCode)) {
                errorCode = err.modbusErrorCode;
            }
            functionCode = parseInt(functionCode) | 0x80;
            responseBuffer = Buffer.alloc(3 + 2);
            responseBuffer.writeUInt8(errorCode, 2);
            _serverDebug("error processing response", unitID, functionCode);
        }
        if (!responseBuffer) {
            _serverDebug("no response buffer", unitID, functionCode);
            return sockWriter(null, responseBuffer);
        }
        responseBuffer.writeUInt8(unitID, 0);
        responseBuffer.writeUInt8(functionCode, 1);
        crc = crc16(responseBuffer.slice(0, -2));
        responseBuffer.writeUInt16LE(crc, responseBuffer.length - 2);
        _serverDebug("server response", unitID, functionCode, responseBuffer);
        return sockWriter(null, responseBuffer);
    };
}
function _callbackFactory ( unitID , functionCode , sockWriter ) { return function cb ( err , responseBuffer ) { var crc ; if ( err ) { var errorCode = 0x04 ; if ( ! isNaN ( err . modbusErrorCode ) ) { errorCode = err . modbusErrorCode ; } functionCode = parseInt ( functionCode ) | 0x80 ; responseBuffer = Buffer . alloc ( 3 + 2 ) ; responseBuffer . writeUInt8 ( errorCode , 2 ) ; _serverDebug ( "error processing response" , unitID , functionCode ) ; } if ( ! responseBuffer ) { _serverDebug ( "no response buffer" , unitID , functionCode ) ; return sockWriter ( null , responseBuffer ) ; } responseBuffer . writeUInt8 ( unitID , 0 ) ; responseBuffer . writeUInt8 ( functionCode , 1 ) ; crc = crc16 ( responseBuffer . slice ( 0 , - 2 ) ) ; responseBuffer . writeUInt16LE ( crc , responseBuffer . length - 2 ) ; _serverDebug ( "server response" , unitID , functionCode , responseBuffer ) ; return sockWriter ( null , responseBuffer ) ; } ; }
Helper function for creating callback functions.
Helper function for creating callback functions .
// If we have an error. // slave device failure // Set an error response // If we do not have a responseBuffer // add unit number and function code // Add crc // Call callback function