This repository has been archived by the owner on Mar 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
statusfetcher.js
113 lines (92 loc) · 2.12 KB
/
statusfetcher.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
var Client = require("node-rest-client").Client;
var StatusFetcher = function(url, user, pass, reloadInterval) {
var self = this;
var reloadTimer = null;
var status = {};
var fetchFailedCallback = function() {};
var statusReceivedCallback = function() {};
var opts = {
mimetypes: {
"json": ["application/json"]
}
};
if (user && pass) {
opts.user = user;
opts.password = pass;
}
var apiClient = new Client(opts);
apiClient.registerMethod("getStatus", url, "GET");
/* fetchStatus()
* Initiates status fetch.
*/
var fetchStatus = function() {
clearTimeout(reloadTimer);
reloadTimer = null;
apiClient.methods.getStatus(handleApiResponse);
};
var handleApiResponse = function(data, response) {
if (data === undefined) {
fetchFailedCallback(self, "Received data empty or invalid.");
return;
}
status = data;
self.broadcastStatus();
scheduleTimer();
}
/* scheduleTimer()
* Schedule the timer for the next update.
*/
var scheduleTimer = function() {
//console.log("Schedule update timer.");
clearTimeout(reloadTimer);
reloadTimer = setTimeout(function() {
fetchStatus();
}, reloadInterval);
};
/* public methods */
/* startFetch()
* Initiate fetchStatus();
*/
this.startFetch = function() {
fetchStatus();
};
/* broadcastStatus()
* Broadcast the existing trains.
*/
this.broadcastStatus = function() {
statusReceivedCallback(self);
};
/* onReceive(callback)
* Sets the on success callback
*
* argument callback function - The on success callback.
*/
this.onReceive = function(callback) {
statusReceivedCallback = callback;
};
/* onError(callback)
* Sets the on error callback
*
* argument callback function - The on error callback.
*/
this.onError = function(callback) {
fetchFailedCallback = callback;
};
/* status()
* Returns the status of this fetcher.
*
* return string - The status of this fetcher.
*/
this.status = function() {
return status;
};
/* url()
* Returns the url of this fetcher.
*
* return string - The url of this fetcher.
*/
this.url = function() {
return url;
};
};
module.exports = StatusFetcher;