forked from CFenner/MMM-Sonos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
executable file
·59 lines (51 loc) · 1.54 KB
/
node_helper.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
/* Magic Mirror 2
* Module: MMM-Sonos
*
* By Christopher Fenner https://github.com/CFenner
* Modified by Snille https://github.com/Snille
* MIT Licensed.
*/
var NodeHelper = require('node_helper');
var http = require('http');
var https = require('https');
var url = require('url');
module.exports = NodeHelper.create({
start: function () {
console.log('Sonos helper started ...');
},
// Subclass socketNotificationReceived.
socketNotificationReceived: function(notification, targetUrl) {
if (notification === 'SONOS_UPDATE') {
const self = this;
// Parse the URL to determine the protocol.
const parsedUrl = new url.URL(targetUrl);
const protocol = parsedUrl.protocol === 'https:' ? https : http;
// Make the HTTP or HTTPS request.
const req = protocol.get(targetUrl, (res) => {
let data = '';
// Accumulate data chunks.
res.on('data', (chunk) => {
data += chunk;
});
// Handle response end.
res.on('end', () => {
if (res.statusCode === 200) {
try {
self.sendSocketNotification('SONOS_DATA', JSON.parse(data));
} catch (err) {
console.error('Error parsing JSON:', err);
}
} else {
console.error(`Request failed. Status code: ${res.statusCode}`);
}
});
});
// Handle request errors.
req.on('error', (err) => {
console.error('Request error:', err);
});
// End the request.
req.end();
}
}
});