Socket
Socket
Sign inDemoInstall

node-modbus

Package Overview
Dependencies
178
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.0.1 to 4.2.0

node-modbus/maps/handler/client/ReadCoils.js.map

19

CHANGELOG.md

@@ -5,20 +5,9 @@ # Change Log

<a name="4.0.1"></a>
## [4.0.1](https://github.com/biancode/node-modbus/compare/v4.0.1-beta.0...v4.0.1) (2017-09-26)
<a name="4.2.0"></a>
# [4.2.0](https://github.com/biancode/node-modbus/compare/v4.1.0...v4.2.0) (2018-02-07)
<a name="4.0.1-beta.0"></a>
## [4.0.1-beta.0](https://github.com/biancode/node-modbus/compare/v4.0.1-alpha.0...v4.0.1-beta.0) (2017-09-26)
# Change Log
### Bug Fixes
* **client-core:** Rejecting promises when cleaning reqFifo. Prevents unresolved promises, memory leaks, and helps the consuming objects maintain flow in case of errors. ([50d29cc](https://github.com/biancode/node-modbus/commit/50d29cc))
* **client-core:** Rejects command promises if client is not in ready state. Prevents unresolved promises, memory leaks, and helps the object consuming the client maintain flow in case of errors. ([4949ac5](https://github.com/biancode/node-modbus/commit/4949ac5))
* **tcp-client:** Ensures state is ready when connection complete event emites, to allow consuming objects to to start firing commands on connect, without getting rejected from the check that ensures state is 'ready' later on ([05349ba](https://github.com/biancode/node-modbus/commit/05349ba))
<a name="4.0.1-alpha.0"></a>
## 4.0.1-alpha.0 (2017-09-26)
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

@@ -1,78 +0,2 @@

/**
* Modbus client read.
* @module ModbusClientReadCoils
*/
'use strict'
let Stampit = require('stampit')
let Promise = require('bluebird')
module.exports = Stampit()
.init(function () {
let init = function () {
this.addResponseHandler(1, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling read coils response.')
this.log.debug('on read coils got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug(' request: ' + JSON.stringify(request))
if (pdu.length < 2) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
let byteCount = pdu.readUInt8(1)
let resp = {
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
coils: []
}
if (fc !== 1) {
request.defer.reject()
return
}
let cntr = 0
let h = 1
let cur = 0
for (let i = 0; i < byteCount; i += 1) {
h = 1
cur = pdu.readUInt8(2 + i)
for (let j = 0; j < 8; j += 1) {
resp.coils[cntr] = (cur & h) > 0
h = h << 1
cntr += 1
}
}
request.defer.resolve(resp)
}.bind(this)
/**
* Reading coils with FC1.
* @param start
* @param quantity
*/
this.readCoils = function (start, quantity) {
return new Promise(function (resolve, reject) {
let fc = 1
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc, 0)
pdu.writeUInt16BE(start, 1)
pdu.writeUInt16BE(quantity, 3)
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var Stampit=require("stampit"),Promise=require("bluebird");module.exports=Stampit().init(function(){var e=function(){this.addResponseHandler(1,t)}.bind(this),t=function(e,t){if(this.log.debug("handling read coils response."),this.log.debug("on read coils got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug(" request: "+JSON.stringify(t)),e.length<2)t.defer.reject(new Error("PDU length less than two"));else{var r=e.readUInt8(0),i=e.readUInt8(1),n={fc:r,byteCount:i,payload:e.slice(2),coils:[]};if(1===r){for(var s=0,o=1,l=0,d=0;d<i;d+=1){o=1,l=e.readUInt8(2+d);for(var a=0;a<8;a+=1)n.coils[s]=(l&o)>0,o<<=1,s+=1}t.defer.resolve(n)}else t.defer.reject(new Error("FC "+r+" is not valid - FC1 is expected"))}}.bind(this);this.readCoils=function(e,t){return new Promise(function(r,i){var n=Buffer.allocUnsafe(5);n.writeUInt8(1,0),n.writeUInt16BE(e,1),n.writeUInt16BE(t,3),this.queueRequest(1,n,{resolve:r,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/ReadCoils.js.map

@@ -1,77 +0,2 @@

/**
* Modbus client read discrete inputs.
* @module ModbusClientReadDiscreteInputs
*/
'use strict'
let stampit = require('stampit')
let Promise = require('bluebird')
module.exports = stampit()
.init(function () {
let init = function () {
this.addResponseHandler(2, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling read discrete inputs response.')
this.log.debug('on read discrete inputs got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 2) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 2) {
request.defer.reject()
return
}
let byteCount = pdu.readUInt8(1)
let cntr = 0
let resp = {
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
coils: []
}
let h = 1
let cur = 0
for (let i = 0; i < byteCount; i += 1) {
h = 1
cur = pdu.readUInt8(2 + i)
for (let j = 0; j < 8; j += 1) {
resp.coils[cntr] = (cur & h) > 0
h = h << 1
cntr += 1
}
}
request.defer.resolve(resp)
}.bind(this)
this.readDiscreteInputs = function (start, quantity) {
return new Promise(function (resolve, reject) {
let fc = 2
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc)
pdu.writeUInt16BE(start, 1)
pdu.writeUInt16BE(quantity, 3)
if (quantity > 2000) {
reject()
return
}
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var stampit=require("stampit"),Promise=require("bluebird");module.exports=stampit().init(function(){var e=function(){this.addResponseHandler(2,t)}.bind(this),t=function(e,t){if(this.log.debug("handling read discrete inputs response."),this.log.debug("on read discrete inputs got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<2)t.defer.reject(new Error("PDU length less than two"));else{var r=e.readUInt8(0);if(2===r){for(var i=e.readUInt8(1),n=0,s={fc:r,byteCount:i,payload:e.slice(2),coils:[]},o=1,d=0,a=0;a<i;a+=1){o=1,d=e.readUInt8(2+a);for(var u=0;u<8;u+=1)s.coils[n]=(d&o)>0,o<<=1,n+=1}t.defer.resolve(s)}else t.defer.reject(new Error("FC "+r+" is not valid - FC2 is expected"))}}.bind(this);this.readDiscreteInputs=function(e,t){return new Promise(function(r,i){var n=Buffer.allocUnsafe(5);n.writeUInt8(2),n.writeUInt16BE(e,1),n.writeUInt16BE(t,3),t>2e3?i():this.queueRequest(2,n,{resolve:r,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/ReadDiscreteInputs.js.map

@@ -1,63 +0,2 @@

/**
* Modbus client read holding registers.
* @module ModbusClientReadHoldingRegisters
*/
'use strict'
let Stampit = require('stampit')
let Promise = require('bluebird')
module.exports = Stampit()
.init(function () {
let init = function () {
this.addResponseHandler(3, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling read holding registers response.')
this.log.debug('on read holding registers got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 2) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 3) {
request.defer.reject()
return
}
let byteCount = pdu.readUInt8(1)
let resp = {
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
register: []
}
let registerCount = byteCount / 2
for (let i = 0; i < registerCount; i += 1) {
resp.register.push(pdu.readUInt16BE(2 + (i * 2)))
}
request.defer.resolve(resp)
}.bind(this)
this.readHoldingRegisters = function (start, quantity) {
return new Promise(function (resolve, reject) {
let fc = 3
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc)
pdu.writeUInt16BE(start, 1)
pdu.writeUInt16BE(quantity, 3)
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var Stampit=require("stampit"),Promise=require("bluebird");module.exports=Stampit().init(function(){var e=function(){this.addResponseHandler(3,t)}.bind(this),t=function(e,t){if(this.log.debug("handling read holding registers response."),this.log.debug("on read holding registers got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<2)t.defer.reject(new Error("PDU length less than two"));else{var r=e.readUInt8(0);if(3===r){for(var i=e.readUInt8(1),n={fc:r,byteCount:i,payload:e.slice(2),register:[]},s=i/2,o=0;o<s;o+=1)n.register.push(e.readUInt16BE(2+2*o));t.defer.resolve(n)}else t.defer.reject(new Error("FC "+r+" is not valid - FC3 is expected"))}}.bind(this);this.readHoldingRegisters=function(e,t){return new Promise(function(r,i){var n=Buffer.allocUnsafe(5);n.writeUInt8(3),n.writeUInt16BE(e,1),n.writeUInt16BE(t,3),this.queueRequest(3,n,{resolve:r,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/ReadHoldingRegisters.js.map

@@ -1,63 +0,2 @@

/**
* Modbus client read inputs registers.
* @module ModbusClientReadInputRegisters
*/
'use strict'
let Stampit = require('stampit')
let Promise = require('bluebird')
module.exports = Stampit()
.init(function () {
let init = function () {
this.addResponseHandler(4, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling read input registers response.')
this.log.debug('on read input registers got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 2) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 4) {
request.defer.reject()
return
}
let byteCount = pdu.readUInt8(1)
let resp = {
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
register: []
}
let registerCount = byteCount / 2
for (let i = 0; i < registerCount; i += 1) {
resp.register.push(pdu.readUInt16BE(2 + (i * 2)))
}
request.defer.resolve(resp)
}.bind(this)
this.readInputRegisters = function (start, quantity) {
return new Promise(function (resolve, reject) {
let fc = 4
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc)
pdu.writeUInt16BE(start, 1)
pdu.writeUInt16BE(quantity, 3)
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var Stampit=require("stampit"),Promise=require("bluebird");module.exports=Stampit().init(function(){var e=function(){this.addResponseHandler(4,t)}.bind(this),t=function(e,t){if(this.log.debug("handling read input registers response."),this.log.debug("on read input registers got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<2)t.defer.reject(new Error("PDU length less than two"));else{var r=e.readUInt8(0);if(4===r){for(var i=e.readUInt8(1),n={fc:r,byteCount:i,payload:e.slice(2),register:[]},s=i/2,o=0;o<s;o+=1)n.register.push(e.readUInt16BE(2+2*o));t.defer.resolve(n)}else t.defer.reject(new Error("FC "+r+" is not valid - FC4 is expected"))}}.bind(this);this.readInputRegisters=function(e,t){return new Promise(function(r,i){var n=Buffer.allocUnsafe(5);n.writeUInt8(4),n.writeUInt16BE(e,1),n.writeUInt16BE(t,3),this.queueRequest(4,n,{resolve:r,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/ReadInputRegisters.js.map

@@ -1,91 +0,2 @@

/**
* Modbus client write multiple coils.
* @module ModbusClientWriteMultipleCoils
*/
'use strict'
let stampit = require('stampit')
let Promise = require('bluebird')
module.exports = stampit()
.init(function () {
let init = function () {
this.addResponseHandler(15, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling multiple coils response.')
this.log.debug('on write multiple coils got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 5) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 15) {
request.defer.reject()
return
}
let startAddress = pdu.readUInt16BE(1)
let quantity = pdu.readUInt16BE(3)
let resp = {
fc: fc,
startAddress: startAddress,
quantity: quantity
}
request.defer.resolve(resp)
}.bind(this)
this.writeMultipleCoils = function (startAddress, coils, N) {
return new Promise(function (resolve, reject) {
let fc = 15
let basePdu = Buffer.allocUnsafe(6)
let pdu
basePdu.writeUInt8(fc, 0)
basePdu.writeUInt16BE(startAddress, 1)
if (coils instanceof Buffer) {
basePdu.writeUInt16BE(N, 3)
basePdu.writeUInt8(coils.length, 5)
pdu = Buffer.concat([basePdu, coils])
} else if (coils instanceof Array) {
if (coils.length > 1968) {
reject()
return
}
let byteCount = Math.ceil(coils.length / 8)
let curByte = 0
let curByteIdx = 0
let cntr = 0
let payloadPdu = Buffer.allocUnsafe(byteCount)
basePdu.writeUInt16BE(coils.length, 3)
basePdu.writeUInt8(byteCount, 5)
for (let i = 0; i < coils.length; i += 1) {
curByte += coils[i] ? Math.pow(2, cntr) : 0
cntr = (cntr + 1) % 8
if (cntr === 0 || i === coils.length - 1) {
payloadPdu.writeUInt8(curByte, curByteIdx)
curByteIdx = curByteIdx + 1
curByte = 0
}
}
pdu = Buffer.concat([basePdu, payloadPdu])
}
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var stampit=require("stampit"),Promise=require("bluebird");module.exports=stampit().init(function(){var e=function(){this.addResponseHandler(15,t)}.bind(this),t=function(e,t){if(this.log.debug("handling multiple coils response."),this.log.debug("on write multiple coils got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<5)t.defer.reject(new Error("PDU length less than five"));else{var i=e.readUInt8(0);if(15===i){var r={fc:i,startAddress:e.readUInt16BE(1),quantity:e.readUInt16BE(3)};t.defer.resolve(r)}else t.defer.reject(new Error("FC "+i+" is not valid - FC15 is expected"))}}.bind(this);this.writeMultipleCoils=function(e,t,i){return new Promise(function(r,n){var s=Buffer.allocUnsafe(6),l=void 0;if(s.writeUInt8(15,0),s.writeUInt16BE(e,1),t instanceof Buffer)s.writeUInt16BE(i,3),s.writeUInt8(t.length,5),l=Buffer.concat([s,t]);else if(t instanceof Array){if(t.length>1968)return void n();var o=Math.ceil(t.length/8),f=0,a=0,u=0,d=Buffer.allocUnsafe(o);s.writeUInt16BE(t.length,3),s.writeUInt8(o,5);for(var h=0;h<t.length;h+=1)f+=t[h]?Math.pow(2,u):0,0!==(u=(u+1)%8)&&h!==t.length-1||(d.writeUInt8(f,a),a+=1,f=0);l=Buffer.concat([s,d])}this.queueRequest(15,l,{resolve:r,reject:n})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/WriteMultipleCoils.js.map

@@ -1,88 +0,2 @@

/**
* Modbus client write multiple registers.
* @module ModbusClientWriteRegisters
*/
'use strict'
let stampit = require('stampit')
let Promise = require('bluebird')
module.exports = stampit()
.init(function () {
let init = function () {
this.addResponseHandler(16, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling multiple registers response.')
this.log.debug('on write multiple registers got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 5) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 16) {
request.defer.reject()
return
}
let startAddress = pdu.readUInt16BE(1)
let quantity = pdu.readUInt16BE(3)
let resp = {
fc: fc,
startAddress: startAddress,
quantity: quantity
}
request.defer.resolve(resp)
}.bind(this)
this.writeMultipleRegisters = function (startAddress, register) {
return new Promise(function (resolve, reject) {
let fc = 16
let basePdu = Buffer.allocUnsafe(6)
let pdu
basePdu.writeUInt8(fc)
basePdu.writeUInt16BE(startAddress, 1)
if (register instanceof Buffer) {
if (register.length / 2 > 0x007b) {
reject()
}
basePdu.writeUInt16BE(register.length / 2, 3)
basePdu.writeUInt8(register.length, 5)
pdu = Buffer.concat([basePdu, register])
} else if (register instanceof Array) {
if (register.length > 0x007b) {
reject()
return
}
let byteCount = Math.ceil(register.length * 2)
let payloadPdu = Buffer.allocUnsafe(byteCount)
basePdu.writeUInt16BE(register.length, 3)
basePdu.writeUInt8(byteCount, 5)
for (let i = 0; i < register.length; i += 1) {
payloadPdu.writeUInt16BE(register[i], 2 * i)
}
pdu = Buffer.concat([basePdu, payloadPdu])
} else {
reject()
return
}
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var stampit=require("stampit"),Promise=require("bluebird");module.exports=stampit().init(function(){var e=function(){this.addResponseHandler(16,t)}.bind(this),t=function(e,t){if(this.log.debug("handling multiple registers response."),this.log.debug("on write multiple registers got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<5)t.defer.reject(new Error("PDU length less than five"));else{var r=e.readUInt8(0);if(16===r){var i={fc:r,startAddress:e.readUInt16BE(1),quantity:e.readUInt16BE(3)};t.defer.resolve(i)}else t.defer.reject(new Error("FC "+r+" is not valid - FC16 is expected"))}}.bind(this);this.writeMultipleRegisters=function(e,t){return new Promise(function(r,i){var n=Buffer.allocUnsafe(6),s=void 0;if(n.writeUInt8(16),n.writeUInt16BE(e,1),t instanceof Buffer)t.length/2>123&&i(),n.writeUInt16BE(t.length/2,3),n.writeUInt8(t.length,5),s=Buffer.concat([n,t]);else{if(!(t instanceof Array))return void i();if(t.length>123)return void i();var l=Math.ceil(2*t.length),f=Buffer.allocUnsafe(l);n.writeUInt16BE(t.length,3),n.writeUInt8(l,5);for(var o=0;o<t.length;o+=1)f.writeUInt16BE(t[o],2*o);s=Buffer.concat([n,f])}this.queueRequest(16,s,{resolve:r,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/WriteMultipleRegisters.js.map

@@ -1,58 +0,2 @@

/**
* Modbus client write single coil.
* @module ModbusClientWriteCoil
*/
'use strict'
let Stampit = require('stampit')
let Promise = require('bluebird')
module.exports = Stampit()
.init(function () {
let init = function () {
this.addResponseHandler(5, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling write single coil response.')
this.log.debug('on write single coil got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 5) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 5) {
request.defer.reject()
return
}
let outputAddress = pdu.readUInt16BE(1)
let outputValue = pdu.readUInt16BE(3)
let resp = {
fc: fc,
outputAddress: outputAddress,
outputValue: outputValue === 0x0000 ? false : outputValue === 0xFF00 ? true : undefined
}
request.defer.resolve(resp)
}.bind(this)
this.writeSingleCoil = function (address, value) {
return new Promise(function (resolve, reject) {
let fc = 5
let payload = (value instanceof Buffer) ? (value.readUInt8(0) > 0) : value
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc, 0)
pdu.writeUInt16BE(address, 1)
pdu.writeUInt16BE(payload ? 0xff00 : 0x0000, 3)
this.queueRequest(fc, pdu, { resolve: resolve, reject: reject })
}.bind(this))
}
init()
})
"use strict";var Stampit=require("stampit"),Promise=require("bluebird");module.exports=Stampit().init(function(){var e=function(){this.addResponseHandler(5,t)}.bind(this),t=function(e,t){if(this.log.debug("handling write single coil response."),this.log.debug("on write single coil got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(t)),e.length<5)t.defer.reject(new Error("PDU length less than five"));else{var i=e.readUInt8(0);if(5===i){var r=e.readUInt16BE(1),n=e.readUInt16BE(3),s={fc:i,outputAddress:r,outputValue:0!==n&&(65280===n||void 0)};t.defer.resolve(s)}else t.defer.reject(new Error("FC"+i+" is not valid - FC5 is expected"))}}.bind(this);this.writeSingleCoil=function(e,t){return new Promise(function(i,r){var n=t instanceof Buffer?t.readUInt8(0)>0:t,s=Buffer.allocUnsafe(5);s.writeUInt8(5,0),s.writeUInt16BE(e,1),s.writeUInt16BE(n?65280:0,3),this.queueRequest(5,s,{resolve:i,reject:r})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/WriteSingleCoil.js.map

@@ -1,59 +0,2 @@

/**
* Modbus client write single register.
* @module ModbusClientWriteRegister
*/
'use strict'
let Stampit = require('stampit')
let Promise = require('bluebird')
module.exports = Stampit()
.init(function () {
let init = function () {
this.addResponseHandler(6, onResponse)
}.bind(this)
let onResponse = function (pdu, request) {
this.log.debug('handling write single register response.')
this.log.debug('on write single register got PDU: ' + JSON.stringify(pdu) + ' pdu.length:' + pdu.length)
this.log.debug('request: ' + JSON.stringify(request))
if (pdu.length < 5) {
request.defer.reject()
return
}
let fc = pdu.readUInt8(0)
if (fc !== 6) {
request.defer.reject()
return
}
let registerAddress = pdu.readUInt16BE(1)
let registerValue = pdu.readUInt16BE(3)
let resp = {
fc: fc,
registerAddress: registerAddress,
registerValue: registerValue,
registerAddressRaw: pdu.slice(1, 3),
registerValueRaw: pdu.slice(3, 5)
}
request.defer.resolve(resp)
}.bind(this)
this.writeSingleRegister = function (address, value) {
return new Promise(function (resolve, reject) {
let fc = 6
let payload = (value instanceof Buffer) ? value.readUInt16BE(0) : value
let pdu = Buffer.allocUnsafe(5)
pdu.writeUInt8(fc, 0)
pdu.writeUInt16BE(address, 1)
pdu.writeUInt16BE(payload, 3)
this.queueRequest(fc, pdu, {resolve: resolve, reject: reject})
}.bind(this))
}
init()
})
"use strict";var Stampit=require("stampit"),Promise=require("bluebird");module.exports=Stampit().init(function(){var e=function(){this.addResponseHandler(6,r)}.bind(this),r=function(e,r){if(this.log.debug("handling write single register response."),this.log.debug("on write single register got PDU: "+JSON.stringify(e)+" pdu.length:"+e.length),this.log.debug("request: "+JSON.stringify(r)),e.length<5)r.defer.reject(new Error("PDU length less than five"));else{var t=e.readUInt8(0);if(6===t){var i={fc:t,registerAddress:e.readUInt16BE(1),registerValue:e.readUInt16BE(3),registerAddressRaw:e.slice(1,3),registerValueRaw:e.slice(3,5)};r.defer.resolve(i)}else r.defer.reject(new Error("FC "+t+" is not valid - FC6 is expected"))}}.bind(this);this.writeSingleRegister=function(e,r){return new Promise(function(t,i){var s=r instanceof Buffer?r.readUInt16BE(0):r,n=Buffer.allocUnsafe(5);n.writeUInt8(6,0),n.writeUInt16BE(e,1),n.writeUInt16BE(s,3),this.queueRequest(6,n,{resolve:t,reject:i})}.bind(this))},e()});
//# sourceMappingURL=../../maps/handler/client/WriteSingleRegister.js.map

@@ -1,79 +0,2 @@

/**
* Modbus server read.
* @module ModbusServerReadCoils
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating read coils request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(1, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling read coils request.')
if (pdu.length !== 5) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x81, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let quantity = pdu.readUInt16BE(3)
this.emit('readCoilsRequest', start, quantity)
let mem = this.getCoils()
if (start > mem.length * 8 || start + quantity > mem.length * 8) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x81, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let val = 0
let thisByteBitCount = 0
let byteIdx = 2
let byteCount = Math.ceil(quantity / 8)
let response = Buffer.allocUnsafe(2 + byteCount)
response.writeUInt8(0x01, 0)
response.writeUInt8(byteCount, 1)
for (let totalBitCount = start; totalBitCount < start + quantity; totalBitCount += 1) {
let buf = mem.readUInt8(Math.floor(totalBitCount / 8))
let mask = 1 << (totalBitCount % 8)
if (buf & mask) {
val += 1 << (thisByteBitCount % 8)
}
thisByteBitCount += 1
if (thisByteBitCount % 8 === 0 || totalBitCount === (start + quantity) - 1) {
response.writeUInt8(val, byteIdx)
val = 0; byteIdx = byteIdx + 1
}
}
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var t=function(){this.log.debug("initiating read coils request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(1,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling read coils request."),5!==t.length){var i=Buffer.allocUnsafe(2);return i.writeUInt8(129,0),i.writeUInt8(2,1),void e(i)}var r=t.readUInt16BE(1),n=t.readUInt16BE(3);this.emit("readCoilsRequest",r,n);var s=this.getCoils();if(r>8*s.length||r+n>8*s.length){var a=Buffer.allocUnsafe(2);return a.writeUInt8(129,0),a.writeUInt8(2,1),void e(a)}var l=0,o=0,u=2,h=Math.ceil(n/8),d=Buffer.allocUnsafe(2+h);d.writeUInt8(1,0),d.writeUInt8(h,1);for(var f=r;f<r+n;f+=1){s.readUInt8(Math.floor(f/8))&1<<f%8&&(l+=1<<o%8),(o+=1)%8!=0&&f!==r+n-1||(d.writeUInt8(l,u),l=0,u+=1)}e(d)}.bind(this),this.responseDelay)}.bind(this);t()});
//# sourceMappingURL=../../maps/handler/server/ReadCoils.js.map

@@ -1,88 +0,2 @@

/**
* Modbus server read discrete inputs.
* @module ModbusServerReadDiscreteInputs
*/
'use strict'
let stampit = require('stampit')
let handler = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating read discrete inputs request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(2, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling read discrete inputs request.')
if (pdu.length !== 5) {
this.log.debug('wrong pdu length.')
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x82, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let quantity = pdu.readUInt16BE(3)
this.emit('readDiscreteInputsRequest', start, quantity)
let mem = this.getInput()
if (start > mem.length * 8 || start + quantity > mem.length * 8) {
this.log.debug('wrong pdu length.')
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x82, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let val = 0
let thisByteBitCount = 0
let byteIdx = 2
let byteCount = Math.ceil(quantity / 8)
let response = Buffer.allocUnsafe(2 + byteCount)
response.writeUInt8(0x02, 0)
response.writeUInt8(byteCount, 1)
for (let totalBitCount = start; totalBitCount < start + quantity; totalBitCount += 1) {
let buf = mem.readUInt8(Math.floor(totalBitCount / 8))
let mask = 1 << (totalBitCount % 8)
if (buf & mask) {
val += 1 << (thisByteBitCount % 8)
}
thisByteBitCount += 1
if (thisByteBitCount % 8 === 0 || totalBitCount === (start + quantity) - 1) {
response.writeUInt8(val, byteIdx)
val = 0; byteIdx = byteIdx + 1
}
}
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
module.exports = handler
"use strict";var stampit=require("stampit"),handler=stampit().init(function(){var t=function(){this.log.debug("initiating read discrete inputs request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(2,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling read discrete inputs request."),5!==t.length){this.log.debug("wrong pdu length.");var i=Buffer.allocUnsafe(2);return i.writeUInt8(130,0),i.writeUInt8(2,1),void e(i)}var n=t.readUInt16BE(1),r=t.readUInt16BE(3);this.emit("readDiscreteInputsRequest",n,r);var s=this.getInput();if(n>8*s.length||n+r>8*s.length){this.log.debug("wrong pdu length.");var a=Buffer.allocUnsafe(2);return a.writeUInt8(130,0),a.writeUInt8(2,1),void e(a)}var u=0,l=0,d=2,h=Math.ceil(r/8),o=Buffer.allocUnsafe(2+h);o.writeUInt8(2,0),o.writeUInt8(h,1);for(var g=n;g<n+r;g+=1){s.readUInt8(Math.floor(g/8))&1<<g%8&&(u+=1<<l%8),(l+=1)%8!=0&&g!==n+r-1||(o.writeUInt8(u,d),u=0,d+=1)}e(o)}.bind(this),this.responseDelay)}.bind(this);t()});module.exports=handler;
//# sourceMappingURL=../../maps/handler/server/ReadDiscreteInputs.js.map

@@ -1,69 +0,2 @@

/**
* Modbus server read holding registers.
* @module ModbusServerReadHoldingRegisters
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating read holding registers request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(3, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling read holding registers request.')
if (pdu.length !== 5) {
this.log.debug('wrong pdu length.')
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x83, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let byteStart = start * 2
let quantity = pdu.readUInt16BE(3)
this.emit('readHoldingRegistersRequest', byteStart, quantity)
let mem = this.getHolding()
if (byteStart > mem.length || byteStart + (quantity * 2) > mem.length) {
this.log.debug('request outside register boundaries.')
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x83, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let head = Buffer.allocUnsafe(2)
head.writeUInt8(0x03, 0)
head.writeUInt8(quantity * 2, 1)
let response = Buffer.concat([head, mem.slice(byteStart, byteStart + quantity * 2)])
this.log.debug('finished read holding register request.')
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var e=function(){this.log.debug("initiating read holding registers request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(3,t)}.bind(this),t=function(e,t){setTimeout(function(){if(this.log.debug("handling read holding registers request."),5!==e.length){this.log.debug("wrong pdu length.");var i=Buffer.allocUnsafe(2);return i.writeUInt8(131,0),i.writeUInt8(2,1),void t(i)}var r=2*e.readUInt16BE(1),s=e.readUInt16BE(3);this.emit("readHoldingRegistersRequest",r,s);var n=this.getHolding();if(r>n.length||r+2*s>n.length){this.log.debug("request outside register boundaries.");var a=Buffer.allocUnsafe(2);return a.writeUInt8(131,0),a.writeUInt8(2,1),void t(a)}var d=Buffer.allocUnsafe(2);d.writeUInt8(3,0),d.writeUInt8(2*s,1);var o=Buffer.concat([d,n.slice(r,r+2*s)]);this.log.debug("finished read holding register request."),t(o)}.bind(this),this.responseDelay)}.bind(this);e()});
//# sourceMappingURL=../../maps/handler/server/ReadHoldingRegisters.js.map

@@ -1,63 +0,2 @@

/**
* Modbus server read inputs registers.
* @module ModbusServerReadInputRegisters
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating read input registers request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(4, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling read input registers request.')
if (pdu.length !== 5) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x84, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let byteStart = start * 2
let quantity = pdu.readUInt16BE(3)
this.emit('readInputRegistersRequest', byteStart, quantity)
let mem = this.getInput()
if (byteStart > mem.length || byteStart + (quantity * 2) > mem.length) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x84, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let head = Buffer.allocUnsafe(2)
head.writeUInt8(0x04, 0)
head.writeUInt8(quantity * 2, 1)
let response = Buffer.concat([head, mem.slice(byteStart, byteStart + quantity * 2)])
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var t=function(){this.log.debug("initiating read input registers request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(4,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling read input registers request."),5!==t.length){var i=Buffer.allocUnsafe(2);return i.writeUInt8(132,0),i.writeUInt8(2,1),void e(i)}var r=2*t.readUInt16BE(1),n=t.readUInt16BE(3);this.emit("readInputRegistersRequest",r,n);var s=this.getInput();if(r>s.length||r+2*n>s.length){var a=Buffer.allocUnsafe(2);return a.writeUInt8(132,0),a.writeUInt8(2,1),void e(a)}var u=Buffer.allocUnsafe(2);u.writeUInt8(4,0),u.writeUInt8(2*n,1);var l=Buffer.concat([u,s.slice(r,r+2*n)]);e(l)}.bind(this),this.responseDelay)}.bind(this);t()});
//# sourceMappingURL=../../maps/handler/server/ReadInputRegisters.js.map

@@ -1,92 +0,2 @@

/**
* Modbus server write multiple coils.
* @module ModbusServerWriteMultipleCoils
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating write multiple coils request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(15, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling write multiple coils request.')
if (pdu.length < 3) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x8F, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let quantity = pdu.readUInt16BE(3)
let byteCount = pdu.readUInt8(5)
this.emit('preWriteMultipleCoilsRequest', start, quantity, byteCount)
let mem = this.getCoils()
// error response
if (start > mem.length * 8 || start + quantity > mem.length * 8) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x8F, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let response = Buffer.allocUnsafe(5)
response.writeUInt8(0x0F, 0)
response.writeUInt16BE(start, 1)
response.writeUInt16BE(quantity, 3)
let oldValue
let newValue
let current = pdu.readUInt8(6 + 0)
let j = 0
for (let i = start; i < start + quantity; i += 1) {
// reading old value from the coils register
oldValue = mem.readUInt8(Math.floor(i / 8))
// apply new value
if (Math.pow(2, j % 8) & current) {
newValue = oldValue | Math.pow(2, i % 8)
} else {
newValue = oldValue & ~Math.pow(2, i % 8)
}
// write to buffer
mem.writeUInt8(newValue, Math.floor(i / 8))
// read new value from request pdu
j += 1
if (j % 8 === 0 && j < quantity) {
current = pdu.readUInt8(6 + Math.floor(j / 8))
}
}
this.emit('postWriteMultipleCoilsRequest', start, quantity, byteCount)
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var t=function(){this.log.debug("initiating write multiple coils request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(15,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling write multiple coils request."),t.length<3){var i=Buffer.allocUnsafe(2);return i.writeUInt8(143,0),i.writeUInt8(2,1),void e(i)}var r=t.readUInt16BE(1),n=t.readUInt16BE(3),s=t.readUInt8(5);this.emit("preWriteMultipleCoilsRequest",r,n,s);var a=this.getCoils();if(r>8*a.length||r+n>8*a.length){var o=Buffer.allocUnsafe(2);return o.writeUInt8(143,0),o.writeUInt8(2,1),void e(o)}var l=Buffer.allocUnsafe(5);l.writeUInt8(15,0),l.writeUInt16BE(r,1),l.writeUInt16BE(n,3);for(var u=void 0,h=void 0,d=t.readUInt8(6),f=0,U=r;U<r+n;U+=1)u=a.readUInt8(Math.floor(U/8)),h=Math.pow(2,f%8)&d?u|Math.pow(2,U%8):u&~Math.pow(2,U%8),a.writeUInt8(h,Math.floor(U/8)),(f+=1)%8==0&&f<n&&(d=t.readUInt8(6+Math.floor(f/8)));this.emit("postWriteMultipleCoilsRequest",r,n,s),e(l)}.bind(this),this.responseDelay)}.bind(this);t()});
//# sourceMappingURL=../../maps/handler/server/WriteMultipleCoils.js.map

@@ -1,75 +0,2 @@

/**
* Modbus server write multiple registers.
* @module ModbusServerWriteRegisters
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating write multiple registers request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(16, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling write multiple registers request.')
if (pdu.length < 3) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x90, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let start = pdu.readUInt16BE(1)
let byteStart = start * 2
let quantity = pdu.readUInt16BE(3)
let byteCount = pdu.readUInt8(5)
if (quantity > 0x007b) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x90, 0)
buf.writeUInt8(0x03, 1)
cb(buf)
return
}
this.emit('preWriteMultipleRegistersRequest', byteStart, quantity, byteCount)
let mem = this.getHolding()
if (byteStart > mem.length || byteStart + (quantity * 2) > mem.length) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x90, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let response = Buffer.allocUnsafe(5)
response.writeUInt8(0x10, 0)
response.writeUInt16BE(start, 1)
response.writeUInt16BE(quantity, 3)
pdu.copy(mem, byteStart, 6, 6 + byteCount)
this.emit('postWriteMultipleRegistersRequest', byteStart, quantity, byteCount)
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var t=function(){this.log.debug("initiating write multiple registers request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(16,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling write multiple registers request."),t.length<3){var i=Buffer.allocUnsafe(2);return i.writeUInt8(144,0),i.writeUInt8(2,1),void e(i)}var r=t.readUInt16BE(1),n=2*r,s=t.readUInt16BE(3),a=t.readUInt8(5);if(s>123){var l=Buffer.allocUnsafe(2);return l.writeUInt8(144,0),l.writeUInt8(3,1),void e(l)}this.emit("preWriteMultipleRegistersRequest",n,s,a);var u=this.getHolding();if(n>u.length||n+2*s>u.length){var o=Buffer.allocUnsafe(2);return o.writeUInt8(144,0),o.writeUInt8(2,1),void e(o)}var f=Buffer.allocUnsafe(5);f.writeUInt8(16,0),f.writeUInt16BE(r,1),f.writeUInt16BE(s,3),t.copy(u,n,6,6+a),this.emit("postWriteMultipleRegistersRequest",n,s,a),e(f)}.bind(this),this.responseDelay)}.bind(this);t()});
//# sourceMappingURL=../../maps/handler/server/WriteMultipleRegisters.js.map

@@ -1,83 +0,2 @@

/**
* Modbus server write single coil.
* @module ModbusServerWriteCoil
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating write single coil request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(5, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling write single coil request.')
if (pdu.length !== 5) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x85, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let address = pdu.readUInt16BE(1)
let value = !(pdu.readUInt16BE(3) === 0x0000)
if (pdu.readUInt16BE(3) !== 0x0000 && pdu.readUInt16BE(3) !== 0xFF00) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x85, 0)
buf.writeUInt8(0x03, 1)
cb(buf)
return
}
this.emit('preWriteSingleCoilRequest', address, value)
let mem = this.getCoils()
if (address > mem.length * 8) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x85, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let response = Buffer.allocUnsafe(5)
response.writeUInt8(5, 0)
response.writeUInt16BE(address, 1)
response.writeUInt16BE(value ? 0xFF00 : 0x0000, 3)
let oldValue = mem.readUInt8(Math.floor(address / 8))
let newValue
if (value) {
newValue = oldValue | Math.pow(2, address % 8)
} else {
newValue = oldValue & ~Math.pow(2, address % 8)
}
mem.writeUInt8(newValue, Math.floor(address / 8))
this.emit('postWriteSingleCoilRequest', address, value)
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var t=function(){this.log.debug("initiating write single coil request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(5,e)}.bind(this),e=function(t,e){setTimeout(function(){if(this.log.debug("handling write single coil request."),5!==t.length){var i=Buffer.allocUnsafe(2);return i.writeUInt8(133,0),i.writeUInt8(2,1),void e(i)}var r=t.readUInt16BE(1),n=!(0===t.readUInt16BE(3));if(0!==t.readUInt16BE(3)&&65280!==t.readUInt16BE(3)){var s=Buffer.allocUnsafe(2);return s.writeUInt8(133,0),s.writeUInt8(3,1),void e(s)}this.emit("preWriteSingleCoilRequest",r,n);var a=this.getCoils();if(r>8*a.length){var o=Buffer.allocUnsafe(2);return o.writeUInt8(133,0),o.writeUInt8(2,1),void e(o)}var l=Buffer.allocUnsafe(5);l.writeUInt8(5,0),l.writeUInt16BE(r,1),l.writeUInt16BE(n?65280:0,3);var u=a.readUInt8(Math.floor(r/8)),f=void 0;f=n?u|Math.pow(2,r%8):u&~Math.pow(2,r%8),a.writeUInt8(f,Math.floor(r/8)),this.emit("postWriteSingleCoilRequest",r,n),e(l)}.bind(this),this.responseDelay)}.bind(this);t()});
//# sourceMappingURL=../../maps/handler/server/WriteSingleCoil.js.map

@@ -1,66 +0,2 @@

/**
* Modbus server write single register.
* @module ModbusServerWriteRegister
*/
'use strict'
let stampit = require('stampit')
module.exports = stampit()
.init(function () {
let init = function () {
this.log.debug('initiating write single register request handler.')
if (!this.responseDelay) {
this.responseDelay = 0
}
this.setRequestHandler(6, onRequest)
}.bind(this)
let onRequest = function (pdu, cb) {
setTimeout(function () {
this.log.debug('handling write single register request.')
if (pdu.length !== 5) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x86, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let address = pdu.readUInt16BE(1)
let byteAddress = address * 2
let value = pdu.readUInt16BE(3)
this.emit('preWriteSingleRegisterRequest', byteAddress, value)
let mem = this.getHolding()
if (byteAddress > mem.length) {
let buf = Buffer.allocUnsafe(2)
buf.writeUInt8(0x86, 0)
buf.writeUInt8(0x02, 1)
cb(buf)
return
}
let response = Buffer.allocUnsafe(5)
response.writeUInt8(0x06)
response.writeUInt16BE(address, 1)
response.writeUInt16BE(value, 3)
mem.writeUInt16BE(value, byteAddress)
this.emit('postWriteSingleRegisterRequest', byteAddress, value)
cb(response)
}.bind(this), this.responseDelay)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit");module.exports=stampit().init(function(){var e=function(){this.log.debug("initiating write single register request handler."),this.responseDelay||(this.responseDelay=0),this.setRequestHandler(6,t)}.bind(this),t=function(e,t){setTimeout(function(){if(this.log.debug("handling write single register request."),5!==e.length){var i=Buffer.allocUnsafe(2);return i.writeUInt8(134,0),i.writeUInt8(2,1),void t(i)}var r=e.readUInt16BE(1),n=2*r,s=e.readUInt16BE(3);this.emit("preWriteSingleRegisterRequest",n,s);var a=this.getHolding();if(n>a.length){var l=Buffer.allocUnsafe(2);return l.writeUInt8(134,0),l.writeUInt8(2,1),void t(l)}var u=Buffer.allocUnsafe(5);u.writeUInt8(6),u.writeUInt16BE(r,1),u.writeUInt16BE(s,3),a.writeUInt16BE(s,n),this.emit("postWriteSingleRegisterRequest",n,s),t(u)}.bind(this),this.responseDelay)}.bind(this);e()});
//# sourceMappingURL=../../maps/handler/server/WriteSingleRegister.js.map

@@ -1,191 +0,2 @@

/**
* Modbus client core.
* @module ModbusCoreClient
*/
'use strict'
var stampit = require('stampit')
var logger = require('stampit-log')
var StateMachine = require('stampit-state-machine')
let ExceptionMessage = {
0x01: 'ILLEGAL FUNCTION',
0x02: 'ILLEGAL DATA ADDRESS',
0x03: 'ILLEGAL DATA VALUE',
0x04: 'SLAVE DEVICE FAILURE',
0x05: 'ACKNOWLEDGE',
0x06: 'SLAVE DEVICE BUSY',
0x08: 'MEMORY PARITY ERROR',
0x0A: 'GATEWAY PATH UNAVAILABLE',
0x0B: 'GATEWAY TARGET DEVICE FAILED TO RESPOND'
}
module.exports = stampit()
.refs({
'logLabel': 'ModbusCoreClient',
'logLevel': 'info',
'logEnabled': true
})
.compose(StateMachine)
.compose(logger)
.init(function () {
let responseHandler = {}
let currentRequest = null
this.reqFifo = []
let init = function () {
if (!this.timeout) {
this.timeout = 2000 // ms
}
if (!this.endianType) {
this.endianType = 'LITTLE'
}
if (this.logLevel) {
this.log.logLevel = this.logLevel
}
this.log.info('log level: ' + this.log.logLevel)
this.on('data', onData)
this.on('timeout', onTimeout)
this.on('newState_closed', onClosed)
}.bind(this)
let flush = function () {
if (this.reqFifo.length === 0) {
this.log.debug('Nothing in request pipe.')
return
} else {
this.log.debug(this.reqFifo.length + ' requests in request pipe.')
}
currentRequest = this.reqFifo.shift()
if (currentRequest && currentRequest.pdu) {
this.setState('waiting')
this.emit('send', currentRequest.pdu, setRequestTimeout)
this.log.debug('Data flushed.')
}
}.bind(this)
let setRequestTimeout = function () {
currentRequest.timeout = setTimeout(function () {
currentRequest.defer.reject({err: 'timeout'})
this.emit('trashCurrentRequest')
this.log.error('Request timed out after ' + this.timeout / 1000 + ' sec')
this.emit('timeout')
}.bind(this), this.timeout)
this.log.debug('set timeout of ' + this.timeout + ' ms on send to wait for data')
}.bind(this)
let onTimeout = function () {
// TODO: may here is something to be done
this.setState('ready')
}.bind(this)
let onClosed = function () {
if (currentRequest) {
this.log.debug('Clearing timeout of the current request.')
clearTimeout(currentRequest.timeout)
}
this.log.debug('Cleaning up request fifo.')
while (this.reqFifo.length) {
this.reqFifo.shift().defer.reject({err: 'Fifo cleanup'})
}
}.bind(this)
let handleErrorPDU = function (pdu) {
let errorCode = pdu.readUInt8(0)
// if error code is smaller than 0x80
// ths pdu describes no error
if (errorCode < 0x80) {
return false
}
// pdu describes an error
if (pdu.length < 2) {
currentRequest.defer.reject('PDU length ' + pdu.length + ' invalid')
return true
}
let exceptionCode = pdu.readUInt8(1)
let message = ExceptionMessage[exceptionCode]
let err = {
errorCode: errorCode,
exceptionCode: exceptionCode,
message: message
}
// call the desired deferred
currentRequest.defer.reject(err)
return true
}
/**
* Handle the incoming data, cut out the mbap
* packet and send the pdu to the listener
*/
let onData = function (pdu) {
if (!currentRequest) {
this.log.debug('No current request.')
return
}
clearTimeout(currentRequest.timeout)
this.log.debug('received data and clean timeout PDU: ' + JSON.stringify(pdu))
// check pdu for error
if (handleErrorPDU(pdu)) {
this.log.debug('Received pdu describes an error.')
currentRequest = null
this.setState('ready')
return
}
// handle pdu
let handler = responseHandler[currentRequest.fc]
if (!handler) {
this.log.debug('Found not handler for fc', currentRequest.fc)
throw new Error('No handler implemented for fc ' + currentRequest.fc)
}
// TODO: here is may a problem - if we set here error it stay on error, but it should become ready again later
handler(pdu, currentRequest)
this.setState('ready')
}.bind(this)
this.addResponseHandler = function (fc, handler) {
responseHandler[fc] = handler
return this
}.bind(this)
this.queueRequest = function (fc, pdu, defer) {
let req = {
fc: fc,
defer: defer,
pdu: pdu
}
if (this.inState('ready')) {
/* fill reqFifo just in ready state
- think about running machines
- recorded data sending later and very fast - because it is in queue - can damage machines
*/
this.reqFifo.push(req)
flush()
} else {
this.log.warn('not ready to transport data state:' + this.getState())
if (this.inState('closed')) {
this.emit('error', 'connection closed')
}
defer.reject({err: 'modbus client not in "ready" state'})
}
}
init()
})
"use strict";var stampit=require("stampit"),logger=require("stampit-log"),StateMachine=require("stampit-state-machine"),ExceptionMessage={1:"ILLEGAL FUNCTION",2:"ILLEGAL DATA ADDRESS",3:"ILLEGAL DATA VALUE",4:"SLAVE DEVICE FAILURE",5:"ACKNOWLEDGE",6:"SLAVE DEVICE BUSY",8:"MEMORY PARITY ERROR",10:"GATEWAY PATH UNAVAILABLE",11:"GATEWAY TARGET DEVICE FAILED TO RESPOND"};module.exports=stampit().refs({logLabel:"ModbusCoreClient",logLevel:"info",logEnabled:!0}).compose(StateMachine).compose(logger).init(function(){var e={},t=null;this.reqFifo=[];var i=function(){this.timeout||(this.timeout=2e3),this.endianType||(this.endianType="LITTLE"),this.logLevel&&(this.log.logLevel=this.logLevel),this.log.info("log level: "+this.log.logLevel),this.on("data",u),this.on("timeout",r),this.on("newState_closed",n)}.bind(this),o=function(){0!==this.reqFifo.length?(this.log.debug(this.reqFifo.length+" requests in request pipe."),(t=this.reqFifo.shift())&&t.pdu&&(this.setState("waiting"),this.emit("send",t.pdu,s),this.log.debug("Data flushed."))):this.log.debug("Nothing in request pipe.")}.bind(this),s=function(){t.timeout=setTimeout(function(){t.defer.reject({err:"timeout"}),this.emit("trashCurrentRequest"),this.log.error("Request timed out after "+this.timeout/1e3+" sec"),this.emit("timeout")}.bind(this),this.timeout),this.log.debug("set timeout of "+this.timeout+" ms on send to wait for data")}.bind(this),r=function(){this.setState("ready")}.bind(this),n=function(){for(t&&(this.log.debug("Clearing timeout of the current request."),clearTimeout(t.timeout)),this.log.debug("Cleaning up request fifo.");this.reqFifo.length;)this.reqFifo.shift().defer.reject({err:"Fifo cleanup"})}.bind(this),u=function(i){if(t){if(clearTimeout(t.timeout),this.log.debug("received data and clean timeout PDU: "+JSON.stringify(i)),function(e){var i=e.readUInt8(0);if(i<128)return!1;if(e.length<2)return t.defer.reject("PDU length "+e.length+" invalid"),!0;var o=e.readUInt8(1),s={errorCode:i,exceptionCode:o,message:ExceptionMessage[o]};return t.defer.reject(s),!0}(i))return this.log.debug("Received pdu describes an error."),t=null,void this.setState("ready");var o=e[t.fc];if(!o)throw this.log.debug("Found not handler for fc",t.fc),new Error("No handler implemented for fc "+t.fc);o(i,t),this.setState("ready")}else this.log.debug("No current request.")}.bind(this);this.addResponseHandler=function(t,i){return e[t]=i,this}.bind(this),this.queueRequest=function(e,t,i){var s={fc:e,defer:i,pdu:t};this.inState("ready")?(this.reqFifo.push(s),o()):(this.log.warn("not ready to transport data state:"+this.getState()),this.inState("closed")&&this.emit("error","connection closed"),i.reject({err:'modbus client not in "ready" state'}))},i()});
//# sourceMappingURL=maps/modbus-client-core.js.map

@@ -1,218 +0,2 @@

/**
* Modbus Serial client.
* @module ModbusSerialClient
*/
'use strict'
let stampit = require('stampit')
let ModbusCore = require('./modbus-client-core.js')
module.exports = stampit()
.compose(ModbusCore)
.refs({
'logLabel': 'ModbusSerialClient'
})
.init(function () {
let SerialPort = require('serialport')
let crc = require('crc')
let serialport
let receiveBuffer = Buffer.alloc(256)
let receivedBytes = 0
let expectedBytes = 0
let crcBytes = 2
let minLength = 0x80
let exeptionMessageLength = 5
if (!this.connectionDelay) {
if (process.platform === 'win32') {
this.connectionDelay = 500 // ms
} else {
this.connectionDelay = 250 // ms
}
}
let init = function () {
this.setState('init')
if (!this.connectionType) { this.connectionType = 'RTU' }
if (!this.portName) { throw new Error('No portname.') }
if (!this.baudRate) { this.baudRate = 9600 }
if (!this.dataBits) { this.dataBits = 8 }
if (!this.stopBits) { this.stopBits = 1 }
if (!this.parity) { this.parity = 'none' }
// TODO: flowControl - ['xon', 'xoff', 'xany', 'rtscts']
// TODO: settings - ['brk', 'cts', 'dtr', 'dts', 'rts']
if (this.injectedSerialport) {
serialport = this.injectedSerialport
this.log.debug('we are working on a mockup serialport')
} else {
setTimeout(openSerialPort, this.connectionDelay)
}
this.log.debug('set on send method')
this.on('send', onSend)
}.bind(this)
let openSerialPort = function () {
// some delay needed on windows systems serial reconnect
if (this.connectionType === 'ASCII') {
serialport = new SerialPort(this.portName, {
baudRate: this.baudRate,
parity: this.parity,
dataBits: this.dataBits,
stopBits: this.stopBits,
parser: (this.endianType === 'BIG') ? SerialPort.parsers.byteDelimiter([13, 10]) : SerialPort.parsers.byteDelimiter([10, 13])
})
} else {
serialport = new SerialPort(this.portName, {
baudRate: this.baudRate,
parity: this.parity,
dataBits: this.dataBits,
stopBits: this.stopBits
})
}
this.log.debug('serialport settings: ' + JSON.stringify(serialport.options))
serialport.on('open', onOpen)
serialport.on('disconnect', onDisconnect)
serialport.on('close', onClose)
serialport.on('data', onData)
serialport.on('error', onError)
}.bind(this)
let onOpen = function () {
this.setState('ready')
}.bind(this)
let onDisconnect = function (err) {
this.setState('disconnected')
if (err) {
this.emit('error', err)
}
}.bind(this)
let onClose = function () {
this.setState('closed')
}.bind(this)
let onData = function (pdu) {
if (pdu.length !== 0) { // at least one byte has been received
this.log.debug('received serial data ' + JSON.stringify(pdu))
if ((pdu.length + receivedBytes) <= receiveBuffer.length) {
if (receivedBytes === 0 && pdu && pdu[0] === 0) {
this.log.debug('we got a broadcast from master')
this.resetReceiveBuffer()
return
}
pdu.copy(receiveBuffer, receivedBytes, 0)
receivedBytes += pdu.length
if (receivedBytes >= exeptionMessageLength) {
if (receivedBytes === exeptionMessageLength) {
if (receiveBuffer[1] >= minLength &&
crc.crc16modbus(receiveBuffer.slice(0, receivedBytes)) === 0) {
this.emit('data', receiveBuffer.slice(1, receivedBytes - crcBytes))
this.resetReceiveBuffer()
}
} else {
if (expectedBytes > 0) {
if (receivedBytes === expectedBytes) {
if (crc.crc16modbus(receiveBuffer.slice(0, receivedBytes)) === 0) {
this.emit('data', receiveBuffer.slice(1, receivedBytes - crcBytes))
this.resetReceiveBuffer()
}
} else {
this.log.debug('received bytes ' + expectedBytes + ' differ from expected bytes ' + receivedBytes)
}
} else {
this.log.debug('none expected bytes: ' + expectedBytes)
this.emit('data', pdu)
}
}
} else {
this.log.debug('received bytes to less to do more -> receivedBytes: ' + receivedBytes)
}
} else {
this.log.debug('received bytes to less to do more -> receivedBytes: ' + receivedBytes)
}
} else {
this.log.debug('received bytes to less to do more -> pdu.length is empty')
}
}.bind(this)
this.resetReceiveBuffer = function () {
receivedBytes = 0
receiveBuffer = null
receiveBuffer = Buffer.alloc(256)
}
let onError = function (err) {
this.emit('error', err)
}.bind(this)
let onSend = function (pdu, setRequestTimeout) {
this.log.debug('PDU data' + JSON.stringify(pdu))
let base = Buffer.allocUnsafe(1)
base.writeUInt8(1)
let buf = Buffer.concat([base, pdu])
let crcModbus = crc.crc16modbus(buf)
let crcBufModbus = Buffer.allocUnsafe(2)
crcBufModbus.writeUInt16LE(crcModbus, 0)
this.log.debug('crcModbus: ' + JSON.stringify(crcModbus) + ' crcModbus Buffer:' + JSON.stringify(crcBufModbus))
let bufWithCRC = Buffer.concat([buf, crcBufModbus])
this.log.debug('Endian-Type: ' + this.endianType)
this.log.debug('Buffer with CR16LE ' + this.connectionType + ' : ' + JSON.stringify(bufWithCRC))
receivedBytes = 0
switch (pdu[0]) { // check for the function code that is requested
case 1:
case 2:
// expected response length is crc+adr+fc+len=5 + (number of coils/8)+1 to be requested
expectedBytes = 5 + (Math.floor(pdu.readInt16BE(3) / 8)) + 1
break
case 3:
case 4:
// expected response length is crc+adr+fc+len=5 + number of bytes to be requested
expectedBytes = 5 + pdu.readInt16BE(3) * 2
break
case 5:
case 6:
case 15:
case 16:
expectedBytes = 8
break
default:
expectedBytes = 0
break
}
if (this.inState('waiting') &&
serialport.isOpen()) {
serialport.write(bufWithCRC, function (err) {
if (err) {
this.log.error('error on write to serial:' + JSON.stringify(err))
this.emit('error', err)
} else {
this.log.debug('package written to serialport')
}
}.bind(this))
}
setRequestTimeout()
}.bind(this)
this.close = function () {
serialport.close()
}
init()
})
"use strict";var stampit=require("stampit"),ModbusCore=require("./modbus-client-core.js");module.exports=stampit().compose(ModbusCore).refs({logLabel:"ModbusSerialClient"}).init(function(){var t=require("serialport"),e=require("crc"),i=void 0,s=Buffer.alloc(256),o=0,r=0;this.connectionDelay||("win32"===process.platform?this.connectionDelay=500:this.connectionDelay=250);var n=function(){if(this.setState("init"),this.connectionType||(this.connectionType="RTU"),!this.portName)throw new Error("No portname.");this.baudRate||(this.baudRate=9600),this.dataBits||(this.dataBits=8),this.stopBits||(this.stopBits=1),this.parity||(this.parity="none"),this.injectedSerialport?(i=this.injectedSerialport,this.log.debug("we are working on a mockup serialport")):setTimeout(a,this.connectionDelay),this.log.debug("set on send method"),this.on("send",f)}.bind(this),a=function(){i="ASCII"===this.connectionType?new t(this.portName,{baudRate:this.baudRate,parity:this.parity,dataBits:this.dataBits,stopBits:this.stopBits,parser:"BIG"===this.endianType?t.parsers.byteDelimiter([13,10]):t.parsers.byteDelimiter([10,13])}):new t(this.portName,{baudRate:this.baudRate,parity:this.parity,dataBits:this.dataBits,stopBits:this.stopBits}),this.log.debug("serialport settings: "+JSON.stringify(i.options)),i.on("open",c),i.on("disconnect",d),i.on("close",h),i.on("data",l),i.on("error",u)}.bind(this),c=function(){this.setState("ready")}.bind(this),d=function(t){this.setState("disconnected"),t&&this.emit("error",t)}.bind(this),h=function(){this.setState("closed")}.bind(this),l=function(t){if(0!==t.length)if(this.log.debug("received serial data "+JSON.stringify(t)),t.length+o<=s.length){if(0===o&&t&&0===t[0])return this.log.debug("we got a broadcast from master"),void this.resetReceiveBuffer();t.copy(s,o,0),(o+=t.length)>=5?5===o?s[1]>=128&&0===e.crc16modbus(s.slice(0,o))&&(this.emit("data",s.slice(1,o-2)),this.resetReceiveBuffer()):r>0?o===r?0===e.crc16modbus(s.slice(0,o))&&(this.emit("data",s.slice(1,o-2)),this.resetReceiveBuffer()):this.log.debug("received bytes "+r+" differ from expected bytes "+o):(this.log.debug("none expected bytes: "+r),this.emit("data",t)):this.log.debug("received bytes to less to do more -> receivedBytes: "+o)}else this.log.debug("received bytes to less to do more -> receivedBytes: "+o);else this.log.debug("received bytes to less to do more -> pdu.length is empty")}.bind(this);this.resetReceiveBuffer=function(){o=0,s=null,s=Buffer.alloc(256)};var u=function(t){this.emit("error",t)}.bind(this),f=function(t,s){this.log.debug("PDU data"+JSON.stringify(t));var n=Buffer.allocUnsafe(1);n.writeUInt8(1);var a=Buffer.concat([n,t]),c=e.crc16modbus(a),d=Buffer.allocUnsafe(2);d.writeUInt16LE(c,0),this.log.debug("crcModbus: "+JSON.stringify(c)+" crcModbus Buffer:"+JSON.stringify(d));var h=Buffer.concat([a,d]);switch(this.log.debug("Endian-Type: "+this.endianType),this.log.debug("Buffer with CR16LE "+this.connectionType+" : "+JSON.stringify(h)),o=0,t[0]){case 1:case 2:r=5+Math.floor(t.readInt16BE(3)/8)+1;break;case 3:case 4:r=5+2*t.readInt16BE(3);break;case 5:case 6:case 15:case 16:r=8;break;default:r=0}this.inState("waiting")&&i.isOpen()&&i.write(h,function(t){t?(this.log.error("error on write to serial:"+JSON.stringify(t)),this.emit("error",t)):this.log.debug("package written to serialport")}.bind(this)),s()}.bind(this);this.close=function(){i.close()},n()});
//# sourceMappingURL=maps/modbus-serial-client.js.map

@@ -1,102 +0,2 @@

/**
* Modbus server core.
* @module ModbusCoreServer
*/
'use strict'
var stampit = require('stampit')
var EventBus = require('stampit-event-bus')
var logger = require('stampit-log')
let core = stampit()
.refs({
'logLabel': 'ModbusCoreServer',
'logLevel': 'info',
'logEnabled': true
})
.compose(EventBus, logger)
.init(function () {
let coils
let holding
let input
let handler = {}
let init = function () {
if (!this.coils) {
coils = Buffer.alloc(1024, 0)
} else {
coils = this.coils
}
if (!this.holding) {
holding = Buffer.alloc(1024, 0)
} else {
holding = this.holding
}
if (!this.input) {
input = Buffer.alloc(1024, 0)
} else {
input = this.input
}
if (this.logLevel) {
this.log.logLevel = this.logLevel
}
this.log.info('log level: ' + this.log.logLevel)
}.bind(this)
this.onData = function (pdu, callback) {
this.log.debug('incoming data')
// get fc and byteCount in advance
let fc = pdu.readUInt8(0)
// get the pdu handler
let reqHandler = handler[fc]
if (!reqHandler) {
// write a error/exception pkt to the
// socket with error code fc + 0x80 and
// exception code 0x01 (Illegal Function)
this.log.debug('no handler for fc', fc)
let buf = Buffer.alloc(2)
buf.writeUInt8(fc + 0x80, 0)
buf.writeUInt8(0x01, 1)
callback(buf)
return
}
reqHandler(pdu, function (response) {
callback(response)
})
}.bind(this)
this.setRequestHandler = function (fc, callback) {
this.log.debug('setting request handler', fc)
handler[fc] = callback
return this
}
this.getCoils = function () {
return coils
}
this.getInput = function () {
return input
}
this.getHolding = function () {
return holding
}
init()
})
module.exports = core
"use strict";var stampit=require("stampit"),EventBus=require("stampit-event-bus"),logger=require("stampit-log"),core=stampit().refs({logLabel:"ModbusCoreServer",logLevel:"info",logEnabled:!0}).compose(EventBus,logger).init(function(){var t=void 0,e=void 0,i=void 0,o={},n=function(){t=this.coils?this.coils:Buffer.alloc(1024,0),e=this.holding?this.holding:Buffer.alloc(1024,0),i=this.input?this.input:Buffer.alloc(1024,0),this.logLevel&&(this.log.logLevel=this.logLevel),this.log.info("log level: "+this.log.logLevel)}.bind(this);this.onData=function(t,e){this.log.debug("incoming data");var i=t.readUInt8(0),n=o[i];if(!n){this.log.debug("no handler for fc",i);var l=Buffer.alloc(2);return l.writeUInt8(i+128,0),l.writeUInt8(1,1),void e(l)}n(t,function(t){e(t)})}.bind(this),this.setRequestHandler=function(t,e){return this.log.debug("setting request handler",t),o[t]=e,this},this.getCoils=function(){return t},this.getInput=function(){return i},this.getHolding=function(){return e},n()});module.exports=core;
//# sourceMappingURL=maps/modbus-server-core.js.map

@@ -1,206 +0,2 @@

/**
* Modbus TCP client.
* @module ModbusTCPClient
*/
'use strict'
let stampit = require('stampit')
let ModbusCore = require('./modbus-client-core.js')
module.exports = stampit()
.compose(ModbusCore)
.refs({
'logLabel': 'ModbusTCPClient'
})
.init(function () {
let reqId = 0
let currentRequestId = reqId
let closedOnPurpose = false
let reconnect = false
let trashRequestId
let buffer = Buffer.alloc(0)
let socket
let closed = true
let init = function () {
this.setState('init')
if (!this.unitId) { this.unitId = 0 }
if (!this.protocolVersion) { this.protocolVersion = 0 }
if (!this.port) { this.port = 502 }
if (!this.host) { this.host = 'localhost' }
if (!this.autoReconnect) { this.autoReconnect = false }
if (!this.reconnectTimeout) { this.reconnectTimeout = 0 }
this.on('send', onSend)
this.on('newState_error', onError)
this.on('trashCurrentRequest', onTrashCurrentRequest)
this.on('stateChanged', this.log.debug)
}.bind(this)
let connect = function () {
this.setState('connect')
if (!socket) {
/* for testing you are able to inject a mocking object
* a simple event object should do the trick */
if (this.injectedSocket) {
socket = this.injectedSocket
} else {
socket = require('net').Socket()
}
socket.on('connect', onSocketConnect)
socket.on('close', onSocketClose)
socket.on('error', onSocketError)
socket.on('data', onSocketData)
}
try {
socket.connect(this.port, this.host)
this.log.debug('socket connected')
} catch (err) {
this.log.error(err + ' on socket connect')
}
}.bind(this)
let onSocketConnect = function () {
closed = false
this.setState('ready')
this.emit('connect')
}.bind(this)
let onSocketClose = function (hadErrors) {
this.log.debug('Socket closed with error', hadErrors)
this.setState('closed')
this.emit('close')
if (!closedOnPurpose && (this.autoReconnect || reconnect)) {
setTimeout(function () {
reconnect = false
connect()
}, this.reconnectTimeout || 0)
}
}.bind(this)
let onSocketError = function (err) {
this.logError('Socket Error', err)
this.setState('error')
this.emit('error', err)
}.bind(this)
let onSocketData = function (data) {
this.log.debug('received data')
buffer = Buffer.concat([buffer, data])
while (buffer.length > 7) {
// 1. extract mbap
let id = buffer.readUInt16BE(0)
let len = buffer.readUInt16BE(4)
if (id === trashRequestId) {
this.log.debug('current mbap contains trashed request id.')
return
}
/* Not all data received yet. */
if (buffer.length < 7 + len - 1) {
break
}
this.log.debug('MBAP extracted')
// 2. extract pdu
let pdu = buffer.slice(7, 7 + len - 1)
this.log.debug('PDU extracted')
// emit data event and let the
// listener handle the pdu
this.emit('data', pdu)
buffer = buffer.slice(pdu.length + 7, buffer.length)
}
}.bind(this)
let onError = function () {
this.log.error('Client in error state.')
socket.destroy()
}.bind(this)
let onSend = function (pdu, setRequestTimeout) {
this.log.debug('Sending pdu to the socket.')
reqId = (reqId + 1) % 0xffff
let head = Buffer.allocUnsafe(7)
head.writeUInt16BE(reqId, 0)
head.writeUInt16BE(this.protocolVersion, 2)
head.writeUInt16BE(pdu.length + 1, 4)
head.writeUInt8(this.unitId, 6)
let pkt = Buffer.concat([head, pdu])
currentRequestId = reqId
setRequestTimeout()
socket.write(pkt)
}.bind(this)
let onTrashCurrentRequest = function () {
trashRequestId = currentRequestId
}
this.connect = function () {
this.setState('connect')
connect()
return this
}
this.reconnect = function () {
if (!this.inState('closed')) {
return this
}
closedOnPurpose = false
reconnect = true
this.log.debug('Reconnecting client.')
socket.end()
return this
}
this.close = function () {
if (closed) {
return this
}
closed = true
closedOnPurpose = true
this.log.debug('Closing client on purpose.')
socket.end()
return this
}
// following is required to test of stream processing
// and is only during test active
if (process.env.DEBUG) {
this.getSocket = function () {
return socket
}
this.setCurrentRequestId = function (id) {
currentRequestId = id
}
this.registerOnSend = function (_onSend) {
this.removeListener(onSend)
this.on('send', _onSend.bind(this))
}
}
init()
})
"use strict";var stampit=require("stampit"),ModbusCore=require("./modbus-client-core.js");module.exports=stampit().compose(ModbusCore).refs({logLabel:"ModbusTCPClient"}).init(function(){var t=0,e=t,i=!1,o=!1,n=void 0,s=Buffer.alloc(0),r=void 0,c=!0,h=function(){this.setState("init"),this.unitId||(this.unitId=0),this.protocolVersion||(this.protocolVersion=0),this.port||(this.port=502),this.host||(this.host="localhost"),this.autoReconnect||(this.autoReconnect=!1),this.reconnectTimeout||(this.reconnectTimeout=0),this.on("send",m),this.on("newState_error",b),this.on("trashCurrentRequest",p),this.on("stateChanged",this.log.debug)}.bind(this),u=function(t){this.setState("connect"),r||((r=this.injectedSocket?this.injectedSocket:require("net").Socket()).on("connect",d),r.on("close",a),r.on("error",l),r.on("data",g),r.on("timeout",f));try{r.connect(this.port,this.host),this.log.debug("socket connected"),"function"==typeof t&&t()}catch(e){this.log.error(e+" on socket connect"),"function"==typeof t&&t(e)}}.bind(this),d=function(){c=!1,this.setState("ready"),this.emit("connect")}.bind(this),a=function(t){this.log.debug("Socket closed with error",t),this.setState("closed"),this.emit("close"),i||!this.autoReconnect&&!o||setTimeout(function(){o=!1,u()},this.reconnectTimeout||0)}.bind(this),l=function(t){this.logError("Socket Error",t),this.setState("error"),this.emit("error",t)}.bind(this),f=function(){this.logError("Socket Timeout, setting state to error"),this.setState("error"),this.emit("error","timeout")}.bind(this),g=function(t){for(this.log.debug("received data"),s=Buffer.concat([s,t]);s.length>7;){var e=s.readUInt16BE(0),i=s.readUInt16BE(4);if(e===n)return void this.log.debug("current mbap contains trashed request id.");if(s.length<7+i-1)break;this.log.debug("MBAP extracted");var o=s.slice(7,7+i-1);this.log.debug("PDU extracted"),this.emit("data",o),s=s.slice(o.length+7,s.length)}}.bind(this),b=function(){this.log.error("Client in error state."),r.destroy()}.bind(this),m=function(i,o){this.log.debug("Sending pdu to the socket."),t=(t+1)%65535;var n=Buffer.allocUnsafe(7);n.writeUInt16BE(t,0),n.writeUInt16BE(this.protocolVersion,2),n.writeUInt16BE(i.length+1,4),n.writeUInt8(this.unitId,6);var s=Buffer.concat([n,i]);e=t,o(),r.write(s)}.bind(this),p=function(){n=e};this.connect=function(t){return this.setState("connect"),u(t),this},this.reconnect=function(){return this.inState("closed")?(i=!1,o=!0,this.log.debug("Reconnecting client."),r.end(),this):this},this.close=function(t){return c?("function"==typeof t&&t(),this):(c=!0,i=!0,this.log.debug("Closing client on purpose."),r.end(),"function"==typeof t&&t(),this)},process.env.DEBUG&&(this.getSocket=function(){return r},this.setCurrentRequestId=function(t){e=t},this.registerOnSend=function(t){this.removeListener(m),this.on("send",t.bind(this))}),h()});
//# sourceMappingURL=maps/modbus-tcp-client.js.map

@@ -1,78 +0,2 @@

/**
* Modbus TCP server client.
* @module ModbusTCPServerClient
*/
'use strict'
let stampit = require('stampit')
let log = require('stampit-log')
module.exports = stampit()
.refs({
'logLabel': 'ModbusTCPServerClient'
})
.compose(log)
.init(function () {
let buffer = Buffer.alloc(0)
let init = function () {
if (!this.socket || this.socketId === undefined || !this.onRequest) {
this.log.error('socket:' + this.socket + ' socketId:' + this.socketId + 'onRequest' + this.onRequest)
throw new Error('No Socket defined.')
}
this.socket.on('end', this.onSocketEnd)
this.socket.on('data', this.onSocketData)
this.socket.on('error', this.onSocketError)
}.bind(this)
this.onSocketEnd = function () {
if (this.onEnd) {
this.onEnd()
}
this.log.debug('connection closed, socket', this.socketId)
}.bind(this)
this.onSocketData = function (data) {
this.log.debug('received data socket', this.socketId, data.byteLength)
buffer = Buffer.concat([buffer, data])
while (buffer.length > 8) {
// 1. extract mbap
let len = buffer.readUInt16BE(4)
let request = {
trans_id: buffer.readUInt16BE(0),
protocol_ver: buffer.readUInt16BE(2),
unit_id: buffer.readUInt8(6)
}
// 2. extract pdu
/* received data is not complete yet.
* break loop and wait for more data. */
if (buffer.length < 7 + len - 1) {
break
}
let pdu = buffer.slice(7, 7 + len)
// emit data event and let the
// listener handle the pdu
this.log.debug('PDU extracted.')
this.onRequest({request: request, pdu: pdu, socket: this.socket})
buffer = buffer.slice(pdu.length + 7, buffer.length)
}
}.bind(this)
this.onSocketError = function (e) {
this.log.error('Socker error', e)
}.bind(this)
init()
})
"use strict";var stampit=require("stampit"),log=require("stampit-log");module.exports=stampit().refs({logLabel:"ModbusTCPServerClient"}).compose(log).init(function(){var t=Buffer.alloc(0),e=function(){if(!this.socket||void 0===this.socketId||!this.onRequest)throw this.log.error("socket:"+this.socket+" socketId:"+this.socketId+"onRequest"+this.onRequest),new Error("No Socket defined.");this.socket.on("end",this.onSocketEnd),this.socket.on("data",this.onSocketData),this.socket.on("error",this.onSocketError)}.bind(this);this.onSocketEnd=function(){this.onEnd&&this.onEnd(),this.log.debug("connection closed, socket",this.socketId)}.bind(this),this.onSocketData=function(e){for(this.log.debug("received data socket",this.socketId,e.byteLength),t=Buffer.concat([t,e]);t.length>8;){var o=t.readUInt16BE(4),s={trans_id:t.readUInt16BE(0),protocol_ver:t.readUInt16BE(2),unit_id:t.readUInt8(6)};if(t.length<7+o-1)break;var i=t.slice(7,7+o);this.log.debug("PDU extracted."),this.onRequest({request:s,pdu:i,socket:this.socket}),t=t.slice(i.length+7,t.length)}}.bind(this),this.onSocketError=function(t){this.log.error("Socker error",t)}.bind(this),e()});
//# sourceMappingURL=maps/modbus-tcp-server-client.js.map

@@ -1,154 +0,2 @@

/**
* Modbus TCP server.
* @module ModbusTCPServer
*/
'use strict'
let stampit = require('stampit')
let ModbusServerCore = require('./modbus-server-core.js')
let StateMachine = require('stampit-state-machine')
let ClientSocket = require('./modbus-tcp-server-client.js')
module.exports = stampit()
.compose(ModbusServerCore)
.compose(StateMachine)
.refs({
'logLabel': 'ModbusTCPServer'
})
.init(function () {
let net = require('net')
let server
let socketList = []
let fifo = []
let clients = []
/**
* Initialization of the modbus TCP server.
*/
let init = function () {
if (!this.port) {
this.port = 502
}
if (!this.hostname) {
this.hostname = '0.0.0.0'
}
if (this.netInject) {
net = this.netInject
}
server = net.createServer()
server.on('connection', function (socket) {
this.log.debug('new connection', socket.address())
if (this.whiteListIPs && this.whiteListIPs.indexOf(socket.address()) < 0) {
this.log.debug('client connection REJECTED', socket.address())
socket.end()
return false
}
clients.push(socket)
initiateSocket(socket)
}.bind(this))
try {
server.listen(this.port, this.hostname, function (err) {
if (err) {
this.log.debug('error while listening', err)
this.emit('error', err)
}
}.bind(this))
this.log.debug('server is listening on port', this.hostname + ':' + this.port)
this.on('newState_ready', flush)
this.setState('ready')
} catch (err) {
this.log.error('server is listening error ' + err + ' on port', this.hostname + ':' + this.port)
this.setState('error')
}
}.bind(this)
/**
* Flush incoming data.
*/
let flush = function () {
if (this.inState('processing')) {
return
}
if (fifo.length === 0) {
return
}
this.setState('processing')
let current = fifo.shift()
this.onData(current.pdu, function (response) {
this.log.debug('sending tcp data')
let head = Buffer.allocUnsafe(7)
head.writeUInt16BE(current.request.trans_id, 0)
head.writeUInt16BE(current.request.protocol_ver, 2)
head.writeUInt16BE(response.length + 1, 4)
head.writeUInt8(current.request.unit_id, 6)
let pkt = Buffer.concat([head, response])
current.socket.write(pkt)
this.setState('ready')
}.bind(this))
}.bind(this)
/**
* Initiate socket on client requests.
*/
let initiateSocket = function (socket) {
let socketId = socketList.length
let requestHandler = function (req) {
fifo.push(req)
flush()
}
let removeHandler = function () {
socketList[socketId] = undefined
/* remove undefined on the end of the array */
for (let i = socketList.length - 1; i >= 0; i -= 1) {
let cur = socketList[i]
if (cur !== undefined) {
break
}
socketList.splice(i, 1)
}
this.log.debug('Client connection closed, remaining clients. ', socketList.length)
}.bind(this)
let clientSocket = ClientSocket({
socket: socket,
socketId: socketId,
onRequest: requestHandler,
onEnd: removeHandler
})
socketList.push(clientSocket)
}.bind(this)
this.close = function (cb) {
for (let c in clients) {
clients[c].destroy()
}
server.close(function () {
server.unref()
if (cb) { cb() }
})
}
init()
})
"use strict";var stampit=require("stampit"),ModbusServerCore=require("./modbus-server-core.js"),StateMachine=require("stampit-state-machine"),ClientSocket=require("./modbus-tcp-server-client.js");module.exports=stampit().compose(ModbusServerCore).compose(StateMachine).refs({logLabel:"ModbusTCPServer"}).init(function(){var t=require("net"),e=void 0,i=[],s=[],n=[],r=function(){this.port||(this.port=502),this.hostname||(this.hostname="0.0.0.0"),this.netInject&&(t=this.netInject),(e=t.createServer()).on("connection",function(t){if(this.log.debug("new connection",t.address()),this.whiteListIPs&&this.whiteListIPs.indexOf(t.address())<0)return this.log.debug("client connection REJECTED",t.address()),t.end(),!1;n.push(t),h(t)}.bind(this));try{e.listen(this.port,this.hostname,function(t){t&&(this.log.debug("error while listening",t),this.emit("error",t))}.bind(this)),this.log.debug("server is listening on port",this.hostname+":"+this.port),this.on("newState_ready",o),this.setState("ready")}catch(t){this.log.error("server is listening error "+t+" on port",this.hostname+":"+this.port),this.setState("error")}}.bind(this),o=function(){if(!this.inState("processing")&&0!==s.length){this.setState("processing");var t=s.shift();this.onData(t.pdu,function(e){this.log.debug("sending tcp data");var i=Buffer.allocUnsafe(7);i.writeUInt16BE(t.request.trans_id,0),i.writeUInt16BE(t.request.protocol_ver,2),i.writeUInt16BE(e.length+1,4),i.writeUInt8(t.request.unit_id,6);var s=Buffer.concat([i,e]);t.socket.write(s),this.setState("ready")}.bind(this))}}.bind(this),h=function(t){var e=i.length,n=function(){i[e]=void 0;for(var t=i.length-1;t>=0;t-=1){if(void 0!==i[t])break;i.splice(t,1)}this.log.debug("Client connection closed, remaining clients. ",i.length)}.bind(this),r=ClientSocket({socket:t,socketId:e,onRequest:function(t){s.push(t),o()},onEnd:n});i.push(r)}.bind(this);this.close=function(t){for(var i in n)n[i].destroy();e.close(function(){e.unref(),t&&t()})},r()});
//# sourceMappingURL=maps/modbus-tcp-server.js.map

@@ -1,48 +0,2 @@

/**
* Modbus.
* @module ModbusCore
*/
'use strict'
let fs = require('fs')
let path = require('path')
let ModbusCore = require('./modbus-client-core.js')
let ModbusTcpClient = require('./modbus-tcp-client.js')
exports.client = {
tcp: {
core: ModbusCore.compose(ModbusTcpClient),
complete: ModbusCore.compose(ModbusTcpClient)
},
serial: {
core: require('./modbus-serial-client.js'),
complete: require('./modbus-serial-client.js')
},
handler: {}
}
fs.readdirSync(path.join(__dirname, '/handler/client'))
.filter(function (file) {
return file.substr(-3) === '.js'
}).forEach(function (file) {
exports.client.tcp.complete = exports.client.tcp.complete.compose(require('./handler/client/' + file))
exports.client.serial.complete = exports.client.serial.complete.compose(require('./handler/client/' + file))
exports.client.handler[file.substr(0, file.length - 3)] = require('./handler/client/' + file)
})
exports.server = {
tcp: {
core: require('./modbus-tcp-server.js'),
complete: require('./modbus-tcp-server.js')
},
handler: {}
}
fs.readdirSync(path.join(__dirname, '/handler/server'))
.filter(function (file) {
return file.substr(-3) === '.js'
}).forEach(function (file) {
exports.server.tcp.complete = exports.server.tcp.complete.compose(require('./handler/server/' + file))
exports.server.handler[file.substr(0, file.length - 3)] = require('./handler/server/' + file)
})
"use strict";var fs=require("fs"),path=require("path"),ModbusCore=require("./modbus-client-core.js"),ModbusTcpClient=require("./modbus-tcp-client.js");exports.client={tcp:{core:ModbusCore.compose(ModbusTcpClient),complete:ModbusCore.compose(ModbusTcpClient)},serial:{core:require("./modbus-serial-client.js"),complete:require("./modbus-serial-client.js")},handler:{}},fs.readdirSync(path.join(__dirname,"/handler/client")).filter(function(e){return".js"===e.substr(-3)}).forEach(function(e){exports.client.tcp.complete=exports.client.tcp.complete.compose(require("./handler/client/"+e)),exports.client.serial.complete=exports.client.serial.complete.compose(require("./handler/client/"+e)),exports.client.handler[e.substr(0,e.length-3)]=require("./handler/client/"+e)}),exports.server={tcp:{core:require("./modbus-tcp-server.js"),complete:require("./modbus-tcp-server.js")},handler:{}},fs.readdirSync(path.join(__dirname,"/handler/server")).filter(function(e){return".js"===e.substr(-3)}).forEach(function(e){exports.server.tcp.complete=exports.server.tcp.complete.compose(require("./handler/server/"+e)),exports.server.handler[e.substr(0,e.length-3)]=require("./handler/server/"+e)});
//# sourceMappingURL=maps/modbus.js.map
{
"name": "node-modbus",
"version": "4.0.1",
"version": "4.2.0",
"description": "Sum of implementations for the Serial/TCP Modbus protocol.",

@@ -15,3 +15,3 @@ "author": "Klaus Landsdorf <klaus.landsdorf@bianco-royal.de>",

"engines": {
"node": "6.x"
"node": "6.x || 8.x"
},

@@ -22,3 +22,3 @@ "dependencies": {

"net": "^1.0.2",
"serialport": "^5.0.0",
"serialport": "^6.1.0",
"stampit": "^2.1.2",

@@ -31,2 +31,4 @@ "stampit-event-bus": "^0.1.1",

"assert": "^1.4.1",
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"eslint-config-standard": "^10.2.1",

@@ -38,14 +40,18 @@ "eslint-config-standard-jsx": "^4.0.2",

"gulp": "^3.9.1",
"gulp-babel": "^7.0.0",
"gulp-clean": "^0.3.2",
"gulp-htmlmin": "^3.0.0",
"gulp-jsdoc3": "^1.0.1",
"gulp-uglify": "^2.0.0",
"gulp-replace": "^0.6.1",
"gulp-sourcemaps": "^2.6.1",
"gulp-uglify": "^3.0.0",
"jsdoc": "^3.4.3",
"mocha": "^3.2.0",
"pump": "^1.0.2",
"sinon": "^1.17.6",
"standard": "^10.0.2",
"standard": "^10.0.3",
"standard-version": "^4.2.0"
},
"scripts": {
"test": "standard --fix && mocha test/*",
"test": "standard --fix && mocha test/* --reporter dot",
"build": "standard --fix && gulp clean && gulp publish",

@@ -52,0 +58,0 @@ "prepublish": "standard --fix && npm run build && npm test",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc