forked from fmandal/MMM-YrThen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
node_helper.js
61 lines (55 loc) · 1.88 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
60
61
const NodeHelper = require('node_helper');
module.exports = NodeHelper.create({
start: function() {
this.config = null;
this.forecastUrl = '';
console.log("MMM-YrThen: Starting helper for MMM-YrThen");
},
socketNotificationReceived: function(notification, payload) {
if (notification === 'GET_YRTHEN_FORECAST') {
this.config = payload.config;
this.forecastUrl = payload.forecastUrl;
if (!this.forecastUrl) {
console.error('MMM-YrThen: forecastUrl is required');
return;
}
this.getForecastFromYrThen();
}
},
async getForecastFromYrThen() {
try {
const https = require('https'); // Use require instead of dynamic import
const options = {
method: 'GET',
hostname: new URL(this.forecastUrl).hostname,
path: new URL(this.forecastUrl).pathname,
headers: {
'User-Agent': `MagicMirror/${this.config.version}` // Add module version to User-Agent
}
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const locationData = { forecast: JSON.parse(data) };
this.sendSocketNotification('YRTHEN_FORECAST_DATA', locationData);
} catch (error) {
console.error(`MMM-YrThen: Error parsing JSON response: ${error}`);
this.sendSocketNotification('YRTHEN_FORECAST_ERROR', error);
}
});
});
req.on('error', (error) => {
console.error(`MMM-YrThen: Error fetching forecast: ${error}`);
this.sendSocketNotification('YRTHEN_FORECAST_ERROR', error);
});
req.end();
} catch (error) {
console.error(`MMM-YrThen: Error fetching forecast: ${error}`);
this.sendSocketNotification('YRTHEN_FORECAST_ERROR', error);
}
}
});