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