fix lots of little issues reported by codacy

This commit is contained in:
Jason Calabrese
2015-06-30 23:34:59 -07:00
parent 61f580b095
commit fd585720b8
54 changed files with 609 additions and 580 deletions
+5 -7
View File
@@ -12,13 +12,11 @@ function create (env, ctx) {
app.set('title', appInfo);
app.enable('trust proxy'); // Allows req.secure test on heroku https connections.
app.use(compression({filter: shouldCompress}));
function shouldCompress(req, res) {
//TODO: return false here if we find a condition where we don't want to compress
// fallback to standard filter function
return compression.filter(req, res);
}
app.use(compression({filter: function shouldCompress(req, res) {
//TODO: return false here if we find a condition where we don't want to compress
// fallback to standard filter function
return compression.filter(req, res);
}}));
//if (env.api_secret) {
// console.log("API_SECRET", env.api_secret);
+10 -10
View File
@@ -12,9 +12,9 @@ function config ( ) {
* First inspect a bunch of environment variables:
* * PORT - serve http on this port
* * MONGO_CONNECTION, CUSTOMCONNSTR_mongo - mongodb://... uri
* * CUSTOMCONNSTR_mongo_collection - name of mongo collection with "sgv" documents
* * CUSTOMCONNSTR_mongo_collection - name of mongo collection with `sgv` documents
* * API_SECRET - if defined, this passphrase is fed to a sha1 hash digest, the hex output is used to create a single-use token for API authorization
* * NIGHTSCOUT_STATIC_FILES - the "base directory" to use for serving
* * NIGHTSCOUT_STATIC_FILES - the `base directory` to use for serving
* static files over http. Default value is the included `static`
* directory.
*/
@@ -23,10 +23,10 @@ function config ( ) {
if (readENV('APPSETTING_ScmType') == readENV('ScmType') && readENV('ScmType') == 'GitHub') {
env.head = require('./scm-commit-id.json');
console.log("SCM COMMIT ID", env.head);
console.log('SCM COMMIT ID', env.head);
} else {
git.short(function record_git_head (head) {
console.log("GIT HEAD", head);
console.log('GIT HEAD', head);
env.head = head || readENV('SCM_COMMIT_ID') || readENV('COMMIT_HASH', '');
});
}
@@ -54,7 +54,7 @@ function config ( ) {
env.profile_collection = readENV('MONGO_PROFILE_COLLECTION', 'profile');
env.devicestatus_collection = readENV('MONGO_DEVICESTATUS_COLLECTION', 'devicestatus');
env.enable = readENV('ENABLE', "");
env.enable = readENV('ENABLE', '');
env.defaults = { // currently supported keys must defined be here
'units': 'mg/dL'
@@ -127,7 +127,7 @@ function config ( ) {
// if a passphrase was provided, get the hex digest to mint a single token
if (useSecret) {
if (readENV('API_SECRET').length < consts.MIN_PASSPHRASE_LENGTH) {
var msg = ["API_SECRET should be at least", consts.MIN_PASSPHRASE_LENGTH, "characters"];
var msg = ['API_SECRET should be at least', consts.MIN_PASSPHRASE_LENGTH, 'characters'];
var err = new Error(msg.join(' '));
// console.error(err);
throw err;
@@ -170,9 +170,9 @@ function config ( ) {
console.warn('BG_HIGH is now ' + env.thresholds.bg_high);
}
//if any of the BG_* thresholds are set, default to "simple" otherwise default to "predict" to preserve current behavior
//if any of the BG_* thresholds are set, default to `simple` otherwise default to `predict` to preserve current behavior
var thresholdsSet = readIntENV('BG_HIGH') || readIntENV('BG_TARGET_TOP') || readIntENV('BG_TARGET_BOTTOM') || readIntENV('BG_LOW');
env.alarm_types = readENV('ALARM_TYPES') || (thresholdsSet ? "simple" : "predict");
env.alarm_types = readENV('ALARM_TYPES') || (thresholdsSet ? 'simple' : 'predict');
//TODO: maybe get rid of ALARM_TYPES and only use enable?
if (env.alarm_types.indexOf('simple') > -1) {
@@ -223,8 +223,8 @@ function readENV(varName, defaultValue) {
|| process.env[varName]
|| process.env[varName.toLowerCase()];
if (typeof value === 'string' && value.toLowerCase() == 'on') value = true;
if (typeof value === 'string' && value.toLowerCase() == 'off') value = false;
if (typeof value === 'string' && value.toLowerCase() == 'on') { value = true; }
if (typeof value === 'string' && value.toLowerCase() == 'off') { value = false; }
return value != null ? value : defaultValue;
}
+36 -35
View File
@@ -3,48 +3,49 @@
var consts = require('../../constants');
function configure (app, wares, ctx) {
var express = require('express'),
api = express.Router( );
var express = require('express'),
api = express.Router( );
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw( ));
// json body types get handled as parsed json
api.use(wares.bodyParser.json( ));
// also support url-encoded content-type
api.use(wares.bodyParser.urlencoded({ extended: true }));
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw( ));
// json body types get handled as parsed json
api.use(wares.bodyParser.json( ));
// also support url-encoded content-type
api.use(wares.bodyParser.urlencoded({ extended: true }));
// List settings available
api.get('/devicestatus/', function(req, res) {
var q = req.query;
if (!q.count) {
q.count = 10;
// List settings available
api.get('/devicestatus/', function(req, res) {
var q = req.query;
if (!q.count) {
q.count = 10;
}
ctx.devicestatus.list(q, function (err, results) {
return res.json(results);
});
});
function config_authed (app, api, wares, ctx) {
api.post('/devicestatus/', /*TODO: auth disabled for quick UI testing... wares.verifyAuthorization, */ function(req, res) {
var obj = req.body;
ctx.devicestatus.create(obj, function (err, created) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
} else {
res.json(created);
}
ctx.devicestatus.list(q, function (err, results) {
return res.json(results);
});
});
});
function config_authed (app, api, wares, ctx) {
}
api.post('/devicestatus/', /*TODO: auth disabled for quick UI testing... wares.verifyAuthorization, */ function(req, res) {
var obj = req.body;
ctx.devicestatus.create(obj, function (err, created) {
if (err)
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
else
res.json(created);
});
});
if (app.enabled('api') || true /*TODO: auth disabled for quick UI testing...*/) {
config_authed(app, api, wares, ctx);
}
}
if (app.enabled('api') || true /*TODO: auth disabled for quick UI testing...*/) {
config_authed(app, api, wares, ctx);
}
return api;
return api;
}
module.exports = configure;
+2 -2
View File
@@ -19,7 +19,7 @@ function create (env, ctx) {
// Only allow access to the API if API_SECRET is set on the server.
app.disable('api');
if (env.api_secret) {
console.log("API_SECRET", env.api_secret);
console.log('API_SECRET', env.api_secret);
app.enable('api');
}
@@ -28,7 +28,7 @@ function create (env, ctx) {
app.extendedClientSettings = ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {};
env.enable.toLowerCase().split(' ').forEach(function (value) {
var enable = value.trim();
console.info("enabling feature:", enable);
console.info('enabling feature:', enable);
app.enable(enable);
});
}
+3 -3
View File
@@ -9,7 +9,7 @@ function configure (app, wares) {
'json', 'svg', 'csv', 'txt', 'png', 'html', 'js'
]));
// Status badge/text/json
api.get('/status', function (req, res, next) {
api.get('/status', function (req, res) {
var info = { status: 'ok'
, apiEnabled: app.enabled('api')
, careportalEnabled: app.enabled('api') && app.enabled('careportal')
@@ -34,13 +34,13 @@ function configure (app, wares) {
res.redirect(302, badge + '.svg');
},
js: function ( ) {
var head = "this.serverSettings =";
var head = 'this.serverSettings =';
var body = JSON.stringify(info);
var tail = ';';
res.send([head, body, tail].join(' '));
},
text: function ( ) {
res.send("STATUS OK");
res.send('STATUS OK');
},
json: function ( ) {
res.json(info);
+33 -32
View File
@@ -3,44 +3,45 @@
var consts = require('../../constants');
function configure (app, wares, ctx) {
var express = require('express'),
api = express.Router( );
var express = require('express'),
api = express.Router( );
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw( ));
// json body types get handled as parsed json
api.use(wares.bodyParser.json( ));
// also support url-encoded content-type
api.use(wares.bodyParser.urlencoded({ extended: true }));
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw( ));
// json body types get handled as parsed json
api.use(wares.bodyParser.json( ));
// also support url-encoded content-type
api.use(wares.bodyParser.urlencoded({ extended: true }));
// List treatments available
api.get('/treatments/', function(req, res) {
ctx.treatments.list({find: req.params}, function (err, results) {
return res.json(results);
});
// List treatments available
api.get('/treatments/', function(req, res) {
ctx.treatments.list({find: req.params}, function (err, results) {
return res.json(results);
});
});
function config_authed (app, api, wares, ctx) {
api.post('/treatments/', /*TODO: auth disabled for now, need to get login figured out... wares.verifyAuthorization, */ function(req, res) {
var treatment = req.body;
ctx.treatments.create(treatment, function (err, created) {
if (err) {
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
} else {
res.json(created);
}
});
});
function config_authed (app, api, wares, ctx) {
}
api.post('/treatments/', /*TODO: auth disabled for now, need to get login figured out... wares.verifyAuthorization, */ function(req, res) {
var treatment = req.body;
ctx.treatments.create(treatment, function (err, created) {
if (err)
res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
else
res.json(created);
});
});
if (app.enabled('api') && app.enabled('careportal')) {
config_authed(app, api, wares, ctx);
}
}
if (app.enabled('api') && app.enabled('careportal')) {
config_authed(app, api, wares, ctx);
}
return api;
return api;
}
module.exports = configure;
+1 -1
View File
@@ -35,7 +35,7 @@ function boot (env) {
}
function ensureIndexes (ctx, next) {
console.info("Ensuring indexes");
console.info('Ensuring indexes');
ctx.store.ensureIndexes(ctx.entries( ), ctx.entries.indexedFields);
ctx.store.ensureIndexes(ctx.treatments( ), ctx.treatments.indexedFields);
ctx.store.ensureIndexes(ctx.devicestatus( ), ctx.devicestatus.indexedFields);
+1 -1
View File
@@ -25,7 +25,7 @@ function init (env, ctx) {
}
function ender ( ) {
if (id) cancelInterval(id);
if (id) { cancelInterval(id); }
stream.emit('end');
}
+24 -23
View File
@@ -2,7 +2,6 @@
var _ = require('lodash');
var async = require('async');
var utils = require('./utils')();
var ObjectID = require('mongodb').ObjectID;
function uniq(a) {
@@ -71,7 +70,7 @@ function init(env, ctx) {
async.parallel({
entries: function (callback) {
var q = {find: {"date": {"$gte": earliest_data}}};
var q = {find: {date: {$gte: earliest_data}}};
ctx.entries.list(q, function (err, results) {
if (!err && results) {
var mbgs = [];
@@ -99,7 +98,7 @@ function init(env, ctx) {
})
}, cal: function (callback) {
//FIXME: date $gte?????
var cq = {count: 1, find: {"type": "cal"}};
var cq = {count: 1, find: {type: 'cal'}};
ctx.entries.list(cq, function (err, results) {
if (!err && results) {
var cals = [];
@@ -115,7 +114,7 @@ function init(env, ctx) {
callback();
});
}, treatments: function (callback) {
var tq = {find: {"created_at": {"$gte": new Date(treatment_earliest_data).toISOString()}}};
var tq = {find: {created_at: {$gte: new Date(treatment_earliest_data).toISOString()}}};
ctx.treatments.list(tq, function (err, results) {
if (!err && results) {
var treatments = results.map(function (treatment) {
@@ -140,7 +139,7 @@ function init(env, ctx) {
if (!err && results) {
// There should be only one document in the profile collection with a DIA. If there are multiple, use the last one.
var profiles = [];
results.forEach(function (element, index, array) {
results.forEach(function (element) {
if (element) {
if (element.dia) {
profiles[0] = element;
@@ -173,7 +172,7 @@ function init(env, ctx) {
var changesFound = false;
// if there's no updates done so far, just return the full set
if (!oldData.sgvs) return newData;
if (!oldData.sgvs) { return newData; }
function nsArrayDiff(oldArray, newArray) {
var seen = {};
@@ -203,23 +202,25 @@ function init(env, ctx) {
var compressibleArrays = ['sgvs', 'treatments', 'mbgs', 'cals'];
for (var array in compressibleArrays) {
var a = compressibleArrays[array];
if (newData.hasOwnProperty(a)) {
if (compressibleArrays.hasOwnProperty(array)) {
var a = compressibleArrays[array];
if (newData.hasOwnProperty(a)) {
// if previous data doesn't have the property (first time delta?), just assign data over
if (!oldData.hasOwnProperty(a)) {
delta[a] = newData[a];
changesFound = true;
continue;
}
// Calculate delta and assign delta over if changes were found
var deltaData = nsArrayDiff(oldData[a], newData[a]);
if (deltaData.length > 0) {
console.log('delta changes found on', a);
changesFound = true;
sort(deltaData);
delta[a] = deltaData;
// if previous data doesn't have the property (first time delta?), just assign data over
if (!oldData.hasOwnProperty(a)) {
delta[a] = newData[a];
changesFound = true;
continue;
}
// Calculate delta and assign delta over if changes were found
var deltaData = nsArrayDiff(oldData[a], newData[a]);
if (deltaData.length > 0) {
console.log('delta changes found on', a);
changesFound = true;
sort(deltaData);
delta[a] = deltaData;
}
}
}
}
@@ -238,7 +239,7 @@ function init(env, ctx) {
}
}
if (changesFound) return delta;
if (changesFound) { return delta; }
return newData;
};
+28 -27
View File
@@ -2,39 +2,40 @@
function storage (collection, ctx) {
function create(obj, fn) {
if (! obj.hasOwnProperty("created_at")){
obj.created_at = (new Date()).toISOString();
}
api().insert(obj, function (err, doc) {
fn(null, doc);
});
function create(obj, fn) {
if (! obj.hasOwnProperty('created_at')){
obj.created_at = (new Date()).toISOString();
}
api().insert(obj, function (err, doc) {
fn(null, doc);
});
}
function create_date_included(obj, fn) {
api().insert(obj, function (err, doc) {
fn(null, doc);
});
function create_date_included(obj, fn) {
api().insert(obj, function (err, doc) {
fn(null, doc);
});
}
}
function last(fn) {
return api().find({}).sort({created_at: -1}).limit(1).toArray(function (err, entries) {
if (entries && entries.length > 0)
fn(err, entries[0]);
else
fn(err, null);
});
}
function last(fn) {
return api().find({}).sort({created_at: -1}).limit(1).toArray(function (err, entries) {
if (entries && entries.length > 0) {
fn(err, entries[0]);
} else {
fn(err, null);
}
});
}
function list(opts, fn) {
var q = opts && opts.find ? opts.find : { };
return ctx.store.limit.call(api().find(q).sort({created_at: -1}), opts).toArray(fn);
}
function list(opts, fn) {
var q = opts && opts.find ? opts.find : { };
return ctx.store.limit.call(api().find(q).sort({created_at: -1}), opts).toArray(fn);
}
function api() {
return ctx.store.db.collection(collection);
}
function api() {
return ctx.store.db.collection(collection);
}
api.list = list;
+8 -7
View File
@@ -2,7 +2,6 @@
var es = require('event-stream');
var sgvdata = require('sgvdata');
var units = require('./units')();
var ObjectID = require('mongodb').ObjectID;
/**********\
@@ -86,7 +85,7 @@ function storage(env, ctx) {
// receives entire list at end of stream
function done (err, result) {
// report any errors
if (err) return fn(err, result);
if (err) { return fn(err, result); }
// batch insert a list of records
create(result, fn);
}
@@ -127,15 +126,17 @@ function storage(env, ctx) {
function getEntry(id, fn) {
with_collection(function(err, collection) {
if (err)
if (err) {
fn(err);
else
collection.findOne({"_id": ObjectID(id)}, function (err, entry) {
if (err)
} else {
collection.findOne({_id: ObjectID(id)}, function (err, entry) {
if (err) {
fn(err);
else
} else {
fn(null, entry);
}
});
}
});
}
+8 -9
View File
@@ -2,17 +2,16 @@
// Craft a JSON friendly status (or error) message.
function sendJSONStatus(res, status, title, description, warning) {
var json = {
status: status,
message: title,
description: description
};
var json = {
status: status,
message: title,
description: description
};
// Add optional warning message.
if (warning)
json.warning = warning;
// Add optional warning message.
if (warning) { json.warning = warning; }
res.status(status).json(json);
res.status(status).json(json);
}
function configure ( ) {
+115 -115
View File
@@ -7,34 +7,34 @@ var direction = require('sgvdata/lib/utils').direction;
var mqtt = require('mqtt');
var moment = require('moment');
function process(client) {
var stream = es.through(
function _write(data) {
this.push(data);
}
);
return stream;
}
function every(storage) {
function iter(item, next) {
storage.create(item, next);
function process ( ) {
var stream = es.through(
function _write(data) {
this.push(data);
}
return es.map(iter);
);
return stream;
}
function downloader() {
var opts = {
model: decoders.models.G4Download
, json: function (o) {
return o;
}
, payload: function (o) {
return o;
}
};
return decoders(opts);
function every (storage) {
function iter(item, next) {
storage.create(item, next);
}
return es.map(iter);
}
function downloader () {
var opts = {
model: decoders.models.G4Download
, json: function (o) {
return o;
}
, payload: function (o) {
return o;
}
};
return decoders(opts);
}
function toSGV (proto, vars) {
@@ -71,9 +71,9 @@ function toTimestamp (proto, receiver_time, download_time) {
var record_offset = receiver_time - proto.sys_timestamp_sec;
var record_time = download_time.clone( ).subtract(record_offset, 'second');
var obj = {
device: 'dexcom'
, date: record_time.unix() * 1000
, dateString: record_time.format( )
device: 'dexcom'
, date: record_time.unix() * 1000
, dateString: record_time.format( )
};
return obj;
}
@@ -121,7 +121,7 @@ function sgvSensorMerge(packet) {
} else {
console.info('mismatch or missing, sgv: ', sgv, ' sensor: ', sensor);
//timestamps aren't close enough so add both
if (sgv) merged.push(sgv);
if (sgv) { merged.push(sgv); }
//but the sensor will become and sgv now
if (sensor) {
sensor.type = 'sgv';
@@ -159,99 +159,99 @@ function iter_mqtt_record_stream (packet, prop, sync) {
var stream = es.readArray(list || [ ]);
var receiver_time = packet.receiver_system_time_sec;
var download_time = moment(packet.download_timestamp);
function map(item, next) {
var timestamped = toTimestamp(item, receiver_time, download_time.clone( ));
var r = sync(item, timestamped);
if (!('type' in r)) {
r.type = prop;
}
console.log("ITEM", item, "TO", prop, r);
next(null, r);
function map(item, next) {
var timestamped = toTimestamp(item, receiver_time, download_time.clone( ));
var r = sync(item, timestamped);
if (!('type' in r)) {
r.type = prop;
}
return stream.pipe(es.map(map));
console.log('ITEM', item, 'TO', prop, r);
next(null, r);
}
return stream.pipe(es.map(map));
}
function configure(env, ctx) {
var uri = env['MQTT_MONITOR'];
var opts = {
encoding: 'binary',
clean: false,
clientId: env.mqtt_client_id
};
var client = mqtt.connect(uri, opts);
var downloads = downloader();
client.subscribe('sgvs');
client.subscribe('published');
client.subscribe('/downloads/protobuf', {qos: 2}, granted);
client.subscribe('/uploader', granted);
client.subscribe('/entries/sgv', granted);
function granted() {
console.log('granted', arguments);
}
var uri = env['MQTT_MONITOR'];
var opts = {
encoding: 'binary',
clean: false,
clientId: env.mqtt_client_id
};
var client = mqtt.connect(uri, opts);
var downloads = downloader();
client.subscribe('sgvs');
client.subscribe('published');
client.subscribe('/downloads/protobuf', {qos: 2}, granted);
client.subscribe('/uploader', granted);
client.subscribe('/entries/sgv', granted);
function granted() {
console.log('granted', arguments);
}
client.on('message', function (topic, msg) {
console.log('topic', topic);
console.log(topic, 'on message', 'msg', msg.length);
switch (topic) {
case '/uploader':
console.log({type: topic, msg: msg.toString()});
break;
case '/downloads/protobuf':
var b = new Buffer(msg, 'binary');
console.log("BINARY", b.length, b.toString('hex'));
try {
var packet = downloads.parse(b);
if (!packet.type) {
packet.type = topic;
}
} catch (e) {
console.log("DID NOT PARSE", e);
break;
}
console.log('DOWNLOAD msg', msg.length, packet);
console.log('download SGV', packet.sgv[0]);
console.log('download_timestamp', packet.download_timestamp, new Date(Date.parse(packet.download_timestamp)));
console.log("WRITE TO MONGO");
var download_timestamp = moment(packet.download_timestamp);
if (packet.download_status === 0) {
es.readArray(sgvSensorMerge(packet)).pipe(ctx.entries.persist(function empty(err, result) {
console.log("DONE WRITING MERGED SGV TO MONGO", err, result);
}));
iter_mqtt_record_stream(packet, 'cal', toCal)
.pipe(ctx.entries.persist(function empty(err, result) {
console.log("DONE WRITING Cal TO MONGO", err, result.length);
}));
iter_mqtt_record_stream(packet, 'meter', toMeter)
.pipe(ctx.entries.persist(function empty(err, result) {
console.log("DONE WRITING Meter TO MONGO", err, result.length);
}));
}
packet.type = "download";
ctx.devicestatus.create({
uploaderBattery: packet.uploader_battery,
created_at: download_timestamp.toISOString()
}, function empty(err, result) {
console.log("DONE WRITING TO MONGO devicestatus ", result, err);
});
ctx.entries.create([ packet ], function empty(err, res) {
console.log("Download written to mongo: ", packet)
});
// ctx.entries.write(packet);
break;
default:
console.log(topic, 'on message', 'msg', msg);
// ctx.entries.write(msg);
break;
client.on('message', function (topic, msg) {
console.log('topic', topic);
console.log(topic, 'on message', 'msg', msg.length);
switch (topic) {
case '/uploader':
console.log({type: topic, msg: msg.toString()});
break;
case '/downloads/protobuf':
var b = new Buffer(msg, 'binary');
console.log('BINARY', b.length, b.toString('hex'));
try {
var packet = downloads.parse(b);
if (!packet.type) {
packet.type = topic;
}
} catch (e) {
console.log('DID NOT PARSE', e);
break;
}
});
client.entries = process(client);
client.every = every;
return client;
console.log('DOWNLOAD msg', msg.length, packet);
console.log('download SGV', packet.sgv[0]);
console.log('download_timestamp', packet.download_timestamp, new Date(Date.parse(packet.download_timestamp)));
console.log('WRITE TO MONGO');
var download_timestamp = moment(packet.download_timestamp);
if (packet.download_status === 0) {
es.readArray(sgvSensorMerge(packet)).pipe(ctx.entries.persist(function empty(err, result) {
console.log('DONE WRITING MERGED SGV TO MONGO', err, result);
}));
iter_mqtt_record_stream(packet, 'cal', toCal)
.pipe(ctx.entries.persist(function empty(err, result) {
console.log('DONE WRITING Cal TO MONGO', err, result.length);
}));
iter_mqtt_record_stream(packet, 'meter', toMeter)
.pipe(ctx.entries.persist(function empty(err, result) {
console.log('DONE WRITING Meter TO MONGO', err, result.length);
}));
}
packet.type = 'download';
ctx.devicestatus.create({
uploaderBattery: packet.uploader_battery,
created_at: download_timestamp.toISOString()
}, function empty(err, result) {
console.log('DONE WRITING TO MONGO devicestatus ', result, err);
});
ctx.entries.create([ packet ], function empty(err, res) {
console.log('Download written to mongo: ', packet)
});
// ctx.entries.write(packet);
break;
default:
console.log(topic, 'on message', 'msg', msg);
// ctx.entries.write(msg);
break;
}
});
client.entries = process(client);
client.every = every;
return client;
}
//expose for tests that don't need to connect
+1 -1
View File
@@ -114,7 +114,7 @@ function init (env, ctx) {
};
notifications.snoozedBy = function snoozedBy (notify) {
if (_.isEmpty(requests.snoozes)) return false;
if (_.isEmpty(requests.snoozes)) { return false; }
var byLevel = _.filter(requests.snoozes, function checkSnooze (snooze) {
return snooze.level >= notify.level;
+9 -9
View File
@@ -13,10 +13,10 @@ var DIRECTIONS = {
, 'RATE OUT OF RANGE': 9
};
var iob = require("./plugins/iob")();
var iob = require('./plugins/iob')();
var async = require('async');
var units = require('./units')();
var profileObject = require("./profilefunctions")();
var profileObject = require('./profilefunctions')();
function directionToTrend (direction) {
var trend = 8;
@@ -47,7 +47,7 @@ function pebble (req, res) {
//for compatibility we're keeping battery and iob here, but they would be better somewhere else
if (sgvData.length > 0) {
sgvData[0].battery = uploaderBattery ? "" + uploaderBattery : undefined;
sgvData[0].battery = uploaderBattery ? '' + uploaderBattery : undefined;
if (req.iob) {
sgvData[0].iob = iob.calcTotal(treatmentResults.slice(0, 20), profileResult, new Date(now)).display;
}
@@ -67,7 +67,7 @@ function pebble (req, res) {
if (!err && value) {
uploaderBattery = value.uploaderBattery;
} else {
console.error("req.devicestatus.tail", err);
console.error('req.devicestatus.tail', err);
}
callback();
});
@@ -89,7 +89,7 @@ function pebble (req, res) {
}
});
} else {
console.error("pebble profile error", arguments);
console.error('pebble profile error', arguments);
}
callback();
});
@@ -109,7 +109,7 @@ function pebble (req, res) {
}
});
} else {
console.error("pebble cal error", arguments);
console.error('pebble cal error', arguments);
}
callback();
});
@@ -118,7 +118,7 @@ function pebble (req, res) {
}
}
, entries: function(callback) {
var q = { count: req.count + 1, find: { "sgv": { $exists: true }} };
var q = { count: req.count + 1, find: {sgv: { $exists: true }} };
req.ctx.entries.list(q, function(err, results) {
if (!err && results) {
@@ -151,7 +151,7 @@ function pebble (req, res) {
}
});
} else {
console.error("pebble entries error", arguments);
console.error('pebble entries error', arguments);
}
callback();
});
@@ -162,7 +162,7 @@ function pebble (req, res) {
function loadTreatments(req, earliest_data, fn) {
if (req.iob) {
var q = { find: {"created_at": {"$gte": new Date(earliest_data).toISOString()}} };
var q = { find: {created_at: {$gte: new Date(earliest_data).toISOString()}} };
req.ctx.treatments.list(q, fn);
} else {
fn(null, []);
+2 -2
View File
@@ -65,11 +65,11 @@ function init() {
if (max > sbx.scaleBg(sbx.thresholds.bg_target_top)) {
rangeLabel = 'HIGH';
eventName = 'high';
if (!result.pushoverSound) result.pushoverSound = 'climb';
if (!result.pushoverSound) { result.pushoverSound = 'climb'; }
} else if (min < sbx.scaleBg(sbx.thresholds.bg_target_bottom)) {
rangeLabel = 'LOW';
eventName = 'low';
if (!result.pushoverSound) result.pushoverSound = 'falling';
if (!result.pushoverSound) { result.pushoverSound = 'falling'; }
} else {
rangeLabel = 'Check BG';
}
+1 -3
View File
@@ -1,7 +1,5 @@
'use strict';
var _ = require('lodash');
function init() {
function basal() {
@@ -13,7 +11,7 @@ function init() {
function hasRequiredInfo (sbx) {
if (!sbx.data.profile) return false;
if (!sbx.data.profile) { return false; }
if (!sbx.data.profile.hasData()) {
console.warn('For the Basal plugin to function you need a treatment profile');
+4 -6
View File
@@ -2,9 +2,7 @@
var _ = require('lodash');
var TEN_MINS = 10 * 60 * 1000;
var FIFTEEN_MINS = 15 * 60 * 1000;
function init() {
@@ -17,7 +15,7 @@ function init() {
function hasRequiredInfo (sbx) {
if (!sbx.data.profile) return false;
if (!sbx.data.profile) { return false; }
if (!sbx.data.profile.hasData()) {
console.warn('For the BolusWizardPreview plugin to function you need a treatment profile');
@@ -57,9 +55,9 @@ function init() {
bwp.checkNotifications = function checkNotifications (sbx) {
var results = sbx.properties.bwp;
if (results == undefined) return;
if (results == undefined) { return; }
if (results.lastSGV < sbx.data.profile.getHighBGTarget(sbx.time)) return;
if (results.lastSGV < sbx.data.profile.getHighBGTarget(sbx.time)) { return; }
var snoozeBWP = Number(sbx.extendedSettings.snooze) || 0.10;
var warnBWP = Number(sbx.extendedSettings.warn) || 0.50;
@@ -121,7 +119,7 @@ function init() {
bwp.updateVisualisation = function updateVisualisation (sbx) {
var results = sbx.properties.bwp;
if (results == undefined) return;
if (results == undefined) { return; }
// display text
var info = [
+1 -1
View File
@@ -38,7 +38,7 @@ function init() {
});
var info = [{label: 'Inserted:', value: moment(treatmentDate).format('lll')}];
if (message != '') info.push({label: 'Notes:', value: message});
if (message != '') { info.push({label: 'Notes:', value: message}); }
sbx.pluginBase.updatePillText(cage, {
value: age + 'h'
+6 -2
View File
@@ -35,7 +35,11 @@ function init() {
var liverSensRatio = 1;
var totalCOB = 0;
var lastCarbs = null;
if (!treatments) return {};
if (!treatments) {
return {};
}
if (typeof time === 'undefined') {
time = new Date();
}
@@ -147,7 +151,7 @@ function init() {
var prop = sbx.properties.cob;
if (prop == undefined || prop.cob == undefined) return;
if (prop == undefined || prop.cob == undefined) { return; }
var displayCob = Math.round(prop.cob * 10) / 10;
+3 -3
View File
@@ -24,7 +24,7 @@ function init() {
var totalIOB = 0
, totalActivity = 0;
if (!treatments) return {};
if (!treatments) { return {}; }
if (time === undefined) {
time = new Date();
@@ -38,8 +38,8 @@ function init() {
if (tIOB.iobContrib > 0) {
lastBolus = treatment;
}
if (tIOB && tIOB.iobContrib) totalIOB += tIOB.iobContrib;
if (tIOB && tIOB.activityContrib) totalActivity += tIOB.activityContrib;
if (tIOB && tIOB.iobContrib) { totalIOB += tIOB.iobContrib; }
if (tIOB && tIOB.activityContrib) { totalActivity += tIOB.activityContrib; }
}
});
+1 -1
View File
@@ -21,7 +21,7 @@ function init (majorPills, minorPills, statusPills, bgStatus, tooltip) {
container = minorPills
}
var pillName = "span.pill." + plugin.name;
var pillName = 'span.pill.' + plugin.name;
var pill = container.find(pillName);
var classes = 'pill ' + plugin.name;
+2 -2
View File
@@ -33,8 +33,8 @@ function init() {
autoSnoozeAlarms(sbx);
//and add some info notifications
//the notification providers (push, websockets, etc) are responsible to not sending the same notifications repeatedly
if (mbgCurrent) requestMBGNotify(lastMBG, sbx);
if (treatmentCurrent) requestTreatmentNotify(lastTreatment, sbx);
if (mbgCurrent) { requestMBGNotify(lastMBG, sbx); }
if (treatmentCurrent) { requestTreatmentNotify(lastTreatment, sbx); }
}
};
+11 -13
View File
@@ -10,18 +10,17 @@ function init(profileData) {
}
profile.loadData = function loadData(profileData) {
profile.data = _.cloneDeep(profileData);
profile.preprocessProfileOnLoad(profile.data[0]);
}
profile.data = _.cloneDeep(profileData);
profile.preprocessProfileOnLoad(profile.data[0]);
};
profile.timeStringToSeconds = function timeStringToSeconds(time) {
var split = time.split(":");
var split = time.split(':');
return parseInt(split[0])*3600 + parseInt(split[1])*60;
}
};
// preprocess the timestamps to seconds for a couple orders of magnitude faster operation
profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container)
{
profile.preprocessProfileOnLoad = function preprocessProfileOnLoad(container) {
for (var key in container) {
var value = container[key];
@@ -31,17 +30,16 @@ function init(profileData) {
if (value.time) {
var sec = profile.timeStringToSeconds(value.time);
if (!isNaN(sec)) value.timeAsSeconds = sec;
if (!isNaN(sec)) { value.timeAsSeconds = sec; }
}
}
}
};
if (profileData) profile.loadData(profileData);
if (profileData) { profile.loadData(profileData); }
profile.getValueByTime = function getValueByTime(time, valueContainer)
{
if (!time) time = new Date();
profile.getValueByTime = function getValueByTime (time, valueContainer) {
if (!time) { time = new Date(); }
// If the container is an Array, assume it's a valid timestamped value container
+2 -3
View File
@@ -2,7 +2,6 @@
var _ = require('lodash');
var crypto = require('crypto');
var units = require('./units')();
var NodeCache = require('node-cache');
function init(env, ctx) {
@@ -53,7 +52,7 @@ function init(env, ctx) {
};
pushnotify.pushoverAck = function pushoverAck (response) {
if (!response.receipt) return false;
if (!response.receipt) { return false; }
var notify = receipts.get(response.receipt);
console.info('push ack, response: ', response, ', notify: ', notify);
@@ -67,7 +66,7 @@ function init(env, ctx) {
var receiptKeys = receipts.keys();
_.forEach(receiptKeys, function eachKey (receipt) {
ctx.pushover.cancelWithReceipt(receipt, function cancelCallback (err, response) {
ctx.pushover.cancelWithReceipt(receipt, function cancelCallback (err) {
if (err) {
console.error('error canceling receipt, err: ', err);
} else {
+4 -4
View File
@@ -2,7 +2,6 @@
var _ = require('lodash');
var units = require('./units')();
var utils = require('./utils');
var profile = require('./profilefunctions')();
function init ( ) {
@@ -140,7 +139,9 @@ function init ( ) {
function roundInsulinForDisplayFormat (insulin) {
if (insulin == 0) return '0';
if (insulin == 0) {
return '0';
}
if (sbx.properties.roundingStyle == 'medtronic') {
var denominator = 0.1;
@@ -161,8 +162,7 @@ function init ( ) {
}
function unitsLabel ( ) {
if (sbx.units == 'mmol') return 'mmol/L';
return 'mg/dl';
return sbx.units == 'mmol' ? 'mmol/L' : 'mg/dl';
}
function roundBGToDisplayFormat (bg) {
+2 -1
View File
@@ -37,8 +37,9 @@ function init (env, cb, forceNewConnection) {
mongo.db = connection;
// If there is a valid callback, then invoke the function to perform the callback
if (cb && cb.call)
if (cb && cb.call) {
cb(err, mongo);
}
});
}
}
+4 -4
View File
@@ -23,10 +23,10 @@ function storage (env, ctx) {
// clean data
delete obj.eventTime;
if (!obj.carbs) delete obj.carbs;
if (!obj.insulin) delete obj.insulin;
if (!obj.notes) delete obj.notes;
if (!obj.preBolus || obj.preBolus == 0) delete obj.preBolus;
if (!obj.carbs) { delete obj.carbs; }
if (!obj.insulin) { delete obj.insulin; }
if (!obj.notes) { delete obj.notes; }
if (!obj.preBolus || obj.preBolus == 0) { delete obj.preBolus; }
if (!obj.glucose) {
delete obj.glucose;
delete obj.glucoseType;
+2
View File
@@ -1,3 +1,5 @@
'use strict';
function mgdlToMMOL(mgdl) {
return (Math.round((mgdl / 18) * 10) / 10).toFixed(1);
}
+19 -9
View File
@@ -25,15 +25,25 @@ function init() {
, offset = time == -1 ? -1 : (now - time) / 1000
, parts = {};
if (offset < MINUTE_IN_SECS * -5) parts = { value: 'in the future' };
else if (offset == -1) parts = { label: 'time ago' };
else if (offset <= MINUTE_IN_SECS * 2) parts = { value: 1, label: 'min ago' };
else if (offset < (MINUTE_IN_SECS * 60)) parts = { value: Math.round(Math.abs(offset / MINUTE_IN_SECS)), label: 'mins ago' };
else if (offset < (HOUR_IN_SECS * 2)) parts = { value: 1, label: 'hr ago' };
else if (offset < (HOUR_IN_SECS * 24)) parts = { value: Math.round(Math.abs(offset / HOUR_IN_SECS)), label: 'hrs ago' };
else if (offset < DAY_IN_SECS) parts = { value: 1, label: 'day ago' };
else if (offset <= (DAY_IN_SECS * 7)) parts = { value: Math.round(Math.abs(offset / DAY_IN_SECS)), label: 'day ago' };
else parts = { value: 'long ago' };
if (offset < MINUTE_IN_SECS * -5) {
parts = { value: 'in the future' };
} else if (offset == -1) {
parts = { label: 'time ago' };
} else if (offset <= MINUTE_IN_SECS * 2) {
parts = { value: 1, label: 'min ago' };
} else if (offset < (MINUTE_IN_SECS * 60)) {
parts = { value: Math.round(Math.abs(offset / MINUTE_IN_SECS)), label: 'mins ago' };
} else if (offset < (HOUR_IN_SECS * 2)) {
parts = { value: 1, label: 'hr ago' };
} else if (offset < (HOUR_IN_SECS * 24)) {
parts = { value: Math.round(Math.abs(offset / HOUR_IN_SECS)), label: 'hrs ago' };
} else if (offset < DAY_IN_SECS) {
parts = { value: 1, label: 'day ago' };
} else if (offset <= (DAY_IN_SECS * 7)) {
parts = { value: Math.round(Math.abs(offset / DAY_IN_SECS)), label: 'day ago' };
} else {
parts = { value: 'long ago' };
}
if (offset > DAY_IN_SECS * 7) {
parts.status = 'warn';
+1 -4
View File
@@ -1,8 +1,5 @@
'use strict';
var _ = require('lodash');
var utils = require('./utils')();
function init (env, ctx, server) {
function websocket ( ) {
@@ -56,7 +53,7 @@ function init (env, ctx, server) {
var delta = ctx.data.calculateDelta(lastData);
if (delta.delta) {
console.log('lastData full size', JSON.stringify(lastData).length,'bytes');
if (delta.sgvs) console.log('patientData update size', JSON.stringify(delta).length,'bytes');
if (delta.sgvs) { console.log('patientData update size', JSON.stringify(delta).length,'bytes'); }
emitData(delta);
} else { console.log('delta calculation indicates no new data is present'); }
}
+37 -31
View File
@@ -275,7 +275,9 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
}
function inRetroMode() {
if (!brush) return false;
if (!brush) {
return false;
}
var time = brush.extent()[1].getTime();
@@ -470,8 +472,11 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
var dotRadius = function(type) {
var radius = prevChartWidth > WIDTH_BIG_DOTS ? 4 : (prevChartWidth < WIDTH_SMALL_DOTS ? 2 : 3);
if (type == 'mbg') radius *= 2;
else if (type == 'rawbg') radius = Math.min(2, radius - 1);
if (type == 'mbg') {
radius *= 2;
} else if (type == 'rawbg') {
radius = Math.min(2, radius - 1);
}
return radius / focusRangeAdjustment;
};
@@ -493,7 +498,7 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
})
.attr('fill', function (d) { return d.color; })
.attr('opacity', function (d) { return futureOpacity(d.date.getTime() - latestSGV.x); })
.attr('stroke-width', function (d) { if (d.type == 'mbg') return 2; else return 0; })
.attr('stroke-width', function (d) { return d.type == 'mbg' ? 2 : 0; })
.attr('stroke', function (d) {
return (isDexcom(d.device) ? 'white' : '#0099ff');
})
@@ -512,33 +517,34 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
// if new circle then just display
prepareFocusCircles(focusCircles.enter().append('circle'))
.on('mouseover', function (d) {
if (d.type != 'sgv' && d.type != 'mbg') return;
if (d.type === 'sgv' || d.type === 'mbg') {
var bgType = (d.type === 'sgv' ? 'CGM' : (isDexcom(d.device) ? 'Calibration' : 'Meter'))
, rawbgValue = 0
, noiseLabel = '';
var bgType = (d.type == 'sgv' ? 'CGM' : (isDexcom(d.device) ? 'Calibration' : 'Meter'))
, rawbgValue = 0
, noiseLabel = '';
if (d.type == 'sgv') {
if (rawbg.showRawBGs(d.y, d.noise, cal, sbx)) {
rawbgValue = scaleBg(rawbg.calc(d, cal, sbx));
if (d.type === 'sgv') {
if (rawbg.showRawBGs(d.y, d.noise, cal, sbx)) {
rawbgValue = scaleBg(rawbg.calc(d, cal, sbx));
}
noiseLabel = rawbg.noiseCodeToDisplay(d.y, d.noise);
}
noiseLabel = rawbg.noiseCodeToDisplay(d.y, d.noise);
}
tooltip.transition().duration(TOOLTIP_TRANS_MS).style('opacity', .9);
tooltip.html('<strong>' + bgType + ' BG:</strong> ' + d.sgv +
(d.type == 'mbg' ? '<br/><strong>Device: </strong>' + d.device : '') +
(rawbgValue ? '<br/><strong>Raw BG:</strong> ' + rawbgValue : '') +
(noiseLabel ? '<br/><strong>Noise:</strong> ' + noiseLabel : '') +
'<br/><strong>Time:</strong> ' + formatTime(d.date))
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pageY + 15) + 'px');
tooltip.transition().duration(TOOLTIP_TRANS_MS).style('opacity', .9);
tooltip.html('<strong>' + bgType + ' BG:</strong> ' + d.sgv +
(d.type == 'mbg' ? '<br/><strong>Device: </strong>' + d.device : '') +
(rawbgValue ? '<br/><strong>Raw BG:</strong> ' + rawbgValue : '') +
(noiseLabel ? '<br/><strong>Noise:</strong> ' + noiseLabel : '') +
'<br/><strong>Time:</strong> ' + formatTime(d.date))
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pageY + 15) + 'px');
}
})
.on('mouseout', function (d) {
if (d.type != 'sgv' && d.type != 'mbg') return;
tooltip.transition()
.duration(TOOLTIP_TRANS_MS)
.style('opacity', 0);
if (d.type === 'sgv' || d.type === 'mbg') {
tooltip.transition()
.duration(TOOLTIP_TRANS_MS)
.style('opacity', 0);
}
});
focusCircles.exit()
@@ -963,9 +969,9 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
})
.attr('fill', function (d) { return d.color; })
.style('opacity', function (d) { return highlightBrushPoints(d) })
.attr('stroke-width', function (d) {if (d.type == 'mbg') return 2; else return 0; })
.attr('stroke', function (d) { return 'white'; })
.attr('r', function(d) { if (d.type == 'mbg') return 4; else return 2;});
.attr('stroke-width', function (d) { return d.type == 'mbg' ? 2 : 0; })
.attr('stroke', function ( ) { return 'white'; })
.attr('r', function (d) { return d.type == 'mbg' ? 4 : 2; });
if (badData.length > 0) {
console.warn("Bad Data: isNaN(sgv)", badData);
@@ -1138,10 +1144,10 @@ var app = {}, browserSettings = {}, browserStorage = $.localStorage;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function drawTreatment(treatment, scale, showValues) {
if (!treatment.carbs && !treatment.insulin) return;
if (!treatment.carbs && !treatment.insulin) { return; }
// don't render the treatment if it's not visible
if (Math.abs(xScale(treatment.created_at.getTime())) > window.innerWidth) return;
if (Math.abs(xScale(treatment.created_at.getTime())) > window.innerWidth) { return; }
var CR = treatment.CR || 20;
var carbs = treatment.carbs || CR;
+4 -4
View File
@@ -155,7 +155,7 @@ function closeDrawer(id, callback) {
$("html, body").animate({ scrollTop: 0 });
$(id).animate({right: '-300px'}, 300, function () {
$(id).css('display', 'none');
if (callback) callback();
if (callback) { callback(); }
});
}
@@ -173,7 +173,7 @@ function toggleDrawer(id, openCallback, closeCallback) {
closeOpenDraw(function () {
openDraw = id;
$(id).css('display', 'block').animate({right: '0'}, 300, function () {
if (callback) callback();
if (callback) { callback(); }
});
});
@@ -205,8 +205,8 @@ function currentTime() {
var hours = now.getHours();
var minutes = now.getMinutes();
if (hours<10) hours = '0' + hours;
if (minutes<10) minutes = '0' + minutes;
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
return ''+ hours + ':' + minutes;
}
+14 -14
View File
@@ -1,16 +1,16 @@
db.treatments.find().forEach(
function (elem) {
db.treatments.update(
{
_id: elem._id
},
{
$set: {
glucose: elem.glucoseValue,
insulin: elem.insulinGiven,
carbs: elem.carbsGiven
}
}
);
}
function (elem) {
db.treatments.update(
{
_id: elem._id
},
{
$set: {
glucose: elem.glucoseValue,
insulin: elem.insulinGiven,
carbs: elem.carbsGiven
}
}
);
}
);
+9 -9
View File
@@ -1,6 +1,6 @@
var fs = require('fs');
var data = ""
var data = ''
var END_TIME = Date.now();
var FIVE_MINS_IN_MS = 300000;
var TIME_PERIOD_HRS = 24;
@@ -10,17 +10,17 @@ var currentBG = START_BG;
var currentTime = END_TIME - (TIME_PERIOD_HRS * DATA_PER_HR * FIVE_MINS_IN_MS);
for(var i = 0; i < TIME_PERIOD_HRS * DATA_PER_HR; i++) {
currentBG += Math.ceil(Math.cos(i)*5+.2);
currentTime += FIVE_MINS_IN_MS;
data += "1," + currentBG + ",,,,,,,,," + new Date(currentTime).toString() + ",,,,\n";
currentBG += Math.ceil(Math.cos(i)*5+.2);
currentTime += FIVE_MINS_IN_MS;
data += '1,' + currentBG + ',,,,,,,,,' + new Date(currentTime).toString() + ',,,,\n';
}
fs.writeFile("../Dexcom.csv", data);
fs.writeFile('../Dexcom.csv', data);
function makedata() {
currentBG -= 1;
currentTime += FIVE_MINS_IN_MS;
data += "1," + currentBG + ",,,,,,,,," + new Date(currentTime).toString() + ",,,,\n";
fs.writeFile("../Dexcom.csv", data);
currentBG -= 1;
currentTime += FIVE_MINS_IN_MS;
data += '1,' + currentBG + ',,,,,,,,,' + new Date(currentTime).toString() + ',,,,\n';
fs.writeFile('../Dexcom.csv', data);
}
setInterval(makedata, 1000 * 10)
+17 -18
View File
@@ -1,7 +1,6 @@
'use strict';
var mongodb = require('mongodb');
var software = require('./../package.json');
var env = require('./../env')();
var util = require('./helpers/util');
@@ -9,26 +8,26 @@ var util = require('./helpers/util');
main();
function main() {
var MongoClient = mongodb.MongoClient;
MongoClient.connect(env.mongo, function connected(err, db) {
var MongoClient = mongodb.MongoClient;
MongoClient.connect(env.mongo, function connected(err, db) {
console.log("Connecting to mongo...");
if (err) {
console.log("Error occurred: ", err);
throw err;
}
populate_collection(db);
});
console.log('Connecting to mongo...');
if (err) {
console.log('Error occurred: ', err);
throw err;
}
populate_collection(db);
});
}
function populate_collection(db) {
var cgm_collection = db.collection(env.mongo_collection);
var new_cgm_record = util.get_cgm_record();
var cgm_collection = db.collection(env.mongo_collection);
var new_cgm_record = util.get_cgm_record();
cgm_collection.insert(new_cgm_record, function (err, created) {
if (err) {
throw err;
}
process.exit(0);
});
cgm_collection.insert(new_cgm_record, function (err) {
if (err) {
throw err;
}
process.exit(0);
});
}
+23 -24
View File
@@ -1,6 +1,5 @@
'use strict';
var software = require('./../package.json');
var env = require('./../env')();
var http = require('http');
var util = require('./util');
@@ -8,34 +7,34 @@ var util = require('./util');
main();
function main() {
send_entry_rest();
send_entry_rest();
}
function send_entry_rest() {
var new_cgm_record = util.get_cgm_record();
var new_cgm_record_string = JSON.stringify(new_cgm_record);
var new_cgm_record = util.get_cgm_record();
var new_cgm_record_string = JSON.stringify(new_cgm_record);
var options = {
host: 'localhost',
port: env.PORT,
path: '/api/v1/entries/',
method: 'POST',
headers: {
'api-secret' : env.api_secret,
'Content-Type': 'application/json',
'Content-Length': new_cgm_record_string.length
}
};
var options = {
host: 'localhost',
port: env.PORT,
path: '/api/v1/entries/',
method: 'POST',
headers: {
'api-secret' : env.api_secret,
'Content-Type': 'application/json',
'Content-Length': new_cgm_record_string.length
}
};
var req = http.request(options, function(res) {
console.log("Ok: ", res.statusCode);
});
var req = http.request(options, function(res) {
console.log("Ok: ", res.statusCode);
});
req.on('error', function(e) {
console.error('error');
console.error(e);
});
req.on('error', function(e) {
console.error('error');
console.error(e);
});
req.write(new_cgm_record_string);
req.end();
req.write(new_cgm_record_string);
req.end();
}
+54 -45
View File
@@ -1,63 +1,72 @@
'use strict';
exports.get_cgm_record = function() {
var dateobj = new Date();
var datemil = dateobj.getTime();
var datesec = datemil / 1000;
var datestr = getDateString(dateobj);
var dateobj = new Date();
var datemil = dateobj.getTime();
var datesec = datemil / 1000;
var datestr = getDateString(dateobj);
// We put the time in a range from -1 to +1 for every thiry minute period
var range = (datesec % 1800) / 900 - 1.0;
// We put the time in a range from -1 to +1 for every thiry minute period
var range = (datesec % 1800) / 900 - 1.0;
// The we push through a COS function and scale between 40 and 400 (so it is like a bg level)
var sgv = Math.floor(360 * (Math.cos(10.0 * range / 3.14) / 2 + 0.5)) + 40;
var dir = range > 0.0 ? "FortyFiveDown" : "FortyFiveUp";
// The we push through a COS function and scale between 40 and 400 (so it is like a bg level)
var sgv = Math.floor(360 * (Math.cos(10.0 * range / 3.14) / 2 + 0.5)) + 40;
var dir = range > 0.0 ? 'FortyFiveDown' : 'FortyFiveUp';
console.log('Writing Record: ');
console.log('sgv = ' + sgv);
console.log('date = ' + datemil);
console.log('dir = ' + dir);
console.log('str = ' + datestr);
console.log('Writing Record: ');
console.log('sgv = ' + sgv);
console.log('date = ' + datemil);
console.log('dir = ' + dir);
console.log('str = ' + datestr);
return {
'device': 'dexcom',
'date': datemil,
'sgv': sgv,
'direction': dir,
'dateString': datestr
};
}
return {
'device': 'dexcom',
'date': datemil,
'sgv': sgv,
'direction': dir,
'dateString': datestr
};
};
//TODO: use moment
function getDateString(d) {
// How I wish js had strftime. This would be one line of code!
// How I wish js had strftime. This would be one line of code!
var month = d.getMonth();
var day = d.getDay();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDay();
var year = d.getFullYear();
if (month < 10) month = '0' + month;
if (day < 10) day = '0' + day;
if (month < 10) { month = '0' + month; }
if (day < 10) { day = '0' + day; }
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var ampm = 'PM';
if (hour < 12) {
ampm = "AM";
}
var ampm = 'PM';
if (hour < 12) {
ampm = 'AM';
}
if (hour == 0) {
hour = 12;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour < 10) hour = '0' + hour;
if (min < 10) min = '0' + min;
if (sec < 10) sec = '0' + sec;
if (hour < 10) {
hour = '0' + hour;
}
return month + '/' + day + '/' + year + ' ' + hour + ':' + min + ':' + sec + ' ' + ampm;
if (min < 10) {
min = '0' + min;
}
if (sec < 10) {
sec = '0' + sec;
}
return month + '/' + day + '/' + year + ' ' + hour + ':' + min + ':' + sec + ' ' + ampm;
}
+3 -5
View File
@@ -1,6 +1,8 @@
'use strict';
var request = require('supertest');
var should = require('should');
var load = require('./fixtures/load');
require('should');
describe('Entries REST api', function ( ) {
var entries = require('../lib/api/entries/');
@@ -23,10 +25,6 @@ describe('Entries REST api', function ( ) {
this.archive( ).remove({ }, done);
});
it('should be a module', function ( ) {
entries.should.be.ok;
});
// keep this test pinned at or near the top in order to validate all
// entries successfully uploaded. if res.body.length is short of the
// expected value, it may indicate a regression in the create
+3 -2
View File
@@ -1,12 +1,13 @@
'use strict';
var request = require('supertest');
var should = require('should');
require('should');
describe('Status REST api', function ( ) {
var api = require('../lib/api/');
before(function (done) {
var env = require('../env')( );
env.enable = "careportal rawbg";
env.enable = 'careportal rawbg';
env.api_secret = 'this is my long pass phrase';
this.wares = require('../lib/middleware/')(env);
this.app = require('express')( );
+3 -1
View File
@@ -1,4 +1,6 @@
var should = require('should');
'use strict';
require('should');
describe('cage', function ( ) {
var cage = require('../lib/plugins/cannulaage')();
+17 -17
View File
@@ -1,6 +1,6 @@
'use strict';
var should = require('should');
require('should');
describe('COB', function ( ) {
var cob = require('../lib/plugins/cob')();
@@ -17,18 +17,18 @@ describe('COB', function ( ) {
var treatments = [
{
"carbs": "100",
"created_at": new Date("2015-05-29T02:03:48.827Z")
'carbs': '100',
'created_at': new Date('2015-05-29T02:03:48.827Z')
},
{
"carbs": "10",
"created_at": new Date("2015-05-29T03:45:10.670Z")
'carbs': '10',
'created_at': new Date('2015-05-29T03:45:10.670Z')
}
];
var after100 = cob.cobTotal(treatments, profile, new Date("2015-05-29T02:03:49.827Z"));
var before10 = cob.cobTotal(treatments, profile, new Date("2015-05-29T03:45:10.670Z"));
var after10 = cob.cobTotal(treatments, profile, new Date("2015-05-29T03:45:11.670Z"));
var after100 = cob.cobTotal(treatments, profile, new Date('2015-05-29T02:03:49.827Z'));
var before10 = cob.cobTotal(treatments, profile, new Date('2015-05-29T03:45:10.670Z'));
var after10 = cob.cobTotal(treatments, profile, new Date('2015-05-29T03:45:11.670Z'));
after100.cob.should.equal(100);
Math.round(before10.cob).should.equal(59);
@@ -39,16 +39,16 @@ describe('COB', function ( ) {
var treatments = [
{
"carbs": "8",
"created_at": new Date("2015-05-29T04:40:40.174Z")
'carbs': '8',
'created_at': new Date('2015-05-29T04:40:40.174Z')
}
];
var rightAfterCorrection = new Date("2015-05-29T04:41:40.174Z");
var later1 = new Date("2015-05-29T05:04:40.174Z");
var later2 = new Date("2015-05-29T05:20:00.174Z");
var later3 = new Date("2015-05-29T05:50:00.174Z");
var later4 = new Date("2015-05-29T06:50:00.174Z");
var rightAfterCorrection = new Date('2015-05-29T04:41:40.174Z');
var later1 = new Date('2015-05-29T05:04:40.174Z');
var later2 = new Date('2015-05-29T05:20:00.174Z');
var later3 = new Date('2015-05-29T05:50:00.174Z');
var later4 = new Date('2015-05-29T06:50:00.174Z');
var result1 = cob.cobTotal(treatments, profile, rightAfterCorrection);
var result2 = cob.cobTotal(treatments, profile, later1);
@@ -70,8 +70,8 @@ describe('COB', function ( ) {
var data = {
treatments: [{
carbs: "8"
, "created_at": Date.now() - 60000 //1m ago
carbs: '8'
, 'created_at': Date.now() - 60000 //1m ago
}]
, profile: profile
};
+4 -3
View File
@@ -1,11 +1,12 @@
var should = require('should');
'use strict';
require('should');
describe('Data', function ( ) {
var env = require('../env')();
var ctx = {};
data = require('../lib/data')(env, ctx);
// console.log(data);
var data = require('../lib/data')(env, ctx);
it('should return original data if there are no changes', function() {
data.sgvs = [{sgv: 100, x:100},{sgv: 100, x:99}];
+1 -1
View File
@@ -1,6 +1,6 @@
'use strict';
var should = require('should');
require('should');
describe('Delta', function ( ) {
var delta = require('../lib/plugins/delta')();
+6 -6
View File
@@ -1,6 +1,6 @@
var should = require('should');
'use strict';
var FIVE_MINS = 10 * 60 * 1000;
require('should');
describe('IOB', function ( ) {
var iob = require('../lib/plugins/iob')();
@@ -11,7 +11,7 @@ describe('IOB', function ( ) {
var time = new Date()
, treatments = [ {
created_at: time - 1,
insulin: "1.00"
insulin: '1.00'
}
];
@@ -41,7 +41,7 @@ describe('IOB', function ( ) {
var treatments = [{
created_at: (new Date()) - 1,
insulin: "1.00"
insulin: '1.00'
}];
var rightAfterBolus = iob.calcTotal(treatments);
@@ -56,7 +56,7 @@ describe('IOB', function ( ) {
var treatments = [{
created_at: time,
insulin: "5.00"
insulin: '5.00'
}];
var whenApproaching0 = iob.calcTotal(treatments, undefined, new Date(time + (3 * 60 * 60 * 1000) - (90 * 1000)));
@@ -71,7 +71,7 @@ describe('IOB', function ( ) {
var time = new Date()
, treatments = [ {
created_at: time - 1,
insulin: "1.00"
insulin: '1.00'
}
];
+5 -3
View File
@@ -1,4 +1,6 @@
var should = require('should');
'use strict';
require('should');
var FIVE_MINS = 5 * 60 * 1000;
@@ -12,8 +14,8 @@ describe('mqtt', function ( ) {
;
it('setup env correctly', function (done) {
process.env.MONGO="mongodb://localhost/test_db";
process.env.MONGO_COLLECTION="test_sgvs";
process.env.MONGO='mongodb://localhost/test_db';
process.env.MONGO_COLLECTION='test_sgvs';
process.env.MQTT_MONITOR = 'mqtt://user:password@m10.cloudmqtt.com:12345';
var env = require('../env')();
env.mqtt_client_id.should.equal('fSjoHx8buyCtAc474tg8Dt3');
+1 -1
View File
@@ -166,7 +166,7 @@ describe('Pebble Endpoint with Raw', function ( ) {
var pebbleRaw = require('../lib/pebble');
before(function (done) {
var envRaw = require('../env')( );
envRaw.enable = "rawbg";
envRaw.enable = 'rawbg';
this.appRaw = require('express')( );
this.appRaw.enable('api');
this.appRaw.use('/pebble', pebbleRaw(envRaw, ctx));
+48 -50
View File
@@ -2,8 +2,6 @@ var should = require('should');
describe('Profile', function ( ) {
var env = require('../env')();
var profile_empty = require('../lib/profilefunctions')();
it('should say it does not have data before it has data', function() {
@@ -17,8 +15,8 @@ describe('Profile', function ( ) {
});
var profileDataPartial = {
"dia": 3,
"carbs_hr": 30,
'dia': 3
, 'carbs_hr': 30
};
var profilePartial = require('../lib/profilefunctions')([profileDataPartial]);
@@ -29,12 +27,12 @@ describe('Profile', function ( ) {
});
var profileData = {
"dia": 3,
"carbs_hr": 30,
"carbratio": 7,
"sens": 35,
"target_low": 95,
"target_high": 120
'dia': 3
, 'carbs_hr': 30
, 'carbratio': 7
, 'sens': 35
, 'target_low': 95
, 'target_high': 120
};
var profile = require('../lib/profilefunctions')([profileData]);
@@ -80,12 +78,12 @@ describe('Profile', function ( ) {
it('should know how to reload data and still know what the low target is with old style profiles', function() {
var profileData2 = {
"dia": 3,
"carbs_hr": 30,
"carbratio": 7,
"sens": 35,
"target_low": 50,
"target_high": 120
'dia': 3,
'carbs_hr': 30,
'carbratio': 7,
'sens': 35,
'target_low': 50,
'target_high': 120
};
profile.loadData([profileData2]);
@@ -95,69 +93,69 @@ describe('Profile', function ( ) {
var complexProfileData =
{
"sens": [
'sens': [
{
"time": "00:00",
"value": 10
'time': '00:00',
'value': 10
},
{
"time": "02:00",
"value": 10
'time': '02:00',
'value': 10
},
{
"time": "07:00",
"value": 9
'time': '07:00',
'value': 9
}
],
"dia": 3,
"carbratio": [
'dia': 3,
'carbratio': [
{
"time": "00:00",
"value": 16
'time': '00:00',
'value': 16
},
{
"time": "06:00",
"value": 15
'time': '06:00',
'value': 15
},
{
"time": "14:00",
"value": 16
'time': '14:00',
'value': 16
}
],
"carbs_hr": 30,
"startDate": "2015-06-21",
"basal": [
'carbs_hr': 30,
'startDate': '2015-06-21',
'basal': [
{
"time": "00:00",
"value": 0.175
'time': '00:00',
'value': 0.175
},
{
"time": "02:30",
"value": 0.125
'time': '02:30',
'value': 0.125
},
{
"time": "05:00",
"value": 0.075
'time': '05:00',
'value': 0.075
},
{
"time": "08:00",
"value": 0.1
'time': '08:00',
'value': 0.1
},
{
"time": "14:00",
"value": 0.125
'time': '14:00',
'value': 0.125
},
{
"time": "20:00",
"value": 0.3
'time': '20:00',
'value': 0.3
},
{
"time": "22:00",
"value": 0.225
'time': '22:00',
'value': 0.225
}
],
"target_low": 4.5,
"target_high": 8
'target_low': 4.5,
'target_high': 8
};
var complexProfile = require('../lib/profilefunctions')([complexProfileData]);
+3 -1
View File
@@ -1,4 +1,6 @@
var should = require('should');
'use strict';
require('should');
describe('pushnotify', function ( ) {
+1 -1
View File
@@ -1,6 +1,6 @@
'use strict';
var should = require('should');
require('should');
describe('Raw BG', function ( ) {
var rawbg = require('../lib/plugins/rawbg')();
-1
View File
@@ -85,7 +85,6 @@ describe('API_SECRET', function ( ) {
});
it('should not work short', function ( ) {
var known = 'c1d117818a97e847bdf286aa02d9dc8e8f7148f5';
delete process.env.API_SECRET;
process.env.API_SECRET = 'tooshort';
var env;
+3 -1
View File
@@ -1,4 +1,6 @@
var should = require('should');
'use strict';
require('should');
describe('units', function ( ) {
var units = require('../lib/units')();
+1 -1
View File
@@ -1,6 +1,6 @@
'use strict';
var should = require('should');
require('should');
describe('Uploader Battery', function ( ) {
var data = {uploaderBattery: 20};
+3 -1
View File
@@ -1,4 +1,6 @@
var should = require('should');
'use strict';
require('should');
describe('utils', function ( ) {
var utils = require('../lib/utils')();