feat: Added packet timeout for cctalk parser (#1887)

* Added packet timeout for cctalk parser

BREAKING: changed defaults to have a timeout
This commit is contained in:
maxvgi 2019-08-14 08:48:12 +04:00 • committed by Francis Gulotta
parent a7d1937f37
commit 714e438c25
4 changed files with 44 additions and 2 deletions

View file

@ -3,6 +3,13 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [4.0.0](https://github.com/serialport/node-serialport/compare/@serialport/parser-cctalk@2.0.2...@serialport/parser-cctalk@4.0.0) (2019-08-05)
### implementing packet byte timeouts due to cctalk documentation
* Added timeout parameter to constructor
* Implemented the reset of packet receiving process after timeout ([#1886])
# [3.0.0](https://github.com/serialport/node-serialport/compare/@serialport/parser-cctalk@2.0.2...@serialport/parser-cctalk@3.0.0) (2019-05-16)

View file

@ -12,12 +12,23 @@ const parser = port.pipe(new CCtalk())
parser.on('data', console.log)
*/
class CCTalkParser extends Transform {
constructor() {
constructor(maxDelayBetweenBytesMs = 50) {
super()
this.array = []
this.cursor = 0
this.lastByteFetchTime = 0
this.maxDelayBetweenBytesMs = maxDelayBetweenBytesMs
}
_transform(buffer, _, cb) {
if (this.maxDelayBetweenBytesMs > 0) {
const now = Date.now()
if (now - this.lastByteFetchTime > this.maxDelayBetweenBytesMs) {
this.array = []
this.cursor = 0
}
this.lastByteFetchTime = now
}
this.cursor += buffer.length
// TODO: Better Faster es7 no supported by node 4
// ES7 allows directly push [...buffer]

View file

@ -48,4 +48,28 @@ describe('CCTalkParser', () => {
assert.deepEqual(spy.getCall(3).args[0], Buffer.from([2, 2, 1, 252, 1, 1, 217]))
assert.deepEqual(spy.getCall(4).args[0], Buffer.from([2, 0, 1, 253, 217]))
})
it('resets incomplete message after timeout', () => {
const spy = sinon.spy()
const clock = sinon.useFakeTimers(Date.now())
const parser = new CCTalkParser(50)
parser.on('data', spy)
parser.write(Buffer.from([2, 2, 1]))
clock.tick(51)
parser.write(Buffer.from([2, 2, 1, 254, 1, 1, 217]))
assert.equal(spy.callCount, 1)
assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217]))
clock.restore()
})
it('disabled message timeout', () => {
const spy = sinon.spy()
const clock = sinon.useFakeTimers(Date.now())
const parser = new CCTalkParser(0)
parser.on('data', spy)
parser.write(Buffer.from([2, 2, 1]))
clock.tick(100)
parser.write(Buffer.from([254, 1, 1, 217]))
assert.equal(spy.callCount, 1)
assert.deepEqual(spy.getCall(0).args[0], Buffer.from([2, 2, 1, 254, 1, 1, 217]))
clock.restore()
})
})

View file

@ -1,6 +1,6 @@
{
"name": "@serialport/parser-cctalk",
"version": "3.0.0",
"version": "4.0.0",
"main": "cctalk.js",
"engines": {
"node": ">=8.6.0"