forked from LIU9293/weigeng-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.js
110 lines (91 loc) · 2.41 KB
/
controller.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const dgram = require('dgram')
const { parseData, packData } = require('./utils')
class WeigengController {
constructor ({ port = 60000, selfPort = 6000 }) {
this.originalIp = '255.255.255.255'
this.selfPort = selfPort
this.port = port
this.messageQueue = []
this.socket = this.init.bind(this)
this.sendData = this.sendData.bind(this)
this.broadcastData = this.broadcastData.bind(this)
this.search = this.search.bind(this)
this.getStatus = this.getStatus.bind(this)
this.openDoor = this.openDoor.bind(this)
this.getIp = this.getIp.bind(this)
this.init()
}
init () {
const socket = dgram.createSocket('udp4')
this.socket = socket
socket.on('error', err => {
console.error(`[WeigengController] Lost UPD connection:\n${err.stack}.`)
console.log('[WeigengController] Will try to reconnect in 10s...')
socket.close()
setTimeout(this.init, 10 * 1000)
})
socket.on('message', (msg, rinfo) => {
const message = parseData(msg)
console.log(
`[UDP] Got message from ${rinfo.address}:${rinfo.port}.`,
JSON.stringify(message)
)
if (message.funcName === 'Search') {
const { serial, subNet, gateway, mac } = message
this.serial = serial
this.ip = rinfo.address
this.subNet = subNet
this.gateway = gateway
this.mac = mac
}
if (message.funcName === 'OpenDoor') {
this.messageQueue.push({
timestamp: new Date().getTime()
})
}
})
socket.bind(this.selfPort)
setTimeout(this.search, 1000)
}
sendData (funcCode, payload) {
this.socket.setBroadcast(false)
const data = packData(funcCode, payload, this.serial)
this.socket.send(
data,
0,
data.byteLength,
this.port,
this.ip,
err => {
if (err) console.error(err)
}
)
}
broadcastData (funcCode, payload) {
this.socket.setBroadcast(true)
const data = packData(funcCode, payload, this.serial)
this.socket.send(
data,
0,
data.byteLength,
this.port,
this.originalIp,
err => {
if (err) console.error(err)
}
)
}
search () {
this.broadcastData(0x94)
}
getStatus () {
this.broadcastData(0x20)
}
getIp () {
this.broadcastData(0x92)
}
openDoor (n) {
this.broadcastData(0x40, n)
}
}
module.exports = WeigengController