forked from z0mt3c/ehz-sml-reader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
82 lines (74 loc) · 2.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const EventEmitter = require('events')
const SerialPort = require('serialport')
const Readline = SerialPort.parsers.Readline
const Hoek = require('hoek')
const defaultOptions = {
port: '/dev/ttyUSB0',
portOptions: {
baudrate: 9600,
databits: 8,
stopbits: 1,
parity: 'none'
},
pattern: {
total: { regex: new RegExp('070100010800.{24}(.{16})0177'), divisor: 10000 },
t1: { regex: new RegExp('070100010801.{24}(.{8})0177'), divisor: 10000 },
t2: { regex: new RegExp('070100010802.{24}(.{8})0177'), divisor: 10000 },
w1: { regex: new RegExp('070100100700.{16}(.{8})0177'), divisor: 1 }
},
autoStart: true
}
class Reader extends EventEmitter {
constructor (options) {
super()
this.options = Hoek.applyToDefaults(defaultOptions, options || {})
if (this.options.autoStart) this.start()
}
start () {
this._chunk = ''
this._port = new SerialPort(this.options.port, this.options.portOptions)
this._parser = this._port.pipe(new Readline({delimiter:'1b1b1b1b01010101', encoding: 'hex' }))
this._parser.on('data', this._onData.bind(this))
this._port.on('error', this._onError.bind(this))
this._port.on('open', () => {
console.log("Connection established")
this.emit('open')
})
}
stop () {
this._port.stop()
}
_onData (data) {
if (data.indexOf('760') !== 0) return
let message = {}
let hasKey = false
Object.keys(this.options.pattern).forEach((key) => {
const pattern = this.options.pattern[key]
if (pattern.regex) {
const match = data.match(pattern.regex)
if (match) {
let value = match[match.length - 1]
value = parseInt(value, 16) / pattern.divisor
message[key] = value
hasKey = true
}
} else if (pattern.prefix) {
const match = data.indexOf(pattern.prefix)
if (match !== -1) {
let value = data.substr(match + pattern.prefix.length + pattern.skip, pattern.parse)
value = parseInt(value, 16) / pattern.divisor
message[key] = value
hasKey = true
}
}
})
if (hasKey) {
this._lastMessage = message
this.emit('data', message)
}
}
_onError (error) {
this.emit('error', error)
}
}
module.exports = Reader