This commit is contained in:
zhongjin 2019-01-16 12:05:42 +08:00
parent 56ec7f8444
commit 36025dac53
25 changed files with 0 additions and 2079 deletions

View File

@ -1,206 +0,0 @@
A simple an easy to use Modbus TCP client/server implementation.
Modbus
========
Modbus is a simple Modbus TCP Client with a simple API.
Installation
------------
Just type `npm install jsmodbus` and you are ready to go.
Testing
-------
The test files are implemented using [mocha](https://github.com/visionmedia/mocha) and sinon.
Simply `npm install -g mocha` and `npm install -g sinon`. To run the tests type from the projects root folder `mocha test/*`.
Please feel free to fork and add your own tests.
TCP Client example
--------------
```javascript
var modbus = require('jsmodbus');
// create a modbus client
var client = modbus.client.tcp.complete({
'host' : host,
'port' : port,
'autoReconnect' : true,
'reconnectTimeout' : 1000,
'timeout' : 5000,
'unitId' : 0
});
client.connect();
// reconnect with client.reconnect()
client.on('connect', function () {
// make some calls
client.readCoils(0, 13).then(function (resp) {
// resp will look like { fc: 1, byteCount: 20, coils: [ values 0 - 13 ], payload: <Buffer> }
console.log(resp);
}).fail(console.log);
client.readDiscreteInputs(0, 13).then(function (resp) {
// resp will look like { fc: 2, byteCount: 20, coils: [ values 0 - 13 ], payload: <Buffer> }
console.log(resp);
}).fail(console.log);
client.readHoldingRegisters(0, 10).then(function (resp) {
// resp will look like { fc: 3, byteCount: 20, register: [ values 0 - 10 ], payload: <Buffer> }
console.log(resp);
}).fail(console.log);
client.readInputRegisters(0, 10).then(function (resp) {
// resp will look like { fc: 4, byteCount: 20, register: [ values 0 - 10 ], payload: <Buffer> }
console.log(resp);
}).fail(console.log);
client.writeSingleCoil(5, true).then(function (resp) {
// resp will look like { fc: 5, byteCount: 4, outputAddress: 5, outputValue: true }
console.log(resp);
}).fail(console.log);
client.writeSingleCoil(5, new Buffer(0x01)).then(function (resp) {
// resp will look like { fc: 5, byteCount: 4, outputAddress: 5, outputValue: true }
console.log(resp);
}).fail(console.log);
client.writeSingleRegister(13, 42).then(function (resp) {
// resp will look like { fc: 6, byteCount: 4, registerAddress: 13, registerValue: 42 }
console.log(resp);
}).fail(console.log);
client.writeSingleRegister(13, new Buffer([0x00 0x2A])).then(function (resp) {
// resp will look like { fc: 6, byteCount: 4, registerAddress: 13, registerValue: 42 }
console.log(resp);
}).fail(console.log);
client.writeMultipleCoils(3, [1, 0, 1, 0, 1, 1]).then(function (resp) {
// resp will look like { fc: 15, startAddress: 3, quantity: 6 }
console.log(resp);
}).fail(console.log);
client.writeMultipleCoils(3, new Buffer([0x2B]), 6).then(function (resp) {
// resp will look like { fc: 15, startAddress: 3, quantity: 6 }
console.log(resp);
}).fail(console.log);
client.writeMultipleRegisters(4, [1, 2, 3, 4]).then(function (resp) {
// resp will look like { fc : 16, startAddress: 4, quantity: 4 }
console.log(resp);
}).fail(console.log);
client.writeMultipleRegisters(4, new Buffer([0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04]).then(function (resp) {
// resp will look like { fc : 16, startAddress: 4, quantity: 4 }
console.log(resp);
}).fail(console.log);
});
client.on('error', function (err) {
console.log(err);
})
```
Server example
--------------
```javascript
var stampit = require('stampit'),
modbus = require('jsmodbus');
var customServer = stampit()
.refs({
'logEnabled' : true,
'port' : 8888,
'responseDelay' : 10, // so we do not fry anything when someone is polling this server
// specify coils, holding and input register here as buffer or leave it for them to be new Buffer(1024)
coils : new Buffer(1024),
holding : new Buffer(1024),
input : new Buffer(1024)
})
.compose(modbus.server.tcp.complete)
.init(function () {
var init = function () {
// get the coils with this.getCoils() [ Buffer(1024) ]
// get the holding register with this.getHolding() [ Buffer(1024) ]
// get the input register with this.getInput() [ Buffer(1024) ]
// listen to requests
this.on('readCoilsRequest', function (start, quantity) {
// do something, this will be executed in sync before the
// read coils request is executed
});
// the write request have pre and post listener
this.on('[pre][post]WriteSingleCoilRequest', function (address, value) {
});
}.bind(this);
init();
});
customServer();
// you can of course always use a standard server like so
var server = modbus.server.tcp.complete({ port : 8888 });
// and interact with the register via the getCoils(), getHolding() and getInput() calls
server.getHolding().writeUInt16BE(123, 1);
````
## License
Copyright (C) 2016 Stefan Poeter (Stefan.Poeter[at]cloud-automation.de)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,56 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 1;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
let fc = pdu.readUInt8(0);
if (fc !== FC) {
cb(`ReadCoils: Invalid FC ${fc}`);
} else {
let byteCount = pdu.readUInt8(1);
// let bitCount = byteCount * 8;
let resp = {
unitId,
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
data: []
};
let counter = 0;
for (let i = 0; i < byteCount; i+=1) {
let h = 1, cur = pdu.readUInt8(2 + i);
for (let j = 0; j < 8; j++) {
resp.data[counter] = (cur & h) > 0 ;
h = h << 1;
counter += 1;
}
}
cb && cb(null, resp);
}
};
this.readCoils = (unitId, start, quantity) => {
return new Promise((resolve, reject) => {
let pdu = Put().word8(FC).word16be(start).word16be(quantity).buffer();
this.queueRequest(unitId, FC, pdu, (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,62 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 2;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
let fc = pdu.readUInt8(0);
if (fc !== FC) {
cb(`ReadDiscreteInputs: Invalid FC ${fc}`);
} else {
let byteCount = pdu.readUInt8(1);
let counter = 0;
let resp = {
unitId,
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
data: []
};
for (let i = 0; i < byteCount; i++) {
let h = 1, cur = pdu.readUInt8(2 + i);
for (let j = 0; j < 8; j+=1) {
resp.data[counter] = (cur & h) > 0 ;
h = h << 1;
counter += 1;
}
}
cb && cb(null, resp);
}
};
this.readDiscreteInputs = (unitId, start, quantity) => {
return new Promise((resolve, reject) => {
if (quantity > 2000) {
return reject('quantity is too big');
}
let pdu = Put().word8be(FC).word16be(start).word16be(quantity).buffer();
this.queueRequest(unitId, FC, pdu, (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,52 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 3;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
let fc = pdu.readUInt8(0);
if (fc !== FC) {
cb(`ReadHoldingRegisters: Invalid FC ${fc}`);
} else {
let byteCount = pdu.readUInt8(1);
let resp = {
unitId,
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
register: []
};
const registerCount = byteCount / 2;
for (let i = 0; i < registerCount; i++) {
resp.register.push(pdu.readUInt16BE(2 + (i * 2)));
}
cb && cb(null, resp);
}
};
this.readHoldingRegisters = (unitId, start, quantity) => {
return new Promise((resolve, reject) => {
let pdu = Put().word8be(FC).word16be(start).word16be(quantity).buffer();
this.queueRequest(unitId, FC, pdu, (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,52 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 4;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
let fc = pdu.readUInt8(0);
if (fc !== FC) {
cb(`ReadInputRegisters: Invalid FC ${fc}`);
} else {
let byteCount = pdu.readUInt8(1);
let resp = {
unitId,
fc: fc,
byteCount: byteCount,
payload: pdu.slice(2),
register: []
};
const registerCount = byteCount / 2;
for (let i = 0; i < registerCount; i++) {
resp.register.push(pdu.readUInt16BE(2 + (i * 2)));
}
cb && cb(null, resp);
}
};
this.readInputRegisters = (unitId, start, quantity) => {
return new Promise((resolve, reject) => {
let pdu = Put().word8be(FC).word16be(start).word16be(quantity).buffer();
this.queueRequest(unitId, FC, pdu, (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,73 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 15;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
const fc = pdu.readUInt8(0);
const startAddress = pdu.readUInt16BE(1);
const quantity = pdu.readUInt16BE(3);
let resp = {
unitId: unitId,
fc: fc,
startAddress: startAddress,
quantity: quantity
};
if (fc !== FC) {
cb(`WriteMultipleCoils: Invalid FC ${fc}`);
} else {
cb(null, resp);
}
};
this.writeMultipleCoils = (unitId, startAddress, data, N) => {
return new Promise((resolve, reject) => {
let pdu = Put().word8(FC).word16be(startAddress);
if (data instanceof Buffer) {
pdu.word16be(N).word8(data.length).put(data);
} else if (data instanceof Array) {
if (data.length > 1968) {
reject('Length is too big');
return;
}
const byteCount = Math.ceil(data.length / 8);
let curByte = 0;
let cntr = 0;
pdu.word16be(data.length).word8(byteCount);
for (let i = 0; i < data.length; i += 1) {
curByte += data[i] ? Math.pow(2, cntr) : 0;
cntr = (cntr + 1) % 8;
if (cntr === 0 || i === coils.length - 1 ) {
pdu.word8(curByte);
curByte = 0;
}
}
}
this.queueRequest(unitId, FC, pdu.buffer(), (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,71 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 16;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
const fc = pdu.readUInt8(0);
if (fc !== FC) {
cb(`WriteMultipleRegisters: Invalid FC ${fc}`);
} else {
const startAddress = pdu.readUInt16BE(1);
const quantity = pdu.readUInt16BE(3);
let resp = {
unitId: unitId,
fc: fc,
startAddress: startAddress,
quantity: quantity
};
cb(null, resp);
}
};
this.writeMultipleRegisters = (unitId, startAddress, data) => {
return new Promise((resolve, reject) => {
let pdu = Put().word8(FC).word16be(startAddress);
if (data instanceof Buffer) {
if (data.length / 2 > 0x007b) {
reject('Length is too big');
return;
}
pdu.word16be(data.length / 2).word8(data.length).put(data);
} else if (data instanceof Array) {
if (data.length > 0x007b) {
reject('Length is too big');
return;
}
let byteCount = Math.ceil(data.length * 2);
pdu.word16be(data.length).word8(byteCount);
for (let i = 0; i < data.length; i += 1) {
pdu.word16be(data[i]);
}
} else {
reject('Invalid data');
return;
}
this.queueRequest(unitId, FC, pdu.buffer(), (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,47 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 5;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
const fc = pdu.readUInt8(0);
const outputAddress = pdu.readUInt16BE(1);
const outputValue = pdu.readUInt16BE(3);
let resp = {
unitId: unitId,
fc: fc,
outputAddress: outputAddress,
outputValue: outputValue === 0x0000 ? false : (outputValue === 0xFF00 ? true : undefined)
};
if (fc !== FC) {
cb(`WriteSingleCoil: Invalid FC ${fc}`);
} else {
cb(null, resp);
}
};
this.writeSingleCoil = (unitId, address, value) => {
return new Promise((resolve, reject) => {
const payload = (value instanceof Buffer) ? (value.readUInt8(0) > 0) : value;
const pdu = Put().word8be(FC).word16be(address).word16be(payload ? 0xff00 : 0x0000);
this.queueRequest(unitId, FC, pdu.buffer(), (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,50 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 6;
let init = () => this.addResponseHandler(FC, onResponse);
let onResponse = (unitId, pdu, cb) => {
const fc = pdu.readUInt8(0);
const registerAddress = pdu.readUInt16BE(1);
const registerValue = pdu.readUInt16BE(3);
let resp = {
unitId: unitId,
fc: fc,
registerAddress: registerAddress,
registerValue: registerValue,
registerAddressRaw: pdu.slice(1,2),
registerValueRaw: pdu.slice(3,2)
};
if (fc !== FC) {
cb(`WriteSingleRegister: Invalid FC ${fc}`);
} else {
cb(null, resp);
}
};
this.writeSingleRegister = (unitId, address, value) => {
return new Promise((resolve, reject) => {
const payload = (value instanceof Buffer) ? value : Put().word16be(value).buffer();
const pdu = Put().word8be(FC).word16be(address).put(payload);
this.queueRequest(unitId, FC, pdu.buffer(), (err, resp) => {
if (err) {
reject(err);
} else {
resolve(resp);
}
});
});
};
init();
});

View File

@ -1,52 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 1;
let init = () => {
this.log.debug('initiating read coils request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
this.log.debug('handling read coils request.');
if (pdu.length !== 5) {
cb(Put().word8(0x81).word8(0x02).buffer());
} else {
const fc = pdu.readUInt8(0);
const address = pdu.readUInt16BE(1);
const byteAddress = address * 2;
const value = pdu.readUInt16BE(3);
this.emit('preWriteSingleRegisterRequest', byteAddress, value);
let mem = this.getHolding();
if (byteAddress + 2 > mem.length) {
cb(Put().word8(0x86).word8(0x02).buffer());
} else {
let response = Put().word8(0x06).word16be(address).word16be(value).buffer();
mem.writeUInt16BE(value, byteAddress);
this.emit('postWriteSingleRegisterRequest', byteAddress, value);
cb(response);
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,69 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 2;
let init = () => {
this.log.debug('initiating read discrete inputs request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
this.log.debug('handling read discrete inputs request.');
if (pdu.length !== 5) {
cb(Put().word8(0x82).word8(0x02).buffer());
} else {
const fc = pdu.readUInt8(0);
const start = pdu.readUInt16BE(1);
const quantity = pdu.readUInt16BE( 3);
this.emit('readDiscreteInputsRequest', start, quantity);
let mem = this.getDiscrete();
if (!quantity || start + quantity > mem.length * 8) {
cb(Put().word8(0x82).word8(0x02).buffer());
} else {
let val = 0;
let thisByteBitCount = 0;
let response = Put().word8(0x02).word8(Math.floor(quantity / 8) + (quantity % 8 === 0 ? 0 : 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.word8(val);
val = 0;
}
}
cb(response.buffer());
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,55 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 3;
let init = () => {
this.log.debug('initiating read holding registers request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
if (pdu.length !== 5) {
this.log.warn('wrong pdu length.');
cb(Put().word8(0x83).word8(0x02).buffer());
} else {
const fc = pdu.readUInt8(0);
const start = pdu.readUInt16BE(1);
const byteStart = start * 2;
const quantity = pdu.readUInt16BE(3);
this.emit('readHoldingRegistersRequest', byteStart, quantity);
let mem = this.getHolding();
if (!quantity || byteStart + (quantity * 2) > mem.length) {
this.log.debug('request outside register boundaries.');
cb(Put().word8(0x83).word8(0x02).buffer());
return;
}
let response = Put().word8(0x03).word8(quantity * 2);
for (let i = byteStart; i < byteStart + (quantity * 2); i += 2) {
response.word16be(mem.readUInt16BE(i));
}
this.log.debug('finished read holding register request.');
cb(response.buffer());
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,52 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 4;
let init = () => {
this.log.debug('initiating read input registers request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
this.log.debug('handling read input registers request.');
if (pdu.length !== 5) {
cb(Put().word8(0x84).word8(0x02).buffer());
} else {
const fc = pdu.readUInt8(0);
const start = pdu.readUInt16BE(1);
const byteStart = start * 2;
const quantity = pdu.readUInt16BE(3);
this.emit('readInputRegistersRequest', byteStart, quantity);
let mem = this.getInput();
if (!quantity || byteStart + (quantity * 2) > mem.length) {
cb(Put().word8(0x84).word8(0x02).buffer());
} else {
let response = Put().word8(0x04).word8(quantity * 2);
for (let i = byteStart; i < byteStart + (quantity * 2); i += 2) {
response.word16be(mem.readUInt16BE(i));
}
cb(response.buffer());
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,77 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 15;
let init = () => {
this.log.debug('initiating write multiple coils request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
this.log.debug('handling write multiple coils request.');
if (pdu.length < 3) {
cb(Put().word8(0x8F).word8(0x02).buffer());
} else {
// const fc = pdu.readUInt8(0);
const start = pdu.readUInt16BE(1);
const quantity = pdu.readUInt16BE(3);
const byteCount = pdu.readUInt8(5);
this.emit('preWriteMultipleCoilsRequest', start, quantity, byteCount);
let mem = this.getCoils();
// error response
if (!quantity || start + quantity > mem.length * 8) {
cb(Put().word8(0x8F).word8(0x02).buffer());
} else {
let response = Put().word8(0x0F).word16be(start).word16be(quantity).buffer();
let oldValue;
let newValue, current = pdu.readUInt8(6);
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);
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,60 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 16;
let init = () => {
this.log.debug('initiating write multiple registers request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
if (pdu.length < 3) {
cb(Put().word8(0x90).word8(0x02).buffer());
} else {
// const fc = pdu.readUInt8(0);
const start = pdu.readUInt16BE(1);
const byteStart = start * 2;
const quantity = pdu.readUInt16BE(3);
const byteCount = pdu.readUInt8(5);
if (quantity > 0x007b) {
cb(Put().word8(0x90).word8(0x03).buffer());
} else {
this.emit('preWriteMultipleRegistersRequest', byteStart, quantity, byteCount);
let mem = this.getHolding();
if (!quantity || byteStart + (quantity * 2) > mem.length) {
cb(Put().word8(0x90).word8(0x02).buffer());
} else {
let response = Put().word8(0x10).word16be(start).word16be(quantity).buffer();
let j = 0;
for (let i = byteStart; i < byteStart + byteCount; i += 1) {
mem.writeUInt8(pdu.readUInt8(6 + j), i);
j++;
}
this.emit('postWriteMultipleRegistersRequest', byteStart, quantity, byteCount);
cb(response);
}
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,62 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 5;
let init = () => {
this.log.debug('initiating write single coil request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
if (pdu.length !== 5) {
cb(Put().word8(0x85).word8(0x02).buffer());
} else {
// const fc = pdu.readUInt8(0);
const address = pdu.readUInt16BE(1);
const value = (pdu.readUInt16BE(3) === 0x0000);
if (pdu.readUInt16BE(3) !== 0x0000 && pdu.readUInt16BE(3) !== 0xFF00) {
cb(Put().word8(0x85).word8(0x03).buffer());
} else {
this.emit('preWriteSingleCoilRequest', address, value);
let mem = this.getCoils();
if (address + 1 > mem.length * 8) {
cb(Put().word8(0x85).word8(0x02).buffer());
} else {
let response = Put().word8(0x05).word16be(address).word16be(value ? 0xFF00 : 0x0000);
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.buffer());
}
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,50 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
module.exports = Stampit()
.init(function () {
const FC = 6;
let init = () => {
this.log.debug('initiating write single register request handler.');
this.responseDelay = this.responseDelay || 0;
this.setRequestHandler(FC, onRequest);
};
let _onRequest = (pdu, cb) => {
this.log.debug('handling write single register request.');
if (pdu.length !== 5) {
cb(Put().word8(0x86).word8(0x02).buffer());
} else {
// const fc = pdu.readUInt8(0);
const address = pdu.readUInt16BE(1);
const byteAddress = address * 2;
const value = pdu.readUInt16BE(3);
this.emit('preWriteSingleRegisterRequest', byteAddress, value);
let mem = this.getHolding();
if (byteAddress + 2 > mem.length) {
cb(Put().word8(0x86).word8(0x02).buffer());
} else {
let response = Put().word8(0x06).word16be(address).word16be(value).buffer();
mem.writeUInt16BE(value, byteAddress);
this.emit('postWriteSingleRegisterRequest', byteAddress, value);
cb(response);
}
}
};
let onRequest = (pdu, cb) => {
if (this.responseDelay) {
setTimeout(_onRequest, this.responseDelay, pdu, cb);
} else {
setImmediate(_onRequest, pdu, cb);
}
};
init();
});

View File

@ -1,17 +0,0 @@
'use strict';
const fs = require('fs');
function Modbus(type, transport) {
let core = require(__dirname + `/transports/modbus-${type}-${transport || 'tcp'}.js`);
fs.readdirSync(__dirname + `/handler/${type}`)
.filter(file => file.substr(-3) === '.js').forEach(file => {
const handler = require(__dirname + `/handler/${type}/${file}`);
core = core.compose(handler);
//core.handler[file.substr(0, file.length - 3)] = handler;
});
return core;
}
module.exports = Modbus;

View File

@ -1,145 +0,0 @@
'use strict';
const Stampit = require('stampit');
const StateMachine = require('stampit-state-machine');
const EventBus = require('stampit-event-bus');
const 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()
.compose(StateMachine, EventBus)
.init(function () {
this.log = this.options && this.options.log;
if (!this.log) {
this.log = {
log: () => console.log.apply(console, arguments),
error: () => console.error.apply(console, arguments),
warn: () => console.warn.apply(console, arguments),
debug: () => console.log.apply(console, arguments)
};
}
let responseHandler = {};
let currentRequest = null;
let reqFifo = [];
let init = () => {
this.options.timeout = this.options.timeout || (5 * 1000); // 5s
this.on('data', onData);
this.on('newState_ready', flush);
this.on('newState_closed', onClosed);
};
let flush = () => {
if (reqFifo.length) {
currentRequest = reqFifo.shift();
currentRequest.timeout = setTimeout(() => {
currentRequest.cb && currentRequest.cb({err: 'timeout'});
this.emit('trashCurrentRequest');
this.log.error('Request timed out.');
this.setState('error');
}, this.options.timeout);
this.setState('waiting');
this.emit('send', currentRequest.pdu, currentRequest.unitId);
}
};
let onClosed = () => {
if (currentRequest) {
this.log.debug('Clearing timeout of the current request.');
clearTimeout(currentRequest.timeout);
}
this.log.debug('Cleaning up request fifo.');
reqFifo = [];
};
let handleErrorPDU = (pdu) => {
const 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
const exceptionCode = pdu.readUInt8(1);
const message = ExceptionMessage[exceptionCode];
const err = {
errorCode: errorCode,
exceptionCode: exceptionCode,
message: message
};
// call the desired deferred
currentRequest.cb && currentRequest.cb(err);
return true;
};
/**
* Handle the incoming data, cut out the mbap
* packet and send the pdu to the listener
*/
let onData = (pdu, unitId) => {
if (!currentRequest) {
this.log.debug('No current request.');
return;
}
clearTimeout(currentRequest.timeout);
// check pdu for error
if (handleErrorPDU(pdu)) {
this.log.debug('Received pdu describes an error.');
currentRequest = null;
this.setState('ready');
return;
}
// handle pdu
const handler = responseHandler[currentRequest.fc];
if (!handler) {
this.log.debug(`Found no handler for fc ${currentRequest.fc}`);
throw new Error(`No handler implemented for fc ${currentRequest.fc}`);
}
handler(unitId, pdu, currentRequest.cb);
this.setState('ready');
};
this.addResponseHandler = (fc, handler) => {
responseHandler[fc] = handler;
return this;
};
this.queueRequest = (unitId, fc, pdu, cb) => {
reqFifo.push({unitId, fc, pdu, cb});
if (this.inState('ready')) {
flush();
}
};
init();
});

View File

@ -1,91 +0,0 @@
'use strict';
const Stampit = require('stampit');
const Put = require('put');
const EventBus = require('stampit-event-bus');
const core = Stampit()
.compose(EventBus)
.init(function () {
this.log = this.options && this.options.log;
if (!this.log) {
this.log = {
log: () => console.log.apply(console, arguments),
error: () => console.error.apply(console, arguments),
warn: () => console.warn.apply(console, arguments),
debug: () => console.log.apply(console, arguments)
};
}
let data = {
coils: null,
holding: null,
input: null,
discrete: null,
};
let handler = {};
let init = () => {
if (!this.coils) {
data.coils = new Buffer(1024);
} else {
data.coils = this.coils;
}
if (!this.holding) {
data.holding = new Buffer(1024);
} else {
data.holding = this.holding;
}
if (!this.input) {
data.input = new Buffer(1024);
} else {
data.input = this.input;
}
if (!this.discrete) {
data.discrete = new Buffer(1024);
} else {
data.discrete = this.discrete;
}
};
this.onData = (pdu, callback) => {
// get fc and byteCount in advance
const fc = pdu.readUInt8(0);
// const byteCount = pdu.readUInt8(1);
// get the pdu handler
const 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);
callback(Put().word8(fc + 0x80).word8(0x01).buffer());
} else {
reqHandler(pdu, response => {
callback(response);
});
}
};
this.setRequestHandler = (fc, callback) => {
this.log.debug('setting request handler', fc);
handler[fc] = callback;
return this;
};
this.getCoils = () => data.coils;
this.getInput = () => data.input;
this.getHolding = () => data.holding;
this.getDiscrete = () => data.discrete;
init();
});
module.exports = core;

View File

@ -1,52 +0,0 @@
{
"author": {
"name": "Stefan Poeter",
"email": "stefan.poeter@cloud-automation.de"
},
"bugs": {
"url": "https://github.com/Cloud-Automation/node-modbus/issues"
},
"dependencies": {
"crc": "3.4.0",
"put": "0.0.6",
"q": "1.0.1",
"serialport": "^4.0.1",
"stampit": "^2.1.2",
"stampit-event-bus": "^0.1.1",
"stampit-log": "^0.3.0",
"stampit-state-machine": "^0.2.1"
},
"deprecated": false,
"description": "Implementation for the Serial/TCP Modbus protocol.",
"devDependencies": {
"mocha": "^3.0.2",
"sinon": "1.5.0"
},
"directories": {
"test": "test",
"example": "examples"
},
"engine": {
"node": ">=0.6"
},
"homepage": "https://github.com/Cloud-Automation/node-modbus#readme",
"keywords": [
"client",
"server",
"serial",
"port",
"modbus",
"tcp"
],
"license": "MIT",
"main": "index.js",
"name": "jsmodbus",
"repository": {
"type": "git",
"url": "git+https://github.com/Cloud-Automation/node-modbus.git"
},
"scripts": {
"test": "mocha test/*"
},
"version": "1.2.4"
}

View File

@ -1,148 +0,0 @@
'use strict';
const stampit = require('stampit');
const crc = require('crc');
const Put = require('put');
const ModbusCore = require('../modbus-client-core.js');
module.exports = stampit()
.compose(ModbusCore)
.init(function () {
const SerialPort = require('serialport');//.SerialPort,
let serialport;
let buffer = new Buffer(0);
let init = () => {
this.setState('init');
let serial = this.options.serial;
if (!serial.portName) {
throw new Error('No portname.');
}
serial.baudRate = serial.baudRate || 9600; // the most are working with 9600
serial.dataBits = serial.dataBits || 8;
serial.stopBits = serial.stopBits || 1;
serial.parity = serial.parity || 'none';
// TODO: flowControl - ['xon', 'xoff', 'xany', 'rtscts']
// TODO: settings - ['brk', 'cts', 'dtr', 'dts', 'rts']
this.log.debug('connect to serial ' + serial.portName + ' with ' + serial.baudRate);
serialport = new SerialPort(serial.portName, {
baudRate: serial.baudRate,
parity: serial.parity,
dataBits: serial.dataBits,
stopBits: serial.stopBits
});
serialport.on('open', onOpen);
serialport.on('close', onClose);
serialport.on('data', onData);
serialport.on('error', onError);
this.on('send', onSend);
};
let onOpen = () => {
this.emit('connect');
this.setState('ready');
};
let onClose = () => this.setState('closed');
function toStrArray(buf) {
if (!buf || !buf.length) return '';
let text = '';
for (let i = 0; i < buf.length; i++) {
text += (text ? ',' : '') + buf[i];
}
return text;
}
let onData = data => {
buffer = Buffer.concat([buffer, data]);
while (buffer.length > 4) {
// 1. there is no mbap
// 2. extract pdu
// 0 - device ID
// 1 - Function CODE
// 2 - Bytes length
// 3.. Data
// checksum.(2 bytes
let len;
let pdu;
// if response for write
if (buffer[1] === 5 || buffer[1] === 6 || buffer[1] === 15 || buffer[1] === 16) {
if (buffer.length < 8) {
break;
}
pdu = buffer.slice(0, 8); // 1 byte device ID + 1 byte FC + 2 bytes address + 2 bytes value + 2 bytes CRC
} else if (buffer[1] > 0 && buffer[1] < 5){
len = buffer[2];
if (buffer.length < len + 5) {
break;
}
pdu = buffer.slice(0, len + 5); // 1 byte deviceID + 1 byte FC + 1 byte length + 2 bytes CRC
} else {
// unknown function code
this.log.error('unknown function code: ' + buffer[1]);
// reset buffer and try again
buffer = new Buffer(0);
break;
}
if (crc.crc16modbus(pdu) === 0) { /* PDU is valid if CRC across whole PDU equals 0, else ignore and do nothing */
if (this.options.unitId !== undefined && pdu[0] !== this.options.unitId) {
// answer for wrong device
this.log.debug('received answer for wrong ID ' + buffer[0] + ', expected ' + this.options.unitId);
}
// emit data event and let the
// listener handle the pdu
this.emit('data', pdu.slice(1, pdu.length - 2), pdu[0]);
} else {
this.log.error('Wrong CRC for frame: ' + toStrArray(pdu));
// reset buffer and try again
buffer = new Buffer(0);
break;
}
buffer = buffer.slice(pdu.length, buffer.length);
}
};
let onError = err => this.emit('error', err);
let onSend = (pdu, unitId) => {
let pkt = Put().word8((unitId === undefined ? this.options.unitId : unitId) || 0).put(pdu);
let buf = pkt.buffer();
let crc16 = crc.crc16modbus(buf);
pkt = pkt.word16le(crc16).buffer();
if (!serialport) {
init();
}
serialport.write(pkt, err => err && this.emit('error', err));
};
this.connect = () => {
if (!serialport) {
init();
}
};
this.close = () => {
if (serialport) {
serialport.close();
serialport = null;
}
};
init();
});

View File

@ -1,175 +0,0 @@
'use strict';
const stampit = require('stampit');
const Put = require('put');
const crc = require('crc');
const Net = require('net');
const ModbusCore = require('../modbus-client-core.js');
module.exports = stampit()
.compose(ModbusCore)
.init(function () {
let closedOnPurpose = false;
let reconnect = false;
let buffer = new Buffer(0);
let socket;
let init = () => {
this.setState('init');
let tcp = this.options.tcp;
tcp.protocolVersion = tcp.protocolVersion || 0;
tcp.port = tcp.port || 502;
tcp.host = tcp.host || 'localhost';
tcp.autoReconnect = tcp.autoReconnect || false;
tcp.reconnectTimeout = tcp.reconnectTimeout || 0;
this.on('send', onSend);
this.on('newState_error', onError);
//this.on('stateChanged', this.log.debug);
};
let connect = () => {
this.setState('connect');
if (!socket) {
socket = new Net.Socket();
socket.on('connect', onSocketConnect);
socket.on('close', onSocketClose);
socket.on('error', onSocketError);
socket.on('data', onSocketData);
}
socket.connect(this.options.tcp.port, this.options.tcp.host);
};
let onSocketConnect = () => {
this.emit('connect');
this.setState('ready');
};
let onSocketClose = hadErrors => {
this.log.debug('Socket closed with error', hadErrors);
this.setState('closed');
this.emit('close');
if (!closedOnPurpose && (this.options.tcp.autoReconnect || reconnect)) {
setTimeout(() => {
reconnect = false;
connect();
}, this.options.tcp.reconnectTimeout);
}
};
let onSocketError = err => {
this.log.error('Socket Error', err);
this.setState('error');
this.emit('error', err);
};
function toStrArray(buf) {
if (!buf || !buf.length) return '';
let text = '';
for (let i = 0; i < buf.length; i++) {
text += (text ? ',' : '') + buf[i];
}
return text;
}
let onSocketData = data => {
buffer = Buffer.concat([buffer, data]);
while (buffer.length > 4) {
// 1. there is no mbap
// 2. extract pdu
// 0 - device ID
// 1 - Function CODE
// 2 - Bytes length
// 3.. Data
// checksum.(2 bytes
let len;
let pdu;
// if response for write
if (buffer[1] === 5 || buffer[1] === 6 || buffer[1] === 15 || buffer[1] === 16) {
if (buffer.length < 8) break;
pdu = buffer.slice(0, 8); // 1 byte device ID + 1 byte FC + 2 bytes address + 2 bytes value + 2 bytes CRC
} else if (buffer[1] > 0 && buffer[1] < 5){
len = buffer[2];
if (buffer.length < len + 5) break;
pdu = buffer.slice(0, len + 5); // 1 byte deviceID + 1 byte FC + 1 byte length + 2 bytes CRC
} else {
// unknown function code
this.log.error('unknown function code: ' + buffer[1]);
// reset buffer and try again
buffer = new Buffer(0);
break;
}
if (crc.crc16modbus(pdu) === 0) { /* PDU is valid if CRC across whole PDU equals 0, else ignore and do nothing */
if (this.options.unitId !== undefined && pdu[0] !== this.options.unitId) {
// answer for wrong device
this.log.debug('received answer for wrong ID ' + buffer[0] + ', expected ' + this.options.unitId);
}
// emit data event and let the
// listener handle the pdu
this.emit('data', pdu.slice(1, pdu.length - 2), pdu[0]);
} else {
this.log.error('Wrong CRC for frame: ' + toStrArray(pdu));
// reset buffer and try again
buffer = new Buffer(0);
break;
}
buffer = buffer.slice(pdu.length, buffer.length);
}
};
let onError = () => {
this.log.error('Client in error state.');
socket.destroy();
};
let onSend = (pdu, unitId) => {
this.log.debug('Sending pdu to the socket.');
let pkt = Put()
.word8((unitId === undefined ? this.options.unitId : unitId) || 0) // unit id
.put(pdu); // the actual pdu
let buf = pkt.buffer();
let crc16 = crc.crc16modbus(buf);
pkt = pkt.word16le(crc16).buffer();
socket.write(pkt);
};
this.connect = () => {
this.setState('connect');
connect();
return this;
};
this.reconnect = () => {
if (!this.inState('closed')) {
return this;
}
closedOnPurpose = false;
reconnect = true;
this.log.debug('Reconnecting client.');
socket.end();
return this;
};
this.close = () => {
closedOnPurpose = true;
this.log.debug('Closing client on purpose.');
socket.end();
return this;
};
init();
});

View File

@ -1,156 +0,0 @@
'use strict';
const stampit = require('stampit');
const Put = require('put');
const Net = require('net');
const ModbusCore = require('../modbus-client-core.js');
module.exports = stampit()
.compose(ModbusCore)
.init(function () {
let reqId = 0;
let currentRequestId = reqId;
let closedOnPurpose = false;
let reconnect = false;
let buffer = new Buffer(0);
let trashRequestId;
let socket;
let init = () => {
this.setState('init');
let tcp = this.options.tcp;
tcp.protocolVersion = tcp.protocolVersion || 0;
tcp.port = tcp.port || 502;
tcp.host = tcp.host || 'localhost';
tcp.autoReconnect = tcp.autoReconnect || false;
tcp.reconnectTimeout = tcp.reconnectTimeout || 0;
this.on('send', onSend);
this.on('newState_error', onError);
this.on('trashCurrentRequest', onTrashCurrentRequest);
//this.on('stateChanged', this.log.debug);
};
let connect = () => {
this.setState('connect');
if (!socket) {
socket = new Net.Socket();
socket.on('connect', onSocketConnect);
socket.on('close', onSocketClose);
socket.on('error', onSocketError);
socket.on('data', onSocketData);
}
socket.connect(this.options.tcp.port, this.options.tcp.host);
};
let onSocketConnect = () => {
this.emit('connect');
this.setState('ready');
};
let onSocketClose = hadErrors => {
this.log.debug('Socket closed with error', hadErrors);
this.setState('closed');
this.emit('close');
if (!closedOnPurpose && (this.options.tcp.autoReconnect || reconnect)) {
setTimeout(() => {
reconnect = false;
connect();
}, this.options.tcp.reconnectTimeout);
}
};
let onSocketError = err => {
this.log.error('Socket Error', err);
this.setState('error');
this.emit('error', err);
};
let onSocketData = data => {
buffer = Buffer.concat([buffer, data]);
while (buffer.length > 8) {
// http://www.simplymodbus.ca/TCP.htm
// 1. extract mbap
const id = buffer.readUInt16BE(0);
//const protId = buffer.readUInt16BE(2);
const len = buffer.readUInt16BE(4);
const unitId = buffer.readUInt8(6);
// 2. extract pdu
if (buffer.length < 7 + len - 1) {
break;
}
const pdu = buffer.slice(7, 7 + len - 1);
if (id === trashRequestId) {
this.log.debug('current mbap contains trashed request id.');
} else {
// emit data event and let the
// listener handle the pdu
this.emit('data', pdu, unitId);
}
buffer = buffer.slice(pdu.length + 7, buffer.length);
}
};
let onError = err => {
this.log.error('Client in error state.');
socket.destroy();
};
let onSend = (pdu, unitId) => {
reqId = (reqId + 1) % 0xffff;
let pkt = Put()
.word16be(reqId) // transaction id
.word16be(this.options.tcp.protocolVersion) // protocol version
.word16be(pdu.length + 1) // pdu length
.word8((unitId === undefined ? this.options.unitId : unitId) || 0) // unit id
.put(pdu) // the actual pdu
.buffer();
currentRequestId = reqId;
socket.write(pkt);
};
let onTrashCurrentRequest = () => trashRequestId = currentRequestId;
this.connect = () => {
connect();
return this;
};
this.reconnect = () => {
if (!this.inState('closed')) {
return this;
}
closedOnPurpose = false;
reconnect = true;
this.log.debug('Reconnecting client.');
socket.end();
return this;
};
this.close = () => {
closedOnPurpose = true;
this.log.debug('Closing client on purpose.');
socket.end();
return this;
};
init();
});

View File

@ -1,149 +0,0 @@
'use strict';
const stampit = require('stampit');
const ModbusServerCore = require('../modbus-server-core.js');
const StateMachine = require('stampit-state-machine');
const Put = require('put');
const net = require('net');
module.exports = stampit()
.compose(ModbusServerCore)
.compose(StateMachine)
.init(function () {
let server;
let socketCount = 0;
let fifo = [];
let clients = [];
let buffer = new Buffer(0);
let init = () => {
let tcp = this.options.tcp;
tcp.port = tcp.port || 502;
tcp.hostname = tcp.hostname || '0.0.0.0';
server = net.createServer();
server.on('connection', s => {
this.log.debug('new connection', s.address());
clients.push(s);
initiateSocket(s);
this.emit('connection', s.address());
});
server.on('disconnect', s => {
this.emit('close', s.address());
});
server.listen(tcp.port, tcp.hostname, err => {
if (err) {
this.log.debug('error while listening', err);
this.emit('error', err);
}
});
this.log.debug('server is listening on port', tcp.hostname + ':' + tcp.port);
this.on('newState_ready', flush);
this.setState('ready');
};
let onSocketEnd = (socket, socketId) => {
return () => {
this.emit('close');
this.log.debug('connection closed, socket', socketId);
//clients[socketId-1].destroy();
delete clients[socketId - 1];
};
};
let onSocketData = (socket, socketId) => {
return data => {
buffer = Buffer.concat([buffer, data]);
while (buffer.length > 8) {
// 1. extract mbap
const len = buffer.readUInt16BE(4);
const request = {
transId: buffer.readUInt16BE(0),
protocolVer: buffer.readUInt16BE(2),
untiId: buffer.readUInt8(6)
};
// 2. extract pdu
if (buffer.length < 7 + len - 1) {
break; // wait for next bytes
}
const pdu = buffer.slice(7, 7 + len - 1);
// emit data event and let the
// listener handle the pdu
fifo.push({request: request, pdu: pdu, socket: socket});
flush();
buffer = buffer.slice(pdu.length + 7, buffer.length);
}
};
};
let flush = () => {
if (this.inState('processing')) {
return;
}
if (!fifo.length) {
return;
}
this.setState('processing');
let current = fifo.shift();
this.onData(current.pdu, response => {
this.log.debug('sending tcp data');
let pkt = Put()
.word16be(current.request.transId) // transaction id
.word16be(current.request.protocolVer) // protocol version
.word16be(response.length + 1) // pdu length
.word8(current.request.untiId) // unit id
.put(response) // the actual pdu
.buffer();
current.socket.write(pkt);
this.setState('ready');
});
};
let onSocketError = (socket, socketCount) => {
return e => {
this.emit('error', e);
this.log.error('Socket error', e);
};
};
let initiateSocket = socket => {
socketCount += 1;
socket.on('end', onSocketEnd(socket, socketCount));
socket.on('data', onSocketData(socket, socketCount));
socket.on('error', onSocketError(socket, socketCount));
};
this.close = cb => {
for (let c in clients) {
if (clients.hasOwnProperty(c)) {
clients[c].destroy()
}
}
server.close(() => {
server.unref();
cb && cb();
});
};
this.getClients = () => clients;
init();
});