-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (75 loc) · 2.34 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
83
84
85
86
87
88
/*
* hue-discover
* https://github.com/jsfi/hue-discover
*
* Copyright (c) 2015 Martin Sachse
* Licensed under the MIT license.
*/
'use strict';
const ssdp = require('peer-ssdp');
const uuid = require('node-uuid');
const got = require('got');
module.exports = function(options) {
let configuration = Object.assign({
timeout: 45000,
bridges: 1,
find: 'meethue.com'
}, options);
return new Promise(function(resolve, reject) {
let peer = ssdp.createPeer();
let usn = uuid.v4();
let location = uuid.v4();
let server = 'hue-discover-' + usn.split('-').pop();
let bridges = [];
let timer;
peer.on('ready', onReady)
.on('notify', onNotify)
.start();
function onReady() {
peer.alive({
NT: 'upnp:rootdevice',
USN: 'uuid:' + uuid + '::upnp:rootdevice',
LOCATION: 'http://{{networkInterfaceAddress}}/upnp/devices/' + location + configuration.description,
SERVER: server
});
peer.search({
ST: 'upnp:rootdevice'
});
timer = setTimeout(notFound, configuration.timeout);
}
function onNotify(headers, device) {
if (!headers.LOCATION) {
return;
}
got(headers.LOCATION)
.then(description => {
if (~description.body.indexOf(configuration.find)) {
bridges.push(device.address);
if (bridges.length == configuration.bridges) {
resolve(bridges);
close();
}
}
}).catch(e => {
if (e.code != 'ECONNREFUSED') {
reject(e);
}
});
}
function close() {
clearTimeout(timer);
peer.byebye({
NT: 'upnp:rootdevice',
USN: 'uuid:' + uuid + '::upnp:rootdevice',
LOCATION: 'http://{{networkInterfaceAddress}}/upnp/devices/' + location + configuration.description,
SERVER: server
}, function () {
peer.close();
});
}
function notFound() {
resolve(bridges);
close();
}
});
};