This repository has been archived by the owner on Nov 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbusstopfetcher.js
103 lines (86 loc) · 2.13 KB
/
busstopfetcher.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
/* Magic Mirror
* Node Helper: MMM-HK-KMB - BusStopFetcher
*
* By Winston / https://github.com/winstonma
* AGPL-3.0 Licensed.
*/
const Log = require("../../js/logger.js");
const cron = require('node-cron');
const Kmb = require('js-kmb-api').default;
/**
* Responsible for requesting an update and broadcasting the data.
*
* @param {string} stopID stop ID of the stop
* @class
*/
const BusStopFetcher = function (stopID) {
const self = this;
let item = null;
const langTable = {
'zh-tw': 'zh-hant',
'zh-hk': 'zh-hant',
'zh-cn': 'zh-hans'
}
let localStorage;
const lang = langTable[config.language] || 'en';
const kmb = new Kmb(lang, localStorage);
const stop = stopID ? new kmb.Stop(stopID) : null;
// Create a schduler to update the bustop info (every 5am)
cron.schedule('* 5 * * *', () => {
Log.log(`BusStop-Fetcher: Fetching stop info for stop ID: ${stopID}`);
fetchBusStop();
}, {
timezone: "Asia/Hong_Kong"
});
let fetchFailedCallback = function () { };
let itemsReceivedCallback = function () { };
/* private methods */
/**
* Request the stop info
*/
const fetchBusStop = function () {
stop.getStoppings()
.then(data => {
item = data;
self.broadcastItems();
})
.catch(error => {
Log.error(error);
fetchFailedCallback(self, error);
})
};
/* public methods */
/**
* Initiate fetchBusStop();
*/
this.startFetch = function () {
fetchBusStop();
};
/**
* Broadcast the existing item.
*/
this.broadcastItems = function () {
if (item == null) {
Log.info("BusStop-Fetcher: No item to broadcast yet.");
return;
}
Log.info(`BusStop-Fetcher: Broadcasting item for stop ID ${stopID}`);
itemsReceivedCallback(self);
};
this.onReceive = function (callback) {
itemsReceivedCallback = callback;
};
this.onError = function (callback) {
fetchFailedCallback = callback;
};
this.stopID = function () {
return stopID;
};
this.item = function () {
return item;
};
this.stopName = function () {
return stop.name;
}
};
module.exports = BusStopFetcher;