-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
420 lines (358 loc) · 16.8 KB
/
index.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/**
Copyright 2017 LGS Innovations
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
(() => {
'use strict';
const TemperatureCrudManager = require('./lib/crud-manager/temperature-crud-manager.js');
const WeightCrudManager = require('./lib/crud-manager/weight-crud-manager.js');
const DepthCrudManager = require('./lib/crud-manager/depth-crud-manager.js');
const TemperatureSettingsManager = require('./lib/settings-manager/temperature-settings-manager.js');
const WeightSettingsManager = require('./lib/settings-manager/weight-settings-manager.js');
const DepthSettingsManager = require('./lib/settings-manager/depth-settings-manager.js');
const QualitySettingsManager = require('./lib/settings-manager/quality-settings-manager.js');
var path = require('path'),
fs = require('fs'),
exec = require('child_process').exec,
filePath = path.join(__dirname, 'data.csv'),
scriptName = path.join(__dirname, 'example_executable.py'),
assert = require('assert');
class App {
constructor() {
//// STUB DRIVER CONTROLS:
// Set to true to read fake values from stub drivers
// Set to false to read real values from sensors and turn on error handling
this.temperature_stub_driver_on = false;
this.weight_stub_driver_on = false;
this.depth_stub_driver_on = false;
/////
this._temperatureCrudManager = new TemperatureCrudManager();
this._weightCrudManager = new WeightCrudManager();
this._depthCrudManager = new DepthCrudManager();
this._temperatureSettingsManager = new TemperatureSettingsManager();
this._weightSettingsManager = new WeightSettingsManager();
this._depthSettingsManager = new DepthSettingsManager();
this._qualitySettingsManager = new QualitySettingsManager();
// Time in milliseconds
this.temperatureTimeDelay = 5000;
this.weightTimeDelay = 5000;
this.depthTimeDelay = 5000;
this.temperatureRedundantFile = path.join(__dirname, 'backups/__temperatureRecords.csv');
this.weightRedundantFile = path.join(__dirname, 'backups/__weightRecords.csv');
this.depthRedundantFile = path.join(__dirname, 'backups/__depthRecords.csv');
this.filePath = path.join(__dirname, 'data.csv');
}
changeTemperatureTimeDelay(newTemperatureTimeDelay) {
this.temperatureTimeDelay = newTemperatureTimeDelay;
}
changeWeightTimeDelay(newWeightTimeDelay) {
this.weightTimeDelay = newWeightTimeDelay;
}
changeDepthTimeDelay(newDepthTimeDelay) {
this.depthTimeDelay = newDepthTimeDelay;
}
// Returns JSON object to store
// Requires compiled executable of temperature sensor code
temperatureDriver(crudManager, settingsManager, redundantFile, stub_driver_on) {
// Stub Driver: Return fake readings
if (stub_driver_on) {
var fdate = '2018/04/26'
var ftime = '07:00:36'
var fcelsius = '69.31'
var fjsonObj = {'date': fdate, 'time': ftime, 'celsius': fcelsius};
crudManager.storeData(fjsonObj); // TODO: Add error handling on fail
settingsManager.setTempReading(fcelsius);
fs.appendFile(redundantFile, JSON.stringify(fjsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Fake temperature reading backed up: ', fjsonObj);
});
console.log('FAKE: Temperature sensor recorded: ', fjsonObj);
}
else {
// TODO: Pull out this filepath into class variables or pass as argument
filePath = '/var/bits/base/modules/modules/bits-weather-dashboard/sensor_drivers/thermometer/pcsensor';
exec(filePath,
function(error, stdout, stderr) {
//Use for debugging
//console.log("stdout=",stdout);
//console.log("stderr=",stderr);
//console.log("error=",error);
if(!error) {
var split_str = String(stdout).trim().split(" ");
if (split_str.length != 5) {
console.log("ERROR: Thermometer driver returned improperly formatted string: " + stdout);
}
var date = split_str[0];
var time = split_str[1];
var fahrenheit = split_str[3].slice(0, -1);
var celsius = split_str[4].slice(0, -1);
var jsonObj = {'date': date, 'time': time, 'celsius': fahrenheit};
if (date.length != 10) {
console.log("ERROR: Thermometer date is incorrectly formatted: " + date);
return;
}
if (time.length != 8) {
console.log("ERROR: Thermometer time is incorrectly formatted: " + time);
return;
}
if (celsius < -10 || celsius > 50) {
console.log("ERROR: Thermometer reading out of bounds: " + celsius);
return;
}
if (fahrenheit < -30 || farenheit > 150) {
console.log("ERROR: Thermometer reading out of bounds: " + fahrenheit);
return;
}
crudManager.storeData(jsonObj); // TODO: Add error handling on fail
settingsManager.setTempReading(fahrenheit);
fs.appendFile(redundantFile, JSON.stringify(jsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Temperature reading backed up: ', jsonObj);
});
console.log('Temperature sensor recorded: ', jsonObj);
}
else {
console.log("ERROR with the temperature sensor");
console.log(error);
return;
}
});
}
}
// Returns JSON object to store
weightDriver(crudManager, settingsManager, redundantFile, stub_driver_on) {
var constDepthDiv = 1.05;
// Stub Driver: Return fake readings
if (stub_driver_on) {
var fdate = '2018/04/26'
var ftime = '07:00:36'
var fweight = '0.00'
var fdepthInInches = (parseFloat(fweight)/constDepthDiv).toFixed(2);
var fjsonObj = {'date': fdate, 'time': ftime, 'weight': fweight, 'estimatedDepth': fdepthInInches};
crudManager.storeData(fjsonObj); // TODO: Add error handling on fail
settingsManager.setWeightReading(fweight);
fs.appendFile(redundantFile, JSON.stringify(fjsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Fake temperature reading backed up: ', fjsonObj);
});
console.log('FAKE: Weight sensor recorded: ', fjsonObj);
}
else {
// TODO: Pull out this filepath into class variables or pass as argument
filePath = '/var/bits/base/modules/modules/bits-weather-dashboard/sensor_drivers/scale/scale.py';
exec('python3 ' + filePath,
function(error, stdout, stderr) {
//Use for debugging
//console.log("stdout=",stdout);
//console.log("stderr=",stderr);
//console.log("error=",error);
if(!error) {
var split_str = String(stdout).trim().split(" ");
if (split_str.length != 4) {
console.log("ERROR: Weight driver returned improperly formatted string: " + stdout);
}
var date = split_str[0];
var time = split_str[1];
var weight = split_str[2];
var depthInInches = (parseFloat(fweight)/constDepthDiv).toFixed(2);
if (date.length != 10) {
console.log("ERROR: Weight driver date is incorrectly formatted: " + date);
return;
}
if (time.length != 8) {
console.log("ERROR: Weight driver time is incorrectly formatted: " + time);
return;
}
if (weight < 0 || weight > 100) {
console.log("ERROR: Weight driver reading is out of bounds: " + weight);
return;
}
if (depthInInches < 0 || depthInInches > 96) {
console.log("ERROR: Weight driver depth in inches is out of bounds: " + depthInInches);
return;
}
var jsonObj = {'date': date, 'time': time, 'weight': weight, 'estimatedDepth': depthInInches};
crudManager.storeData(jsonObj); // TODO: Add error handling on fail
settingsManager.setWeightReading(weight);
fs.appendFile(redundantFile, JSON.stringify(jsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Temperature reading backed up: ', jsonObj);
});
console.log('Weight sensor recorded: ', jsonObj);
} else {
console.log("ERROR with the weight sensor");
console.log(error);
return;
}
});
}
}
// Returns JSON object to store
depthDriver(crudManager, settingsManager, redundantFile, stub_driver_on) {
var constDepthDiv = 1.05;
// Stub Driver: Return fake readings
if (stub_driver_on) {
var fdate = '2018/04/26'
var ftime = '07:00:36'
var fdepth = '12.00'
var fjsonObj = {'date': fdate, 'time': ftime, 'depth': fdepth};
crudManager.storeData(fjsonObj); // TODO: Add error handling on fail
settingsManager.setDepthReading(fdepth);
fs.appendFile(redundantFile, JSON.stringify(fjsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Fake temperature reading backed up: ', fjsonObj);
});
console.log('FAKE: Depth sensor recorded: ', fjsonObj);
}
else {
// TODO: Pull out this filepath into class variables or pass as argument
filePath = '/var/bits/base/modules/modules/bits-weather-dashboard/sensor_drivers/microbit/microbit.py';
exec('python ' + filePath,
function(error, stdout, stderr) {
//Use for debugging
//console.log("stdout=",stdout);
//console.log("stderr=",stderr);
//console.log("error=",error);
if(!error) {
var split_str = String(stdout).trim().split(" ");
if (split_str.length != 4) {
console.log("ERROR: Depth driver returned improperly formatted string: " + stdout);
}
var date = split_str[0];
var time = split_str[1];
var depth = split_str[2];
if (date.length != 10) {
console.log("ERROR: Depth driver date is incorrectly formatted: " + date);
return;
}
if (time.length != 8) {
console.log("ERROR: Depth driver time is incorrectly formatted: " + time);
return;
}
if (depth < 0 || depth > 30) {
console.log("ERROR: Depth driver reading is out of bounds: " + depth);
return;
}
var jsonObj = {'date': date, 'time': time, 'depth': depth};
crudManager.storeData(jsonObj); // TODO: Add error handling on fail
settingsManager.setDepthReading(depth);
fs.appendFile(redundantFile, JSON.stringify(jsonObj)+'\n', (err) => {
if (err) throw err;
//console.log('Temperature reading backed up: ', jsonObj);
});
console.log('Depth sensor recorded: ', jsonObj);
} else {
console.log("ERROR with the depth sensor");
console.log(error);
return;
}
});
}
}
// Compute the quality of snow based on density
qualityCompute(depthManager, qualityManager, weightManager) {
weightManager.getWeightReading()
.then(weight => {
console.log('weight reading',weight)
return Promise.all([depthManager.getDepthReading(),weight]);
})
.then(([depth,weight]) => {
console.log("weight",weight);
console.log("depth",depth);
//calculate snow quality metric
var quality = Number(weight) / (Number(depth) * 144)
let strQuality;
if (quality > 0.011) {
strQuality = "Icy";
}
else if (quality > 0.0072) {
strQuality = "Packed Snow";
}
else if (quality > 0.0025) {
strQuality = "Wet Powder";
}
else {
strQuality = "Powder";
}
console.log('QQ', strQuality)
qualityManager.setQualityReading(strQuality);
});
}
// Generic looping function, used by each sensor
loopReadDataFromFile(crudManager,settingsManager, driverFunction, timeDelay, redundantFile, stub_driver_on) {
driverFunction(crudManager, settingsManager, redundantFile, stub_driver_on);
setTimeout(this.loopReadDataFromFile.bind(this), timeDelay, crudManager, settingsManager, driverFunction, timeDelay, redundantFile);
}
readDataFromFile(callback) {
var content;
fs.readFile(self.filePath, function read(err, data) {
if (err) {
throw err;
}
content = data;
callback(data); // TODO: Replace this line with crudManager.storeData() when ported into driver
});
}
load(messageCenter) {
this._temperatureCrudManager.load(messageCenter);
this._weightCrudManager.load(messageCenter);
this._depthCrudManager.load(messageCenter);
this._temperatureSettingsManager.load(messageCenter);
this._weightSettingsManager.load(messageCenter);
this._depthSettingsManager.load(messageCenter);
this._qualitySettingsManager.load(messageCenter);
return Promise.resolve()
.then(() => console.log('Loaded Weather Dashboard Module!'))
// Temperature sensor loop
.then(() => this.loopReadDataFromFile(
this._temperatureCrudManager,
this._temperatureSettingsManager,
this.temperatureDriver,
this.temperatureTimeDelay,
this.temperatureRedundantFile,
this.temperature_stub_driver_on))
// Weight sensor loop
.then(() => this.loopReadDataFromFile(
this._weightCrudManager,
this._weightSettingsManager,
this.weightDriver,
this.weightTimeDelay,
this.weightRedundantFile,
this.weight_stub_driver_on))
// Depth sensor loop
.then(() => this.loopReadDataFromFile(
this._depthCrudManager,
this._depthSettingsManager,
this.depthDriver,
this.depthTimeDelay,
this.depthRedundantFile,
this.depth_stub_driver_on))
// Snow quality loop
.then(() => this.loopReadDataFromFile(
this._depthSettingsManager,
this._qualitySettingsManager,
this.qualityCompute,
1000,
this._weightSettingsManager));
}
unload() {
return Promise.resolve()
.then(() => console.log(this._temperatureCrudManager.unload(messageCenter)))
.then(() => console.log(this._weightCrudManager.unload(messageCenter)))
.then(() => console.log(this._depthCrudManager.unload(messageCenter)))
.then(() => console.log(this._temperatureSettingsManager.unload(messageCenter)))
.then(() => console.log(this._weightSettingsManager.unload(messageCenter)))
.then(() => console.log(this._depthSettingsManager.unload(messageCenter)))
.then(() => console.log(this._qualitySettingsManager.unload(messageCenter)));
}
}
module.exports = new App();
})();