-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroadcastConnector.js
70 lines (50 loc) · 1.45 KB
/
broadcastConnector.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
const dgram = require('dgram')
const devicePort = 8000
const serverPort = 5000
const defaultInterval = 5000
class BroadcastConnector {
constructor(autostart) {
this.port = devicePort
this.callback = () => {
}
this.client = dgram.createSocket('udp4')
this.client.bind(this.port)
this.client.on('listening', () => {
this.client.setBroadcast(true)
console.log('waiting for response on port ' + this.port)
})
this.client.on('message', (message, remote) => this._onMessage(message, remote))
this.info = {
type: 'ws2801'
}
this._found = false
this._discoveryLoop()
}
restart() {
this._found = false
this._discoveryLoop()
}
setInterval(interval) {
this.interval = interval
}
onServerFound(callback) {
this.callback = callback
}
_onMessage(message, remote) {
this._found = true
this.callback(message)
}
_discoveryLoop() {
if (this._found) return
console.log('discovering...')
this._discover()
setTimeout(() => this._discoveryLoop(), this.interval || defaultInterval)
}
_discover() {
const message = JSON.stringify(this.info)
this.client.send(message, 0, message.length, serverPort, '192.168.0.255', err => {
if (err) throw err;
})
}
}
module.exports = BroadcastConnector