-
Notifications
You must be signed in to change notification settings - Fork 2
/
MessageHeader.js
45 lines (40 loc) · 1.17 KB
/
MessageHeader.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
class MessageHeader {
constructor (deviceId, replyExpected, s, f, messageType, systemBytes) {
this.DeviceId = deviceId
this.ReplyExpected = replyExpected
// Message stream number
this.S = s
// Message function number
this.F = f
this.MessageType = messageType
this.SystemBytes = systemBytes
}
encode () {
// Write to buffer
this.buffer = new Buffer(10)
// DeviceId
this.buffer.writeUInt16BE(this.DeviceId, 0);
// S
this.buffer.writeUInt8(this.S | (this.ReplyExpected ? 128 : 0), 2)
// F
this.buffer.writeUInt8(this.F, 3)
this.buffer.writeUInt8(0, 4)
// MessageType
this.buffer.writeUInt8(this.MessageType, 5)
// SystemBytes
this.buffer.writeInt32BE(this.SystemBytes, 6)
return this.buffer
}
static decode (buf) {
// Decode from buffer
return new MessageHeader(
buf.readUInt16BE(0), // DeviceId
Boolean((buf.readUInt8(2) & 128)), // ReplyExpected
(buf.readUInt8(2) & 63), // S
buf.readUInt8(3), // F
buf.readUInt8(5), // MessageType
buf.readInt32BE(6) // SystemBytes
)
}
}
module.exports = MessageHeader