-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_helper.js
101 lines (82 loc) · 2.99 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
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
let NodeHelper = require("node_helper");
let validUrl = require("valid-url");
let https = require('https');
require('ssl-root-cas').inject();
const host = "https://data.smartdublin.ie/";
module.exports = NodeHelper.create({
start: function () {
console.log("Starting module: " + this.name);
this.bustimes = [];
this.config = {};
this.updateTimer = null;
},
socketNotificationReceived: function (notification, payload) {
if (notification === "DUBLIN_BUS_TIMES_START_WORKER") {
this.config = payload.config;
this.scheduleUpdate(this.config.initialLoadDelay);
console.log("Started dublin bus scheduler");
} else if (notification === "DUBLIN_BUS_TIMES_STOP_WORKER") {
clearTimeout(this.updateTimer);
console.log("Stopped dublin bus scheduler");
}
},
scheduleUpdate: function (delay) {
let nextLoad = this.config.updateInterval;
if (typeof delay !== "undefined" && delay >= 0) {
nextLoad = delay;
}
let self = this;
clearTimeout(this.updateTimer);
this.updateTimer = setTimeout(function () {
self.callDublinBus();
}, nextLoad);
},
callDublinBus: function () {
let url = `${host}cgi-bin/rtpi/realtimebusinformation?stopid=${this.config.stopNumber}`;
let self = this;
if (!validUrl.isUri(url)) {
console.error("Invalid URL to Dublin bus: " + url);
self.sendSocketNotification("DUBLIN_BUS_TIMES_UNKNOWN_ERROR");
return;
}
https.get(url, (resp) => {
if (resp.statusCode !== 200) {
console.error("Dublin bus times not available. Response code: " + payload);
self.sendSocketNotification("DUBLIN_BUS_TIMES_UNAVAILABLE");
return;
}
resp.on('data', (d) => {
self.processData(JSON.parse(d));
});
}).on('error', (e) => {
console.error(e);
self.sendSocketNotification("DUBLIN_BUS_TIMES_UNKNOWN_ERROR");
});
},
processData: function (data) {
let times = data.results.map(result => {
let route = result.route;
let duetime = result.duetime;
if (duetime === "Due") {
return `${route} is due!`;
} else {
let minsMsg = null;
if (duetime === "1") {
minsMsg = "min";
} else {
minsMsg = "mins";
}
return `${route} - ${duetime} ${minsMsg}`;
}
});
if (times.length === 0) {
times.push("There are no bus times available");
}
this.bustimes = times;
this.broadcastDublinbusTimes();
this.scheduleUpdate();
},
broadcastDublinbusTimes: function () {
this.sendSocketNotification("DUBLIN_BUS_TIMES_RECEIVED", this.bustimes);
}
});