-
Notifications
You must be signed in to change notification settings - Fork 9
/
hunt.js
61 lines (50 loc) · 1.4 KB
/
hunt.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
const { Client } = require('node-ssdp')
const { capitalcase } = require('stringcase')
const manifest = require('../package.json')
const defaultOptions = {
duration: 2500,
}
module.exports = (callback, options = defaultOptions) => {
let devices = {}
const opts = typeof callback === 'object'
? callback
: options
return new Promise((resolve, reject) => {
const timerRef = setTimeout(() => {
if (typeof callback === 'function') callback(devices)
resolve(devices)
}, opts.duration || 2500)
const client = new Client()
client.search('ssdp:all')
client.on('response', (headers, statusCode, rinfo) => {
const searchTarget = headers.ST
if (!(searchTarget.match(/^bigfoot:/) || {}).input) {
return // Do nothing
}
// Enable to hunt only one device
if (opts.id === headers.USN) {
clearTimeout(timerRef)
return resolve(parseResponse(headers, statusCode, rinfo))
}
devices = {
...devices,
[headers.USN]: parseResponse(headers, statusCode, rinfo),
}
})
})
}
function parseResponse (headers, statusCode, rinfo) {
const topic = headers.ST.split(':').pop()
return {
id: headers.USN,
topic: capitalcase(topic.toLowerCase()),
name: 'Bigfoot',
brand: 'Bigfoot',
state: {},
meta: {
rinfo,
...headers,
bigfoot_version: manifest.version,
},
}
}