Skip to content

Commit

Permalink
Merge 1103078 into 11c4312
Browse files Browse the repository at this point in the history
  • Loading branch information
scottleibrand committed Oct 27, 2019
2 parents 11c4312 + 1103078 commit c04a00f
Show file tree
Hide file tree
Showing 6 changed files with 228 additions and 48 deletions.
207 changes: 207 additions & 0 deletions bin/oref0-get-ns-entries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
#!/usr/bin/env node

/*
oref0 Nightscout treatment fetch tool
Collects latest treatment data from Nightscout, with support for sending the
If-Modified-Since header and not outputting the report file on 304 Not Modified
response.
Released under MIT license. See the accompanying LICENSE.txt file for
full terms and conditions
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var crypto = require('crypto');
var request = require('request');
var _ = require('lodash');
var fs = require('fs');
var network = require('network');

if (!module.parent) {

var argv = require('yargs')
.usage("$0 ns-glucose.json NSURL API-SECRET <hours>")
.strict(true)
.help('help');

function usage() {
argv.showHelp();
}

var params = argv.argv;
var errors = [];
var warnings = [];

var glucose_input = params._.slice(0, 1).pop();

if ([null, '--help', '-h', 'help'].indexOf(glucose_input) > 0) {
usage();
process.exit(0);
}

var nsurl = params._.slice(1, 2).pop();
if (nsurl && nsurl.charAt(nsurl.length - 1) == "/") nsurl = nsurl.substr(0, nsurl.length - 1); // remove trailing slash if it exists

var apisecret = params._.slice(2, 3).pop();
var hours = Number(params._.slice(3, 4).pop());
var records = 1000;

if (hours > 0) {
records = 12 * hours;
}

if (!glucose_input || !nsurl || !apisecret) {
usage();
process.exit(1);
}

if (apisecret.length != 40) {
var shasum = crypto.createHash('sha1');
shasum.update(apisecret);
apisecret = shasum.digest('hex');
}

var lastDate = null;

var cwd = process.cwd();
var outputPath = cwd + '/' + glucose_input;

function loadFromxDrip(callback, ip) {
var headers = {
'api-secret': apisecret
};

var uri = 'http://' + ip + ':17580/sgv.json?count=' + records; // 192.168.43.1

var options = {
uri: uri
, json: true
, timeout: 10000
, headers: headers
};

console.error("Trying to load CGM data from local xDrip");

request(options, function(error, res, data) {
var failed = false;
if (res && res.statusCode == 403) {
console.error("Load from xDrip failed: API_SECRET didn't match");
failed = true;
}

if (error) {
if (error.code == 'ETIMEDOUT' || error.code == 'ESOCKETTIMEDOUT') {
console.error('Load from xDrip timed out');
} else {
console.error("Load from xDrip failed", error);
failed = true;
}

failed = true;
}

if (!failed && data) {
console.error("CGM results loaded from xDrip");
processAndOutput(data);
return true;
}

if (failed && callback) callback();
});

return false;
}

var nsCallback = function loadFromNightscout() {
// try Nightscout

var lastDate;
var glucosedata;

fs.readFile(outputPath, 'utf8', function(err, fileContent) {

if (err) {
console.error(err);
} else {
try {
glucosedata = JSON.parse(fileContent);

if (glucosedata.constructor == Array) { //{ throw "Glucose data file doesn't seem to be valid"; }
_.forEach(glucosedata, function findLatest(sgvrecord) {
var d = new Date(sgvrecord.dateString);
if (!lastDate || lastDate < d) {
lastDate = d;
}
});
} else {
glucosedata = null;
}
} catch (e) {
console.error(e);
}
}
loadFromNightscoutWithDate(lastDate, glucosedata);
});
}

function loadFromNightscoutWithDate(lastDate, glucosedata) {

var headers = {
'api-secret': apisecret
};

if (!_.isNil(lastDate)) {
headers["If-Modified-Since"] = lastDate.toISOString();
}

var uri = nsurl + '/api/v1/entries/sgv.json?count=' + records;
var options = {
uri: uri
, json: true
, headers: headers
};

request(options, function(error, res, data) {
if (res && (res.statusCode == 200 || res.statusCode == 304)) {

if (data) {
console.error("Got CGM results from Nightscout");
processAndOutput(data);
} else {
console.error("Got Not Changed response from Nightscout, assuming no new data is available");
// output old file
if (!_.isNil(glucosedata)) {
console.log(JSON.stringify(glucosedata));
}
}
} else {
console.error("Loading CGM data from Nightscout failed", error);
}
});

}

function processAndOutput(glucosedata) {

_.forEach(glucosedata, function findLatest(sgvrecord) {
sgvrecord.glucose = sgvrecord.sgv;
});

console.log(JSON.stringify(glucosedata));
}

network.get_gateway_ip(function(err, ip) {
console.error("My router IP is " + ip); // err may be 'No active network interface found.'
loadFromxDrip(nsCallback, ip);
});

}
10 changes: 7 additions & 3 deletions bin/oref0-ns-loop.sh
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,17 @@ function pushover_snooze {


function get_ns_bg {
#openaps get-ns-glucose > /dev/null
# update 24h glucose file if it's 55m old or too small to calculate COB
if ! file_is_recent cgm/ns-glucose-24h.json 54 \
|| ! grep -c glucose cgm/ns-glucose-24h.json | jq -e '. > 36' >/dev/null; then
nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -24hours > cgm/ns-glucose-24h.json
#nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -24hours > cgm/ns-glucose-24h.json
cp cgm/ns-glucose-24h.json cgm/ns-glucose-24h-temp.json
oref0-get-ns-entries cgm/ns-glucose-24h-temp.json $NIGHTSCOUT_HOST $API_SECRET 24 2>&1 >cgm/ns-glucose-24h.json
fi
nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -1hour > cgm/ns-glucose-1h.json
#nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -1hour > cgm/ns-glucose-1h.json
cp cgm/ns-glucose-1h.json cgm/ns-glucose-1h-temp.json
oref0-get-ns-entries cgm/ns-glucose-1h-temp.json $NIGHTSCOUT_HOST $API_SECRET 1 2>&1 >cgm/ns-glucose-1h.json

jq -s '.[0] + .[1]|unique|sort_by(.date)|reverse' cgm/ns-glucose-24h.json cgm/ns-glucose-1h.json > cgm/ns-glucose.json
glucose_fresh # update timestamp on cgm/ns-glucose.json
# if ns-glucose.json data is <10m old, no more than 5m in the future, and valid (>38),
Expand Down
13 changes: 0 additions & 13 deletions lib/oref0-setup/device.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,6 @@
"name": "cgm",
"extra": {}
},
{
"ns-glucose": {
"vendor": "openaps.vendors.process",
"extra": "ns-glucose.ini"
},
"type": "device",
"name": "ns-glucose",
"extra": {
"fields": "",
"cmd": "bash -c \"curl --compressed -m 30 -s $NIGHTSCOUT_HOST/api/v1/entries/sgv.json?count=1000 | json -e \\\"this.glucose = this.sgv\\\"\"",
"args": ""
}
},
{
"extra": {
"fields": "",
Expand Down
22 changes: 0 additions & 22 deletions lib/oref0-setup/report.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,6 @@
},
"name": "monitor/carbhistory.json"
},
{
"type": "report",
"name": "monitor/cgm-glucose.json",
"monitor/cgm-glucose.json": {
"hours": "25.0",
"device": "cgm",
"use": "iter_glucose_hours",
"reporter": "JSON"
}
},
{
"type": "report",
"name": "raw-cgm/raw-entries.json",
Expand All @@ -52,18 +42,6 @@
"glucose": ""
}
},
{
"cgm/ns-glucose.json": {
"oper": "oref0_glucose_since",
"use": "shell",
"reporter": "JSON",
"device": "ns",
"remainder": "-24hours",
"json_default": "True"
},
"type": "report",
"name": "cgm/ns-glucose.json"
},
{
"type": "report",
"monitor/mmtune.json": {
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"oref0-upload-entries": "./bin/oref0-upload-entries.sh",
"oref0-upload-profile": "./bin/oref0-upload-profile.js",
"oref0-version": "./bin/oref0-version.sh",
"oref0-get-ns-entries": "./bin/oref0-get-ns-entries.js",
"peb-urchin-status": "./bin/peb-urchin-status.sh",
"wifi": "./bin/oref0-tail-wifi.sh"
},
Expand All @@ -98,6 +99,7 @@
"lodash": "^4.17.15",
"moment": "^2.24.0",
"moment-timezone": "0.5.23",
"network": "^0.4.1",
"request": "^2.88.0",
"share2nightscout-bridge": "^0.2.1",
"yargs": "^13.2.2"
Expand Down
22 changes: 12 additions & 10 deletions www/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@

function loadBasalBolus(param) {
var i_bg = 0 ;
var bg = 0;
var bg = 100;
$.ajax({
url: "pumphistory",
async: false,
Expand Down Expand Up @@ -513,15 +513,17 @@
} else if ( data[i]._type == 'Bolus' ) {
if ( date1 >= param.minDate ) {
if (parseFloat(data[i].amount) > param.maxBolus) { param.maxBolus = parseFloat(data[i].amount);}
while (i_bg <= param.data.bg.length-1 && param.data.bg[i_bg].t > date1 ) {
i_bg++ ;
}
if ( i_bg == 0 ) {
bg = param.data.bg[i_bg].y;
} else if ( i_bg == param.data.bg.length) {
bg = param.data.bg[i_bg-1].y ;
} else {
bg = ( param.data.bg[i_bg].y + param.data.bg[i_bg-1].y ) / 2;
if (param.data.bg.length > 0) {
while (i_bg <= param.data.bg.length-1 && param.data.bg[i_bg].t > date1 ) {
i_bg++ ;
}
if ( i_bg == 0 ) {
bg = param.data.bg[i_bg].y;
} else if ( i_bg == param.data.bg.length) {
bg = param.data.bg[i_bg-1].y ;
} else {
bg = ( param.data.bg[i_bg].y + param.data.bg[i_bg-1].y ) / 2;
}
}
param.data.bolusBG[param.data.bolusBG.length] = {t:date1,y:bg,label:data[i].amount.toString().replace(/^0+/, '')};
var date3 = new Date(date1.getTime()-60000)
Expand Down

0 comments on commit c04a00f

Please sign in to comment.