-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
284 lines (237 loc) · 9.1 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
var request = require('request');
var parseString = require('xml2js').parseString;
var Service, Characteristic;
actualDevice = [];
var ssdp = require('node-ssdp').Client, client = new ssdp();
http = require('http'), url = require('url'), request = require('request');
var discoverInterval = 10000; //milliseconds
var confHost = "127.0.0.1";
var logBridge ;
var lightbulbService;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-devialet-bridge", "devialet-bridge", ReceiverVolume);
}
function ReceiverVolume(log, config) {
this.log = log;
logBridge = this.log;
this.name = config['name'] || "Devialet Bridge";
this.maxVolume = config['maxVolume'] || 70; // prevent for 100% volume
this.defaultVolume = config['defaultVolume'] || 35; // prevent for 100% at start-up
this.host = confHost = config['host'];
this.lastVolume = 0;
//cap maxVolume. Devialet percentage maxes at 98 in receiver settings
if(this.maxVolume > 98)
this.maxVolume = 98;
if (!this.host) {
this.log.warn('Config is missing host/IP of receiver');
callback(new Error('No host/IP defined.'));
return;
}
searchSpeaker();
}
client.on('response', function inResponse(headers, code, rinfo) {
// console.log("Found something at "+rinfo.address+"===?"+confHost);
if(rinfo.address == confHost)
{
actualDevice["host"] = parseUri(headers.LOCATION).host;
actualDevice["port"] = parseUri(headers.LOCATION).port;
logBridge.info("Devialet Bridge found at "+actualDevice["host"]+":"+actualDevice["port"]);
}
})
function searchSpeaker()
{
logBridge.info("Seraching for Devialet bridge");
client.search('urn:schemas-upnp-org:service:RenderingControl:2');
setTimeout(function() {
if(!actualDevice["host"]) searchSpeaker();
}, discoverInterval);
if(actualDevice["host"])
{
logBridge.info("Devialet bridge found at: "+actualDevice["host"]+":"+actualDevice["port"]);
}
}
ReceiverVolume.prototype.getStatus = function(callback) {
var statusUrl = `http://${this.host}/goform/form${this.zoneName}_${this.zoneName}XmlStatus.xml`;
request.get(statusUrl, function (error, response, body) {
var xml = '';
if (!error && response.statusCode == 200) {
parseString(xml + body, function (err, result) {
callback(result.item);
}.bind(this));
}else{
reSearchPort();
callback(null);
}
}.bind(this));
}
ReceiverVolume.prototype.setControl = function (control, val, callback) {
if(!actualDevice["host"])
{
var status = "Sorry: Speakers not found yet. Try later..";
}
else
{
var status = "Set Volume to: "+val+"%";
var xml = '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
'<s:Body>'+
'<u:SetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:2">'+
'<InstanceID>0</InstanceID>'+
'<Channel>Master</Channel>'+
'<DesiredVolume>'+val+'</DesiredVolume>'+
'</u:SetVolume>'+
'</s:Body>'+
'</s:Envelope>';
var http_options = {
hostname: actualDevice["host"],
port: actualDevice["port"], //a vérifier car pas sur.
path: '/Control/LibRygelRenderer/RygelRenderingControl',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'SOAPACTION': 'urn:schemas-upnp-org:service:RenderingControl:2#SetVolume',
'Content-Length': xml.length
}
}
var req = http.request(http_options, (res) => {
res.setEncoding('utf8');
if ( res.statusCode == 200) {
this.lastVolume = val;
callback(null);
} else {
reSearchPort();
callback(res.statusCode);
}
});
req.on('error', (e) => {
this.log.warn(`problem with request: ${e.message}`);
reSearchPort();
callback(e);
});
req.write(xml);
req.end();
this.log.info(status);
}
this.log.info(status);
}
ReceiverVolume.prototype.setBrightness = function(newLevel, callback) {
if(newLevel>this.maxVolume)newLevel = this.maxVolume;
this.setControl('Volume', newLevel, callback);
}
ReceiverVolume.prototype.setPowerState = function(On, callback) {
if(On && this.lastVolume === 0){ //if Lastvolume Equals 0 it mean you just turn On the device. so Default volume.
newLevel = this.defaultVolume;
this.setControl('Volume', newLevel, callback);
this.lightbulbService.getCharacteristic(Characteristic.Brightness).getValue()
}else if(!On){
newLevel = 0;
this.setControl('Volume', newLevel, callback);
}else{
callback();
}
}
function reSearchPort(){
actualDevice["host"] = null;
actualDevice["port"] = null;
searchSpeaker();
}
ReceiverVolume.prototype.getBrightness = function(callback) {
var status ='';
if(!actualDevice["host"])
{
status = "Sorry: Speakers not found yet. Try later..";
}
else
{
status = "Get Volume.";
var xml = '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
'<s:Body>'+
'<u:GetVolume xmlns:u="urn:schemas-upnp-org:service:RenderingControl:1">'+
'<InstanceID>0</InstanceID>'+
'<Channel>Master</Channel>'+
'</u:GetVolume>'+
'</s:Body>'+
'</s:Envelope>';
var http_options = {
hostname: actualDevice["host"],
port: actualDevice["port"], //a vérifier car pas sur.
path: '/Control/LibRygelRenderer/RygelRenderingControl',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'soapaction': 'urn:schemas-upnp-org:service:RenderingControl:1#GetVolume',
'Content-Length': xml.length
}
}
var req = http.request(http_options, function(res) {
var data = "";
res.setEncoding('utf8');
if ( res.statusCode != 200) {
//there is some problem here, maybe re-try to search for port.
reSearchPort();
callback(res.statusCode);
return;
}
res.on('data', function (chunk) { data += chunk });
res.on('end', function() {
if(data.indexOf("<CurrentVolume>") > -1 && data.indexOf("</CurrentVolume>")) {
var from = data.indexOf("<CurrentVolume>") +15;
var to = data.indexOf("</CurrentVolume>") ;
var currentVolume = data.substr(from,to-from);
// this.log.info(currentVolume);
callback(null,currentVolume);
}
} );
res.on('error', (e) => {
this.log.warn(`problem with response: ${e.message}`);
callback(e, this.lastVolume);
});
});
req.on('error', (e) => {
this.log.warn(`problem with request: ${e.message}`);
reSearchPort();
callback(e, this.lastVolume);
// callback(e);
});
req.write(xml);
req.end();
this.log.info(status);
}
this.log.info(status);
}
ReceiverVolume.prototype.getServices = function() {
this.lightbulbService = new Service.Lightbulb(this.name);
this.lightbulbService
.addCharacteristic(new Characteristic.Brightness())
.on('set', this.setBrightness.bind(this))
.on('get', this.getBrightness.bind(this));
this.lightbulbService
.getCharacteristic(Characteristic.On)
.on('set', this.setPowerState.bind(this) );
return [this.lightbulbService];
}
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};