-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopensensors.js
384 lines (346 loc) · 14.9 KB
/
opensensors.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
var Promise = require("bluebird");
var rp = require('request-promise');
var fs = require("fs");
var promiseDoWhilst = require('promise-do-whilst');
// config encapsulates opensensors-api-key
// valid keys for config are: api-key (required)
module.exports = function(config) {
var API_POST_OPTIONS = {
headers: {
Accept: "application/json",
Authorization: "api-key " + config["api-key"]
}
};
var requests_filename = "./current_requests.json";
var MAX_CONCURRENT_REQUESTS_IN_FLIGHT = 5;
// on launch delete ther requests file
if(fs.existsSync(requests_filename)) {
fs.unlinkSync(requests_filename);
console.log("Removed existing requests file: " + requests_filename);
}
// create it blank
fs.writeFileSync(requests_filename, JSON.stringify([]));
var API_BASE_URL = "https://api.opensensors.io";
var httpGet = function(url, options){
var options = Object.assign(
{},
{
uri: url,
resolveWithFullResponse: true,
json: true,
simple: false
},
options);
return rp(options);
};
// helper (actually workhorse) method that does a GET to a URL
// it appends the augmented payloads in the response to the second argument that gets passed to it
// if the response body JSON contains a next element it recursively calls itself
var retireRequest = function(theUrl){
try {
var file_contents = fs.readFileSync(requests_filename, 'utf8');
if (file_contents.trim() == "") {
file_contents = "[]";
}
var current_requests = JSON.parse(file_contents);
// remove url from the list
var i = current_requests.indexOf(theUrl);
if (i != -1) {
current_requests.splice(i, 1);
}
fs.writeFileSync(requests_filename, JSON.stringify(current_requests));
}
catch (e) {
console.log(requests_filename + ' is corrupt - JSON parse failed');
// this is also a really bad situation, but I don't know what can be done about it
}
};
var getUntil200 = function(url){
var theUrl = url;
var requestsInFlight = 0;
var current_requests = [];
var requestCompletedSuccessfully = false;
var fatalError = null;
var gotNon200 = false;
var gotSaturated = false;
var theResponse = null;
return promiseDoWhilst(() => {
// do this promise
return Promise.try(() => {
try{
var file_contents = fs.readFileSync(requests_filename, 'utf8');
if(file_contents.trim() == ""){
file_contents = "[]";
}
current_requests = JSON.parse(file_contents);
requestsInFlight = current_requests.length;
}
catch(e){
console.log(requests_filename + ' is corrupt - JSON parse failed -- deleting it');
fs.unlinkSync(requests_filename);
file_contents = "[]";
current_requests = JSON.parse(file_contents);
requestsInFlight = current_requests.length;
}
if(requestsInFlight < MAX_CONCURRENT_REQUESTS_IN_FLIGHT) {
// if the server is not saturated, go ahead and make a request and increase the saturation level
// add this request to the list of in flight requests
// if it's not already in the list
if(current_requests.indexOf(theUrl) == -1) {
current_requests.push(theUrl);
try {
fs.writeFileSync(requests_filename, JSON.stringify(current_requests));
}
catch (e) {
console.log("Failed to write to " + requests_filename);
// this is very bad... we really shouldn't proceed at this point with this request
// it should in fact be as though we were saturated
// just as though we had gotten a 400 response, just try again sooner
console.log("Deferring request " + theUrl + " for 5 seconds");
return;
}
return Promise.try(function () {
return httpGet(theUrl, API_POST_OPTIONS);
}).then(function (response) {
if (response.statusCode !== 200) {
console.log(theUrl);
console.log(response.body);
console.log("Got Status Code " + response.statusCode + ", waiting 30 seconds before trying " + theUrl + " again");
gotNon200 = true;
}
else {
// finally! we can retire this request from the list and pass the results on
retireRequest(theUrl);
requestCompletedSuccessfully = true;
return response;
}
}).catch(function(error){
// kill this request status file
retireRequest(theUrl);
console.log("+++++++++++++++++++++++");
console.log("Error: " + error.message + " " + error.stack);
console.log("+++++++++++++++++++++++");
// fatalError = error;
gotSaturated = true; // treat it like you got a saturated result
});
}
}
else{
console.log("Saturated - Deferring request " + theUrl + " for 5 seconds");
gotSaturated = true;
}
}).then((response) => {
if(gotNon200){
return new Promise((resolve, reject) => {
setTimeout(() => {
gotNon200 = false;
gotSaturated = false;
resolve();
}, 30000);
});
}
else if(gotSaturated){
return new Promise((resolve, reject) => {
setTimeout(() => {
gotNon200 = false;
gotSaturated = false;
resolve();
}, 5000);
});
}
else{
theResponse = response;
}
});
}, () => {
// until this function return false, i.e. don't continue
return !requestCompletedSuccessfully && !fatalError;
}).then(() => {
if(!fatalError){
return theResponse;
}
else{
throw fatalError;
}
});
};
var recursiveGET = function(url, results, status, followNext){
var theUrl = url;
var theResults = results;
var theStatus = Object.assign({}, {}, status);
var theFollowNext = followNext;
console.log(theStatus.serialNumber + " Current Num Results: " + theResults.length + " -> URL: " + theUrl);
return Promise.try(function(){
return getUntil200(theUrl);
}).then(function(response){
var theResponse = response;
var augmentedPayloads = [];
if(!theResponse || !theResponse.body){
console.log("%%%%%%%%%%%%%%%%%%%%%%%%%");
console.log("% Unexpected Response: ", JSON.stringify(theResponse,null,2));
console.log("%%%%%%%%%%%%%%%%%%%%%%%%%");
}
else if(theResponse.body.messages){
augmentedPayloads = theResponse.body.messages.map(function(msg){
// as it turns out nan is not valid JSON
var body;
try {
body = msg.payload.text.replace(/':nan/g, '":null');
body = body.replace(/nan/g, 'null');
// workaround for malformation of uknown origin resulting in ' where " should be
body = body.replace(/'/g, '"');
var datum = JSON.parse(body);
datum.timestamp = msg.date;
datum.topic = msg.topic;
return datum;
}
catch(exception){
console.log(exception);
console.log(body);
return {
timestamp: msg.date,
topic: msg.topic
};
}
});
}
return Promise.try(function(){
return theResults.concat(augmentedPayloads);
}).then(function(results){
var theseResults = results;
// if there's a non-null status object provided
// lets reach into the status.filename
// and modify the entry for status.serialnumber
if(theStatus && theStatus.filename) {
var content = fs.readFileSync(theStatus.filename, 'utf8');
if(content == ""){
content = "{}";
}
var json = null;
try {
json = JSON.parse(content);
if (!json[theStatus.serialNumber]) {
json[theStatus.serialNumber] = {};
}
if (theResponse.body.messages) {
json[theStatus.serialNumber].numResults = theseResults.length + theResponse.body.messages.length;
}
else {
json[theStatus.serialNumber].complete = true;
json[theStatus.serialNumber].error = true;
json[theStatus.serialNumber].errorMessage = "No messages found.";
}
if (theseResults.length > 0) {
json[theStatus.serialNumber].timestamp = theseResults[theseResults.length - 1].timestamp;
}
if (!theResponse.body.next) {
json[theStatus.serialNumber].complete = true;
}
else {
json[theStatus.serialNumber].complete = false;
}
}
catch(err){
console.log(err);
return null;
}
if(json) {
try {
fs.writeFileSync(theStatus.filename, JSON.stringify(json));
}
catch(error){
console.log(error.message);
}
}
console.log(theStatus.serialNumber + " Wrote "+ JSON.stringify(json) + " to " + theStatus.filename);
return theseResults;
}
else {
return theseResults; // pass it through
}
}).delay(1000).then(function(newResults){
if(theFollowNext && theResponse.body.next){
console.log("Next Found on url " + theUrl);
console.log("Last timestamp: " + theResponse.body.messages[theResponse.body.messages.length - 1].date);
return recursiveGET(API_BASE_URL + theResponse.body.next, newResults, theStatus, theFollowNext);
}
else{
console.log(theStatus.serialNumber + " Next Not Found on url " + theUrl);
// console.log(response.body);
if(theResponse.body.messages && theResponse.body.messages.length > 0) {
console.log("Response contained messages field with " + theResponse.body.messages.length
+ " messages, Last timestamp: " + theResponse.body.messages[theResponse.body.messages.length - 1].date);
}
else if(!theResponse.body.messages){
console.log("Response did not contain any messages field");
}
else if(theResponse.body.messages.length === 0){
console.log("Response contained messages field with zero messages");
}
else{
console.log("Unexpected response content: ");
console.log(theResponse.body);
}
console.log("Total Results: " + newResults.length);
return newResults;
}
});
}).catch(function(error){
console.log("***********************");
console.log("Error: " + error.message + " " + error.stack);
console.log("***********************");
return [];
});
};
// this function returns a string to append to a url path
// to add the [flat] params object as a querystring
function urlParams(params){
var ret = "";
if(Object.keys(params).length > 0){ // if there are any optional params
ret += '?';
var encodeParams = Object.keys(params).map(function(key){
if(key != "status") { // special case, not an OpenSensors parameter
return key + '=' + encodeURIComponent(params[key]);
}
});
ret += encodeParams.join('&');
}
return ret;
}
// this function returns a string to append to a url path
// to add the [flat] params object as a querystring
function collectMessagesBy(x, val, params){
var API_MESSAGES_BY_PATH = "/v1/messages/" + x;
var url = API_BASE_URL + API_MESSAGES_BY_PATH;
if(!val){
console.error(x + "is required");
return Promise.resolve({});
}
url += "/" + val+ urlParams(params);
var status = params ? Object.assign({}, {}, params.status) : null;
return recursiveGET(url, [], status, true); // follow_next = true
}
// returns an array of message payloads from the API, augmented with timestamp
// valid optional param keys are "start-date", "end-date", and "dur"
function collectMessagesByDevice(device, params){
return collectMessagesBy("device", device, params);
}
// returns an array of message payloads from the API, augmented with timestamp
// valid optional param keys are "start-date", "end-date", and "dur"
function collectMessagesByTopic(topic, params){
return collectMessagesBy("topic", topic, params);
}
// returns an array of message payloads from the API, augmented with timestamp
// valid optional param keys are "start-date", "end-date", and "dur"
function collectMessagesByUser(user, params){
return collectMessagesBy("user", user, params);
}
// this is what require(opensensors)(config) actually will return
return {
messages: {
byDevice: collectMessagesByDevice,
byTopic: collectMessagesByTopic,
byUser: collectMessagesByUser
}
};
};