diff --git a/client.js b/client.js index be63b56..e169b5e 100644 --- a/client.js +++ b/client.js @@ -4,6 +4,7 @@ var Binary = require('bufferlist/binary').Binary; var modbus = require('./modbus-stack'); var netStream = require('net').Stream; var FUNCTION_CODES = modbus.FUNCTION_CODES; +var BitArray = require('node-bitarray'); /* TCP MODBUS Client interface, as it's the most usual use-case. */ function Client () { @@ -54,32 +55,126 @@ Client.REQUESTS = { 5: function(address, value) { if (typeof value !== 'boolean') throw new Error('"Write Single Coil" expects a \'boolean\' value'); return putTwoWord16be(address, value ? 0xff00 : 0x0000); + }, + // WRITE_SINGLE_REGISTER + 6: putTwoWord16be, + + // WRITE_MULTIPLE_COILS + 15: function(address, values) { + if(values.length < 1 || values.length > 1968) { + throw new Error('"Write Multiple Coils" expects 1 to 1968 registers'); + } + + values.map( + function(val) { + if (typeof val !== 'boolean') throw new Error('"Write Multiple Coils" expects \'boolean\' values'); + return val ? 1 : 0; + } + ) + + request = Put() + .word16be(address) + .word16be(values.length) + .word8(Math.ceil(values.length/8)); + + // We have to reverse each 8 bits + while(values.length > 0) { + request.put(BitArray.toBuffer( + values.splice(0,8) + .reverse() // The LSB of the first data byte contains the output addressed in the query. + )); + } + + return request.buffer(); + }, + + // WRITE_MULTIPLE_REGISTERS + 16: function(address, values) { + if(values.length < 1 || values.length > 123) { + throw new Error('"Write Multiple Registers" expects 1 to 123 registers'); + } + + request = Put() + .word16be(address) + .word16be(values.length) + .word8(values.length*2); + + for(var i=0; i= 1.0.1", "bufferlist": ">= 0.0.6", - "put": "*" + "put": "*", + "node-bitarray": ">= 0.0.2" }, "devDependencies": { "colors": ">= 0.3.0", @@ -28,4 +29,4 @@ "files": [ "" ] -} \ No newline at end of file +} diff --git a/server.js b/server.js index 69845e1..389a99f 100644 --- a/server.js +++ b/server.js @@ -5,6 +5,7 @@ var Binary = require('bufferlist/binary').Binary; var modbus = require('./modbus-stack'); var FUNCTION_CODES = modbus.FUNCTION_CODES; + /* Streamlined TCP MODBUS server class. Can be used to respond to MODBUS requests * from TCP clients. `handlers` can be a function which is invoked for every * "request" event, or an Object with keys being the Function Codes your server