-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbraviaDiscovery.js
121 lines (101 loc) · 2.55 KB
/
braviaDiscovery.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
111
112
113
114
115
116
117
118
119
120
121
var SsdpClient = require('node-ssdp').Client;
var Q = require('q');
var wol = require('wake_on_lan');
var StringFormat = require('string-format');
var Request = require('request');
var parseString = require('xml2js').parseString;
function BraviaDiscovery(ip, mac, filter){
this.ssdpClient = new SsdpClient();
this.st = 'urn:schemas-sony-com:service:IRCC:1';
this.url = 'http://{ip}/sony';
this.ip = ip;
this.mac = mac;
this.filter = filter;
}
BraviaDiscovery.prototype.getUrl = function(){
var deferred = Q.defer();
var self = this;
this.getIp().then(function (ip){
deferred.resolve(self.url.format({ip: ip}));
}, deferred.reject);
return deferred.promise;
};
BraviaDiscovery.prototype.getIp = function(){
var deferred = Q.defer();
if (this.ip){
deferred.resolve(this.ip);
}
else{
var self = this;
var discover = function() {
ssdpDiscover(self.ssdpClient, self.st, self.filter).then(function(ip) {
self.ip = ip;
deferred.resolve(ip);
}, deferred.reject);
};
if (this.mac) {
wakeOnLan(this.mac).delay(1000).fin(discover);
} else {
discover();
}
}
return deferred.promise;
};
function wakeOnLan(mac) {
var deferred = Q.defer();
wol.wake(mac, function(error) {
if (error) {
deferred.reject(error);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
function ssdpDiscover(ssdpClient, st, filter){
var deferred = Q.defer();
var timer = null;
ssdpClient.on('response', function (headers, statusCode, rinfo){
if (statusCode == 200) {
getDescription(headers.LOCATION, filter, function (){
if (timer){
clearTimeout(timer);
timer = null;
}
ssdpClient.stop();
deferred.resolve(rinfo.address);
});
}
});
ssdpClient.search(st);
timer = setTimeout(function(){
deferred.reject("Discovery timeout");
ssdpClient.stop();
}, 4000);
return deferred.promise;
}
function getDescription(loc, filter, successAction){
var request = Request.get({
method: 'GET',
uri: loc
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
validateDescription(body, filter, successAction);
}
});
}
function validateDescription(body, filter, successAction){
parseString(body, function(err, result){
if (!err){
if (filter !== undefined) {
if (filter(result.root.device[0])) {
successAction();
};
} else {
successAction();
}
}
});
}
module.exports = BraviaDiscovery;