-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
51 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,37 @@ | ||
|
||
function createReader({ | ||
LEN_HEADER = 2, | ||
LEN_LENGTH = 2, | ||
LEN_CHECKSUM = 2 | ||
}, fn){ | ||
const STATE_HEADER_1 = 0x42; | ||
const STATE_HEADER_2 = 0x4d; | ||
const STATE_LENGTH = 2; | ||
const STATE_DATA = 3; | ||
var flag = STATE_HEADER_1, index, len, buffer = Buffer.alloc(0); | ||
return function(chunk){ | ||
const STATE_HEADER_1 = 0x42; | ||
const STATE_HEADER_2 = 0x4d; | ||
const STATE_LENGTH = 2; | ||
const STATE_DATA = 3; | ||
|
||
const LEN_HEADER = 2; | ||
const LEN_CHECKSUM = 2; | ||
|
||
function createReader(fn){ | ||
let state = STATE_HEADER_1, buffer = Buffer.alloc(0), len; | ||
return chunk => { | ||
buffer = Buffer.concat([ buffer, chunk ]); | ||
for(var i = 0; i < buffer.length; i++){ | ||
if(flag === STATE_HEADER_1 && buffer[i] === STATE_HEADER_1){ | ||
flag = STATE_HEADER_2; | ||
for(const i = 0; i < buffer.length; i++){ | ||
if(state === STATE_HEADER_1 && buffer[i] === STATE_HEADER_1){ | ||
state = STATE_HEADER_2; | ||
continue; | ||
} | ||
if(flag === STATE_HEADER_2 && buffer[i] === STATE_HEADER_2){ | ||
flag = STATE_LENGTH; | ||
index = ++i; | ||
if(state === STATE_HEADER_2 && buffer[i] === STATE_HEADER_2){ | ||
state = STATE_LENGTH; | ||
continue; | ||
} | ||
if(flag === STATE_LENGTH && buffer.length - index >= LEN_LENGTH){ | ||
if(state === STATE_LENGTH){ | ||
len = buffer.readUInt16BE(index); | ||
flag = STATE_DATA; | ||
state = STATE_DATA; | ||
continue; | ||
} | ||
if(flag === STATE_DATA && buffer.length - index >= len + LEN_CHECKSUM){ | ||
if(state === STATE_DATA){ | ||
fn(buffer.slice(index - LEN_HEADER, index + len + LEN_CHECKSUM)); | ||
buffer = buffer.slice(index + len + LEN_CHECKSUM); | ||
flag = STATE_HEADER_1; | ||
state = STATE_HEADER_1; | ||
} | ||
} | ||
}; | ||
} | ||
|
||
|
||
module.exports = createReader; |