├── .bowerrc ├── public └── assets │ ├── error.png │ ├── icon.png │ └── test-loader.js ├── resource ├── icon │ ├── dex.png │ └── icon.png ├── nightscout-owl.png └── chrome-promotional-small.png ├── tests ├── unit │ └── failing-test.js ├── helpers │ └── chrome.js ├── index.html └── test-loader.js ├── Brocfile.js ├── app ├── report │ ├── insights.js │ ├── insights.html │ ├── dailystats.html │ ├── hourlystats.html │ ├── success.html │ ├── percentile.html │ ├── glucosedistribution.html │ ├── glucosedistribution.js │ ├── percentile.js │ ├── hourlystats.js │ ├── stats_controls.js │ ├── dailystats.js │ └── success.js ├── background.js ├── bloodsugar.js ├── blinken_lights.js ├── receiver.html ├── waiting.js ├── datasource │ ├── remotecgm.js │ └── dexcom.js ├── store │ └── egv_records.js ├── config.js ├── flotcandle.js ├── console.js ├── help.html ├── feature │ ├── cgm_download.js │ ├── trending_alerts.js │ └── mongolab.js ├── receiver.js ├── options.js ├── app.js ├── options.html ├── time.js └── window.html ├── .gitignore ├── bower.json ├── deploy.sh ├── manifest.json ├── package.json ├── README.md ├── lib ├── builder.js └── bootstrap-confirmation.js └── LICENSE.md /.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "vendor" 3 | } 4 | -------------------------------------------------------------------------------- /public/assets/error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/public/assets/error.png -------------------------------------------------------------------------------- /public/assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/public/assets/icon.png -------------------------------------------------------------------------------- /resource/icon/dex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/resource/icon/dex.png -------------------------------------------------------------------------------- /resource/icon/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/resource/icon/icon.png -------------------------------------------------------------------------------- /tests/unit/failing-test.js: -------------------------------------------------------------------------------- 1 | QUnit.test('Failing test.', function(assert) { 2 | assert.ok(false); 3 | }); 4 | -------------------------------------------------------------------------------- /resource/nightscout-owl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/resource/nightscout-owl.png -------------------------------------------------------------------------------- /Brocfile.js: -------------------------------------------------------------------------------- 1 | var Builder = require('./lib/builder'); 2 | var builder = new Builder(); 3 | 4 | module.exports = builder.toTree(); 5 | -------------------------------------------------------------------------------- /resource/chrome-promotional-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nightscout/chrome-uploader/HEAD/resource/chrome-promotional-small.png -------------------------------------------------------------------------------- /app/report/insights.js: -------------------------------------------------------------------------------- 1 | Promise.all([ 2 | new Promise(function(ready) { 3 | chrome.storage.local.get("egvrecords", function(values) { 4 | ready(values.egvrecords); 5 | }); 6 | }) 7 | ]).then(function(o) { 8 | var data = o[0]; 9 | }); -------------------------------------------------------------------------------- /tests/helpers/chrome.js: -------------------------------------------------------------------------------- 1 | var chrome; 2 | 3 | chrome.app = { 4 | runtime: { 5 | onLaunched: { 6 | addListener: function(callback) { 7 | console.log('[mock]','chrome.app.runtime.onLaunched.addListener'); 8 | callback.apply(this); 9 | } 10 | } 11 | } 12 | }; 13 | 14 | export default chrome; 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | 7 | # dependencies 8 | /node_modules 9 | /vendor/* 10 | 11 | # misc 12 | /.sass-cache 13 | /connect.lock 14 | /coverage/* 15 | /libpeerconnection.log 16 | npm-debug.log 17 | testem.log 18 | mongoconfig.json 19 | diypsconfig.json -------------------------------------------------------------------------------- /app/background.js: -------------------------------------------------------------------------------- 1 | var app; 2 | var isOpen = false; 3 | 4 | chrome.app.runtime.onLaunched.addListener(function() { 5 | // UI Code here 6 | chrome.app.window.create('app/window.html', { 7 | id: "dexcomcharting", 8 | bounds: { 9 | width: 1000, 10 | height: 525 11 | } 12 | }, function(window) { 13 | isOpen = true; 14 | app = window; 15 | }); 16 | }); -------------------------------------------------------------------------------- /app/report/insights.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 |
12 | 13 | -------------------------------------------------------------------------------- /tests/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "NightScout.info CGM Utility", 3 | "dependencies": { 4 | "jquery": "^1.11.1", 5 | "qunit": "~1.12.0", 6 | "flot": "~0.8.3", 7 | "loader": "stefanpenner/loader.js#1.0.0", 8 | "qunit-phantom-runner": "jonkemp/qunit-phantomjs-runner#3575d9f9850f4c5f30f3595e66e0d59866d53fa5", 9 | "bootstrap": "~3.1.1", 10 | "bootstrap-confirmation": "*", 11 | "requirejs": "~2.1.14", 12 | "simple-statistics": "~0.8.1", 13 | "jquery-ui": "~1.11.2" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/test-loader.js: -------------------------------------------------------------------------------- 1 | /* globals requirejs, require */ 2 | 3 | QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); 4 | 5 | // TODO: load based on params 6 | for (var moduleName in requirejs.entries) { 7 | var shouldLoad; 8 | 9 | if (moduleName.match(/-test$/)) { shouldLoad = true; } 10 | if (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)) { shouldLoad = true; } 11 | 12 | if (shouldLoad) { require(moduleName); } 13 | }; 14 | 15 | if (QUnit.notifications) { 16 | QUnit.notifications({ 17 | icons: { 18 | passed: '/assets/passed.png', 19 | failed: '/assets/failed.png' 20 | } 21 | }); 22 | } 23 | -------------------------------------------------------------------------------- /public/assets/test-loader.js: -------------------------------------------------------------------------------- 1 | /* globals requirejs, require */ 2 | 3 | QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); 4 | 5 | // TODO: load based on params 6 | for (var moduleName in requirejs.entries) { 7 | var shouldLoad; 8 | 9 | if (moduleName.match(/-test$/)) { shouldLoad = true; } 10 | if (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)) { shouldLoad = true; } 11 | 12 | if (shouldLoad) { require(moduleName); } 13 | }; 14 | 15 | if (QUnit.notifications) { 16 | QUnit.notifications({ 17 | icons: { 18 | passed: '/assets/passed.png', 19 | failed: '/assets/failed.png' 20 | } 21 | }); 22 | } 23 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rm -rf node_modules 3 | rm -rf .git 4 | rm npm-debug.log 5 | rm -rf tests 6 | rm resource/chrome-promotional-small.png 7 | rm vendor/jquery/dist/jquery.js 8 | rm vendor/jquery/dist/jquery.min.map 9 | rm -rf vendor/jquery/src 10 | rm vendor/jquery-ui/jquery-ui.js 11 | rm -rf vendor/jquery-ui/ui 12 | mv vendor/jquery-ui/themes/smoothness/ .smoothness 13 | rm -rf vendor/jquery-ui/themes/* 14 | mv .smoothness vendor/jquery-ui/themes/smoothness 15 | rm vendor/jquery-ui/themes/smoothness/jquery-ui.css 16 | rm -rf vendor/qunit 17 | rm -rf vendor/qunit-phantom-runner 18 | rm -rf vendor/bootstrap/test-infra 19 | rm Brocfile.js 20 | rm bower.json 21 | rm .bowerrc 22 | rm package.json 23 | rm deploy.sh -------------------------------------------------------------------------------- /app/bloodsugar.js: -------------------------------------------------------------------------------- 1 | define(["/app/config.js!"], function(config) { 2 | var convertBg; 3 | function makeItMgDl() { 4 | convertBg = function displayAsMgDl(bg) { 5 | return Math.floor(bg); 6 | }; 7 | } 8 | 9 | function makeItMmol() { 10 | convertBg = function displayAsMmol(bg) { 11 | // http://twitter.com/david_jansson/status/517430131846291456 12 | return (Math.round((bg / 18) * 10) / 10).toFixed(1); 13 | }; 14 | } 15 | var changeUnit = function(unit) { 16 | if (unit == "mmol") { 17 | makeItMmol(); 18 | } else { 19 | makeItMgDl(); 20 | } 21 | }; 22 | 23 | config.on("unit", changeUnit); 24 | changeUnit(config.unit); 25 | 26 | return function(mgdl) { 27 | return convertBg(mgdl); 28 | }; 29 | }) -------------------------------------------------------------------------------- /app/blinken_lights.js: -------------------------------------------------------------------------------- 1 | var log = console.log, debug = console.debug, info = console.info; 2 | 3 | define(function() { 4 | var listeners = {}; 5 | var out = {}; 6 | out.on = function(event, cb) { 7 | if (!(event in listeners)) { 8 | listeners[event] = []; 9 | } 10 | listeners[event].push(cb); 11 | } 12 | out.fire = function(event, details) { 13 | (listeners[event] || []).forEach(function(cb) { 14 | cb.call({}, details); 15 | }) 16 | } 17 | console.log = function() { 18 | out.fire("output", arguments); 19 | log.apply(console, arguments); 20 | } 21 | 22 | console.debug = function() { 23 | out.fire("output", arguments); 24 | debug.apply(console, arguments); 25 | } 26 | 27 | console.info = function() { 28 | out.fire("input", arguments); 29 | info.apply(console, arguments); 30 | } 31 | 32 | return out; 33 | }); -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | 4 | "name": "NightScout.info CGM Utility", 5 | "description": "Report #cgmnow, run reports, and upload data to NightScout.", 6 | "version": "0.1.6.2", 7 | "app": { 8 | "background": { 9 | "scripts": ["app/background.js"] 10 | } 11 | }, 12 | "permissions": [ 13 | "serial", 14 | "storage", 15 | "unlimitedStorage", 16 | "", 17 | "notifications", 18 | { 19 | "fileSystem": [ 20 | "write" 21 | ] 22 | }, 23 | "usb", 24 | "webview", 25 | { 26 | "usbDevices": [ 27 | { 28 | "vendorId": 8867, 29 | "productId": 71 30 | } 31 | ] 32 | } 33 | ], 34 | "icons": { 35 | "16": "public/assets/icon.png", 36 | "128": "public/assets/icon.png" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /app/report/dailystats.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 25 | Daily Stats report 26 | 27 | 28 |

Daily Stats for last 7 Days

29 | 30 |
31 |
32 | 33 | -------------------------------------------------------------------------------- /app/receiver.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | 10 |
11 | 12 | Timeframe 13 | 14 | 15 | 25 |
26 |
27 |
-------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "NightScoutCGM", 3 | "version": "0.0.0", 4 | "main": "index.js", 5 | "description": "Download Dexcom data on almost any platform Chrome runs on.", 6 | "private": true, 7 | "scripts": { 8 | "postinstall": "bower install", 9 | "build": "if [ -d \"./dist\" ]; then rm -rf ./dist; fi; broccoli build ./dist", 10 | "test": "broccoli serve", 11 | "start": "broccoli serve" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/nightscout/chrome-uploader.git" 16 | }, 17 | "engines": { 18 | "node": ">= 0.10.0" 19 | }, 20 | "author": "Brian Bosh ", 21 | "license": "Unknown", 22 | "bugs": { 23 | "url": "https://github.com/nightscout/chrome-uploader/issues" 24 | }, 25 | "dependencies": { 26 | "broccoli": "0.12.1", 27 | "broccoli-es6-concatenator": "~0.1.6", 28 | "broccoli-file-mover": "~0.3.5", 29 | "broccoli-merge-trees": "0.1.3", 30 | "broccoli-static-compiler": "0.1.4" 31 | }, 32 | "devDependencies": {} 33 | } 34 | -------------------------------------------------------------------------------- /app/report/hourlystats.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Hourly Stats report 14 | 15 | 16 | 31 |

Hourly Stat Report

32 |
33 |
34 |
35 |
36 |
37 | 38 | -------------------------------------------------------------------------------- /app/report/success.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Success report 12 | 13 | 14 | 48 |

Weekly Success

49 | 50 |
51 |
52 | 53 | -------------------------------------------------------------------------------- /app/report/percentile.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Glucose Percentile report 14 | 29 | 30 | 31 |

Percentile Chart ( 32 | 33 | ):

34 |
35 |
36 |
37 |
38 |
39 | 40 | 41 | -------------------------------------------------------------------------------- /app/waiting.js: -------------------------------------------------------------------------------- 1 | var myApp; 2 | var makeAWindow = function(title) { 3 | return $([ 4 | '' 21 | ].join("")); 22 | }; 23 | 24 | var pleaseWaitDiv = makeAWindow("Communicating"); 25 | 26 | define("waiting", { 27 | show: function(title) { 28 | var me = this; 29 | if (title) { 30 | pleaseWaitDiv = makeAWindow(title); 31 | } 32 | pleaseWaitDiv.modal(); 33 | return function() { 34 | me.hide(); 35 | }; 36 | }, 37 | hide: function () { 38 | pleaseWaitDiv.modal('hide'); 39 | }, 40 | setProgress: function(progress) { 41 | pleaseWaitDiv.find(".bar").width(progress + "%") 42 | } 43 | }); 44 | -------------------------------------------------------------------------------- /app/report/glucosedistribution.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 28 | Glucose Distribution report 29 | 30 | 31 |

Glucose distribution ( 32 | 33 | ):

34 |
35 |
36 |
37 |
38 |
39 | 40 |
41 |
42 | * This is only a rough estimation that can be very inaccurate and does not replace actual blood testing. The formula used is taken from: Nathan, David M., et al. "Translating the A1C assay into estimated average glucose values." Diabetes care 31.8 (2008): 1473-1478. 43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /app/datasource/remotecgm.js: -------------------------------------------------------------------------------- 1 | define(["/app/config.js!", "../feature/mongolab"], function(config, mongolab) { 2 | var ml; 3 | var mongolabUrl = "https://api.mongolab.com/api/1/databases/"; 4 | return { 5 | connect: function() { 6 | return new Promise(function(good, bad) { 7 | ml = config.mongolab; 8 | var doit = function() { 9 | if (config.mongolab.apikey && config.mongolab.database && config.mongolab.collection) // don't attempt to test without a config 10 | mongolab.testConnection(config.mongolab.apikey, config.mongolab.database, config.mongolab.collection).then(good, bad); 11 | }; 12 | if ("mongolab" in config) doit(); 13 | else config.on("mongolab", doit); 14 | }); 15 | }, 16 | // connect: function() { 17 | // return new Promise(function(good, bad) { 18 | // var ml = config.mongolab; 19 | // if (ml.apikey && ml.database && ml.collection) // don't attempt to test without a config 20 | // mongolab.testConnection(ml.apikey, ml.database, ml.collection).then(good, bad); 21 | // }); 22 | // }, 23 | disconnect: function() { 24 | // no op 25 | }, 26 | readFromReceiver: function(pageoffset) { 27 | return new Promise(function(good, bad) { 28 | $.getJSON( 29 | mongolabUrl + ml.database + "/collections/" + ml.collection + "?apiKey=" + ml.apikey + "&l=300&sk=" + (300 * (pageoffset - 1)) + "&s={\"date\":-1}" 30 | ).then(function(docs) { 31 | good(docs.filter(function(record) { 32 | if (Object.keys(record).indexOf("type") > -1) { 33 | return record.type == "sgv"; 34 | } else { 35 | return true; 36 | } 37 | })); 38 | }, bad) 39 | }); 40 | }, 41 | 42 | getAllRecords: function() { 43 | return new Promise(function(done) { 44 | done([]); 45 | }); 46 | } 47 | } 48 | }); -------------------------------------------------------------------------------- /app/store/egv_records.js: -------------------------------------------------------------------------------- 1 | define(function() { 2 | var table = []; // representation of chrome.storage.local.get("egvrecords") 3 | var listeners = []; 4 | var readyToWrite = false; 5 | var loaded = false; 6 | var loadPromise = new Promise(function(done) { 7 | loaded = done; 8 | }); 9 | 10 | var callback = function(newRecords) { 11 | listeners.forEach(function(fn) { 12 | try { 13 | fn(newRecords, table); 14 | } catch (e) { 15 | console.log(e); 16 | } 17 | }); 18 | }; 19 | 20 | var write = function(new_r, all) { 21 | if (!readyToWrite) return; 22 | 23 | chrome.storage.local.set({ 24 | egvrecords: table.slice() 25 | }, function(local) { 26 | console.debug("[egv_records.js write] Wrote %i new records to local storage.", new_r.length) 27 | }) 28 | }; 29 | 30 | chrome.storage.local.get("egvrecords", function(local) { 31 | // replace table with egvrecords from localstorage without loosing methods that've been tacked on here 32 | var localRecords = [(local.egvrecords || []).slice()]; 33 | while (localRecords[0].length > 0xfff0) { 34 | localRecords.push(localRecords[0].splice(0, 0xfff0)) 35 | } 36 | 37 | localRecords.forEach(function(page) { 38 | Array.prototype.splice.apply(table, [table.length, 0].concat(page)); 39 | }); 40 | 41 | table.sort(function(a,b) { 42 | return a.displayTime - b.displayTime; 43 | }); 44 | 45 | callback([]); // run callback with no new records 46 | readyToWrite = true; 47 | loaded(); 48 | }); 49 | 50 | table.add = function(record) { 51 | table.push(record); 52 | callback([record]); 53 | }; 54 | 55 | table.addAll = function(records) { 56 | var localRecords = [records.slice()]; 57 | while (localRecords[0].length > 0xfff0) { 58 | localRecords.push(localRecords[0].splice(0, 0xfff0)) 59 | } 60 | 61 | localRecords.forEach(function(page) { 62 | Array.prototype.splice.apply(table, [table.length, 0].concat(page)); 63 | }) 64 | table.sort(function(a,b) { 65 | return a.displayTime - b.displayTime; 66 | }); 67 | records.sort(function(a,b) { 68 | return a.displayTime - b.displayTime; 69 | }); 70 | callback(records); 71 | }; 72 | 73 | table.removeAll = function() { 74 | table.splice(0, table.length); 75 | callback([]); 76 | }; 77 | 78 | table.onChange = function(callback) { 79 | listeners.push(callback); 80 | }; 81 | 82 | table.onChange(write); // every time it changes re-save 83 | table.onLoad = loadPromise; 84 | 85 | return table; 86 | }); -------------------------------------------------------------------------------- /app/config.js: -------------------------------------------------------------------------------- 1 | define(function() { 2 | var issaving = false; 3 | var listeners = {}; 4 | var fire = function(key, old) { 5 | if (key in listeners) 6 | listeners[key].forEach(function(fn) { 7 | fn(config[key], old); 8 | }); 9 | }; 10 | 11 | var isWindows = !!~window.navigator.appVersion.indexOf("Win"); 12 | 13 | var config = { 14 | unit: "mgdl", 15 | targetrange: { 16 | low: 70, 17 | high: 180 18 | }, 19 | notifications: "important", 20 | trenddisplaytime: 12 21 | }; 22 | 23 | chrome.storage.onChanged.addListener(function(changes, namespace) { 24 | if (issaving) return; 25 | 26 | if ("config" in changes) { 27 | for (var property in changes[config].newValue) { 28 | config.set(property, changes[config].newValue); 29 | } 30 | } 31 | }); 32 | 33 | return { 34 | defined: function() { 35 | }, 36 | load: function(name, require, loaded) { 37 | chrome.storage.local.get("config", function(local) { 38 | for (var prop in (local.config || {})) { 39 | if (prop == "on" || prop == "set") { 40 | // special case 41 | } else { 42 | config[prop] = local.config[prop]; 43 | } 44 | } 45 | config.on = function(key, fn) { 46 | if (key == "loaded" && config.loaded) { 47 | fn(true,true); 48 | } else { 49 | listeners[key] = listeners[key] || []; 50 | listeners[key].push(fn); 51 | } 52 | }; 53 | config.set = function(key, val) { 54 | var working = config; 55 | var old; 56 | while (key.indexOf(".") > -1) { 57 | working = working[key.substr(0, key.indexOf("."))]; 58 | key = key.substr(key.indexOf(".") + 1); 59 | } 60 | var old = working[key]; 61 | if (val != old) { 62 | working[key] = val; 63 | fire(key, old); 64 | issaving = true; 65 | chrome.storage.local.set({ 66 | config: (function(state) { 67 | // rip "set" and "on" out of config object before saving it 68 | var out = {}; 69 | for (var key in state) { 70 | if (["baseUrl", "bundles", "config", "on", "paths", "pkgs", "set", "shim", "waitSeconds"].indexOf(key) == -1) { 71 | out[key] = state[key]; 72 | } 73 | } 74 | return out; 75 | })(config) 76 | }, function(local) { 77 | console.log("[config.js set] saved config"); 78 | setTimeout(function() { 79 | issaving = false; 80 | }, 100); 81 | }) 82 | } 83 | }; 84 | 85 | loaded(config); 86 | }); 87 | } 88 | }; 89 | }); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ##NightScout.info CGM Utility 2 | Download Dexcom data on almost any platform Chrome runs on. 3 | 4 | * OSX 10.7+. 5 | * Ubuntu 12.04+ 6 | * Windows 7-8.1 if [Dexcom Studio](http://dexcom.com/dexcom-studio) is installed. 7 | * Windows 10 out of the box. 8 | 9 | There's a nodejs branch. It's only been tested on nodejs 0.10 on OSX Yosemite. 10 | 11 | Has not been tested on Windows XP. 12 | ##Don't use this for treatment. Don't. Seriously, don't. This is reverse engineered. Dexcom Studio can be aware of lots of gotchas that this simply isn't. Data might stop updating. Data can be entirely wrong. I've seen it make 300 point swings out of the blue, not because BG changed but simply because of how this thing works. 13 | 14 | BE AWARE. If something seems strange double check. Tripple check. And then check again. 15 | 16 | Just like how a CGM is just an alert to check your sugar, this is just an alert to check your Dexcom. 17 | 18 | ###Install 19 | 1. Get code in folder 20 | 2. Open a terminal and CD to that folder 21 | 3. Install dependencies (npm install) 22 | 4. You're done with your terminal. Give yourself a pat on the back. 23 | 5. Go to chrome://extensions 24 | 6. Check developer mode 25 | 7. Load unpacked extension 26 | 8. Pick your folder 27 | 28 | ###Use 29 | 1. Plug in your Dexcom 30 | 2. open chrome://extensions 31 | 3. Click **NightScout.info CGM Utility** icon to launch 32 | 33 | Lots of steps and right now. Some times you get no data back, usually preceded by completely inaccurate graphs- if that happens, press the Reset button. This'll wipe out all the data it's accumulated. Doesn't seem like you really need to unplug/replug anymore. 34 | 35 | 36 | ###Linux 37 | On linux systems the programme doesn't have permission to access the dexcom device. In order to grant this permission, a udev rule has to be supplied. 38 | 39 | 1. Create a file like /etc/udev/rules.d/99-dexcom.rules with admin rights. 40 | 2. Add the following text to this file. Replace YOURGROUP with either a group you are member of or just your username. 41 | SUBSYSTEM=="usb",ATTR{idVendor}=="22a3",ATTR{idProduct}=="0047",MODE="0660",GROUP="YOURGROUP" 42 | 3. trigger udev to load the new rules or simply restart. 43 | 44 | How to to this on Ubuntu (tested on 12.4): 45 | 1. open a terminal 46 | 2. run the following command, replacing YOURUSERNAME with your username: 47 | echo "SUBSYSTEM==\"usb\",ATTR{idVendor}==\"22a3\",ATTR{idProduct}==\"0047\",MODE=\"0660\",GROUP=\"YOURUSERNAME\"" | sudo tee /etc/udev/rules.d/99-dexcom.rules 48 | 3. restart 49 | 50 | -------------------------------------------------------------------------------- /lib/builder.js: -------------------------------------------------------------------------------- 1 | var pickFiles = require('broccoli-static-compiler'); 2 | var mergeTrees = require('broccoli-merge-trees'); 3 | var moveFile = require('broccoli-file-mover'); 4 | var compileES6 = require('broccoli-es6-concatenator'); 5 | 6 | module.exports = Builder; 7 | 8 | function Builder() { 9 | this.name = 'chromadex'; 10 | 11 | this.trees = { 12 | app: 'app', 13 | lib: 'lib', 14 | tests: 'tests', 15 | vendor: 'vendor' 16 | }; 17 | } 18 | 19 | Builder.prototype.publicFolder = function() { 20 | return 'public'; 21 | } 22 | 23 | Builder.prototype.testIndex = function() { 24 | return pickFiles(this.trees.tests, { 25 | files: ['index.html'], 26 | srcDir: '/', 27 | destDir: '/tests' 28 | }); 29 | } 30 | 31 | Builder.prototype._processedAppTree = function() { 32 | return pickFiles(this.trees.app, { 33 | srcDir: '/', 34 | destDir: this.name 35 | }); 36 | } 37 | 38 | Builder.prototype._processedTestsTree = function() { 39 | return pickFiles(this.trees.tests, { 40 | srcDir: '/', 41 | destDir: this.name 42 | }); 43 | } 44 | 45 | Builder.prototype._processedVendorTree = function() { 46 | return pickFiles(this.trees.vendor, { 47 | files: ['**/*.js'], 48 | srcDir: '/', 49 | destDir: 'vendor/' 50 | }); 51 | } 52 | 53 | Builder.prototype.appAndDependencies = function() { 54 | var app = this._processedAppTree(); 55 | var tests = this._processedTestsTree(); 56 | var vendor = this._processedVendorTree(); 57 | 58 | var sourceTrees = [app, vendor, tests] 59 | 60 | return mergeTrees(sourceTrees, { 61 | overwrite: true, 62 | description: 'TreeMerger (appAndDependencies)' 63 | }); 64 | } 65 | 66 | Builder.prototype.testDependencies = function() { 67 | return pickFiles(this.trees.vendor, { 68 | srcDir: '/qunit/qunit', 69 | files: [ 70 | 'qunit.css', 'qunit.js' 71 | ], 72 | destDir: '/assets/' 73 | }); 74 | } 75 | 76 | Builder.prototype.javascript = function() { 77 | var appAndDependencies = this.appAndDependencies(); 78 | 79 | return compileES6(appAndDependencies, { 80 | loaderFile: 'vendor/loader/loader.js', 81 | ignoredModules: [], 82 | legacyFilesToAppend: [ 83 | 'vendor/jquery/dist/jquery.min.js', 84 | 'vendor/flot/jquery.flot.js' 85 | ], 86 | inputFiles: [ 87 | this.name + '/**/*.js' 88 | ], 89 | wrapInEval: false, 90 | outputFile: '/' + this.name + '.js' 91 | }); 92 | } 93 | 94 | Builder.prototype.toArray = function() { 95 | var sourceTrees = [ 96 | this.javascript(), 97 | this.publicFolder(), 98 | this.testIndex(), 99 | this.testDependencies() 100 | ]; 101 | 102 | return sourceTrees; 103 | } 104 | 105 | Builder.prototype.toTree = function() { 106 | return mergeTrees(this.toArray(), { 107 | overwrite: true, 108 | description: 'TreeMerger (allTrees)' 109 | }); 110 | } 111 | -------------------------------------------------------------------------------- /app/flotcandle.js: -------------------------------------------------------------------------------- 1 | (function ($) { 2 | var options = { 3 | series: { candle: null } // or number/string 4 | }; 5 | var offset, x, y; 6 | 7 | function init(plot) { 8 | plot.hooks.processOptions.push(processOptions); 9 | function processOptions(plot,options){ 10 | if(options.series.candle){ 11 | //plot.hooks.processRawData.push(processRawData); 12 | plot.hooks.drawSeries.push(drawSeries); 13 | } 14 | } 15 | /*function processRawData(plot,s,data,datapoints){ 16 | if(s.candle){ 17 | } 18 | }*/ 19 | function drawSeries(plot, ctx, serie){ 20 | if (serie.candle) { 21 | offset = plot.getPlotOffset(); 22 | offset.left = offset.left; 23 | var x1 = serie.xaxis.p2c(serie.data[0][0]); 24 | var x2 = serie.xaxis.p2c(serie.data[1][0]); 25 | var width = (x2 - x1) * 4 / 5; 26 | for (var j = 0; j < serie.data.length; j++) { getAndDrawCandle(ctx, serie, width, serie.data[j]);} 27 | } 28 | } 29 | function getAndDrawCandle(ctx, serie, width, data){ 30 | var dt = data[0]; 31 | var open = data[1]; 32 | var close = data[2]; 33 | var low = data[3]; 34 | var high = data[4]; 35 | drawCandle(ctx, serie, width, dt, open, low, close, high); 36 | } 37 | function drawCandle(ctx, serie, width, dt, open, low, close, high){ 38 | if (open < close){ //Rising 39 | y = offset.top + serie.yaxis.p2c(open) 40 | height = serie.yaxis.p2c(close) - serie.yaxis.p2c(open); 41 | ctx.fillStyle = "#51FF21"; 42 | } else { //Decending 43 | y = offset.top + serie.yaxis.p2c(close) 44 | height = serie.yaxis.p2c(open) - serie.yaxis.p2c(close); 45 | ctx.fillStyle = "#FF0000"; 46 | } 47 | ctx.strokeStyle = "#000000"; 48 | ctx.lineWidth = 0; 49 | x = offset.left + serie.xaxis.p2c(dt); 50 | 51 | //body 52 | ctx.fillRect (x, y, width, height); 53 | ctx.strokeRect(x, y, width, height); 54 | 55 | var highY = serie.yaxis.p2c(high); 56 | var lowY = serie.yaxis.p2c(low); 57 | 58 | //top 59 | if (highY < y + height){ 60 | ctx.beginPath(); 61 | var lineX = x + (width /2); 62 | ctx.moveTo(lineX,y + height); 63 | ctx.lineTo(lineX,highY); 64 | ctx.closePath(); 65 | ctx.stroke(); 66 | } 67 | 68 | //bottom 69 | if (lowY > y){ 70 | ctx.beginPath(); 71 | ctx.moveTo(lineX,y); 72 | ctx.lineTo(lineX,lowY); 73 | ctx.closePath(); 74 | ctx.stroke(); 75 | } 76 | } 77 | } 78 | 79 | $.plot.plugins.push({ 80 | init: init, 81 | options: options, 82 | name: 'candle', 83 | version: '1.0' 84 | }); 85 | })(jQuery); -------------------------------------------------------------------------------- /app/console.js: -------------------------------------------------------------------------------- 1 | define([], function() { 2 | var myLog = [], consoleFunctions = {}; 3 | var flattenSimple = function(d) { 4 | var recursions = 0; 5 | var pad = function(times) { 6 | var s = ""; 7 | for (var i = times; i > 0; i--) { 8 | s += " "; 9 | } 10 | return s; 11 | } 12 | var toString = function(val) { 13 | var out = ""; 14 | if (++recursions > 5) return "/* MAX DESCENTS REACHED */"; 15 | 16 | if (typeof val == "string") { // string 17 | out = val; 18 | } else if (typeof val == "number") { // number 19 | out = val.toString(); 20 | } else if (typeof val == "object" && val.length) { // array 21 | out = "[\n" + Array.prototype.map.call(val, toString).join(",\n") + "\n]\n"; 22 | } else if (typeof val == "object") { // object 23 | if (val.toString == Object.toString) // JS Object 24 | out = val.toString(); 25 | else // Native Object 26 | out = "{\n" + Object.keys(val).filter(function(k) { 27 | return k != "apikey" && (typeof val[k] != "function"); 28 | }).map(function(k) { 29 | return pad(recursions) + k + ": " + toString(val[k]); 30 | }).join(",\n") + "\n" + pad(recursions - 1) + "}"; 31 | } else if (typeof val == "boolean") { // boolean 32 | out = val.toString(); 33 | } else { // null or undefined 34 | out = ""; 35 | } 36 | --recursions; 37 | return pad(recursions) + out; 38 | } 39 | var result = d.map(toString); 40 | if (typeof d[0] == "string") { 41 | var template = result.shift(); 42 | template = template.replace(/%\w/g, function(match) { 43 | return result.shift(); 44 | }); 45 | return template + " " + result.join(" "); 46 | } else { 47 | return result.join(" "); 48 | } 49 | }; 50 | var console = "console" in window? window.console: {}; 51 | ["log", "warn", "info", "error", "debug"].forEach(function(fn) { consoleFunctions[fn] = console[fn] || function() { }; }); 52 | ["log", "warn", "info", "error", "debug"].forEach(function(fn) { 53 | console[fn] = function() { 54 | var stack = {}; 55 | try { 56 | throw new Error(); 57 | } catch (e) { 58 | stack = e.stack; 59 | } 60 | try { 61 | stack = stack 62 | .split("\n") // big string 63 | .slice(2) // throw away intro and this fn's invocation 64 | .filter(function(line) { 65 | return line.indexOf("blinken_lights.js") == -1; 66 | }) 67 | .map(function(line) { 68 | return line.trim(); 69 | }) 70 | .filter(function(line) { 71 | return line.indexOf("jquery") == -1 && line.indexOf("(native)") == -1; 72 | }).map(function(line) { 73 | var parts = line.split(":"); 74 | return { 75 | file: parts[1] 76 | .split("/") 77 | .slice(3) // throw away chrome-extension part 78 | .join("/"), 79 | line: parseInt(parts[2],10) 80 | }; 81 | }); 82 | var args = Array.prototype.slice.call(arguments); 83 | myLog.push(fn.toUpperCase() + ": " + stack[0].file + ":" + stack[0].line + ": " + flattenSimple(args)); 84 | consoleFunctions[fn].apply(console, arguments); 85 | } 86 | catch (e) { 87 | myLog.push("Error occured during console operation. " + JSON.stringify(e)); 88 | } 89 | } 90 | }); 91 | 92 | console.info = function(info) { 93 | var args = Array.prototype.slice.call(arguments); 94 | myLog.push("INFO: REDACTED"); 95 | consoleFunctions["info"].apply(console, arguments); 96 | }; 97 | console.fixMyStuff = function() { 98 | return myLog.join("\n"); 99 | }; 100 | return console; 101 | }); -------------------------------------------------------------------------------- /app/report/glucosedistribution.js: -------------------------------------------------------------------------------- 1 | function generate_report(data, high, low) { 2 | require(["../bloodsugar"], function(convertBg) { 3 | var Statician = ss; 4 | var days = 3 * 30; // months 5 | var config = { low: convertBg(low), high: convertBg(high) }; 6 | var report = $("#report"); 7 | report.empty(); 8 | var minForDay, maxForDay; 9 | var stats = []; 10 | var table = $(""); 11 | var thead = $(""); 12 | $("").appendTo(thead); 13 | $("").appendTo(thead); 14 | $("").appendTo(thead); 15 | $("").appendTo(thead); 16 | $("").appendTo(thead); 17 | $("").appendTo(thead); 18 | $("").appendTo(thead); 19 | thead.appendTo(table); 20 | 21 | ["Low", "Normal", "High"].forEach(function(range) { 22 | var tr = $(""); 23 | var rangeRecords = data.filter(function(record) { 24 | return "bgValue" in record && /\d+/.test(record.bgValue.toString()); 25 | }).filter(function(r) { 26 | r.localBg = parseFloat(r.localBg); 27 | if (range == "Low") { 28 | return r.localBg > 0 && r.localBg < config.low; 29 | } else if (range == "Normal") { 30 | return r.localBg >= config.low && r.localBg < config.high; 31 | } else { 32 | return r.localBg >= config.high; 33 | } 34 | }); 35 | stats.push(rangeRecords.length); 36 | rangeRecords.sort(function(a,b) { 37 | return a.localBg - b.localBg; 38 | }); 39 | var localBgs = rangeRecords.map(function(r) { return r.localBg; }).filter(function(bg) { return !!bg; }); 40 | 41 | var midpoint = Math.floor(rangeRecords.length / 2); 42 | //var statistics = ss.(new Statician(rangeRecords.map(function(r) { return r.localBg; }))).stats; 43 | 44 | $("").appendTo(tr); 45 | $("").appendTo(tr); 46 | $("").appendTo(tr); 47 | if (rangeRecords.length > 0) { 48 | $("").appendTo(tr); 49 | $("").appendTo(tr); 50 | $("").appendTo(tr); 51 | $("").appendTo(tr); 52 | } else { 53 | $("").appendTo(tr); 54 | $("").appendTo(tr); 55 | $("").appendTo(tr); 56 | $("").appendTo(tr); 57 | } 58 | 59 | table.append(tr); 60 | }); 61 | 62 | var tr = $(""); 63 | $("").appendTo(tr); 64 | $("").appendTo(tr); 65 | $("").appendTo(tr); 66 | if (data.length > 0) { 67 | var localBgs = data.map(function(r) { return r.localBg; }).filter(function(bg) { return !!bg; }); 68 | var mgDlBgs = data.map(function(r) { return r.bgValue; }).filter(function(bg) { return !!bg; }); 69 | $("").appendTo(tr); 70 | $("").appendTo(tr); 71 | $("").appendTo(tr); 72 | $("").appendTo(tr); 73 | } else { 74 | $("").appendTo(tr); 75 | $("").appendTo(tr); 76 | $("").appendTo(tr); 77 | $("").appendTo(tr); 78 | } 79 | table.append(tr); 80 | report.append(table); 81 | 82 | setTimeout(function() { 83 | $.plot( 84 | "#overviewchart", 85 | stats, 86 | { 87 | series: { 88 | pie: { 89 | show: true 90 | } 91 | }, 92 | colors: ["#f88", "#8f8", "#ff8"] 93 | } 94 | ); 95 | }); 96 | }); 97 | }; 98 | -------------------------------------------------------------------------------- /app/report/percentile.js: -------------------------------------------------------------------------------- 1 | function generate_report(data, high, low) { 2 | require(["../bloodsugar"], function(convertBg) { 3 | var Statician = ss; 4 | var config = { 5 | low: convertBg(low), 6 | high: convertBg(high) 7 | }; 8 | var window = 30; //minute-window should be a divisor of 60 9 | var bins = []; 10 | for (hour = 0; hour < 24; hour++) { 11 | for (minute = 0; minute < 60; minute = minute + window) { 12 | var date = new Date(); 13 | date.setHours(hour); 14 | date.setMinutes(minute); 15 | var readings = data.filter(function(record) { 16 | return "bgValue" in record && /\d+/.test(record.bgValue.toString()); 17 | }).filter(function(record) { 18 | var recdate = new Date(record.displayTime); 19 | return recdate.getHours() == hour && recdate.getMinutes() >= minute && 20 | recdate.getMinutes() < minute + window;; 21 | }); 22 | readings = readings.map(function(record) { 23 | return record.localBg; 24 | }); 25 | bins.push([date, readings]); 26 | //console.log(date + " - " + readings.length); 27 | //readings.forEach(function(x){console.log(x)}); 28 | } 29 | } 30 | dat10 = bins.map(function(bin) { 31 | return [bin[0], ss.quantile(bin[1], 0.1)]; 32 | }); 33 | dat25 = bins.map(function(bin) { 34 | return [bin[0], ss.quantile(bin[1], 0.25)]; 35 | }); 36 | dat50 = bins.map(function(bin) { 37 | return [bin[0], ss.quantile(bin[1], 0.5)]; 38 | }); 39 | dat75 = bins.map(function(bin) { 40 | return [bin[0], ss.quantile(bin[1], 0.75)]; 41 | }); 42 | dat90 = bins.map(function(bin) { 43 | return [bin[0], ss.quantile(bin[1], 0.9)]; 44 | }); 45 | high = parseFloat(convertBg(high)); 46 | low = parseFloat(convertBg(low)); 47 | //dat50.forEach(function(x){console.log(x[0] + " - " + x[1])}); 48 | $.plot( 49 | "#percentilechart", [{ 50 | label: "median", 51 | data: dat50, 52 | id: 'c50', 53 | color: "#000000", 54 | points: { 55 | show: false 56 | }, 57 | lines: { 58 | show: true, 59 | //fill: true 60 | } 61 | }, { 62 | label: "25%/75% percentile", 63 | data: dat25, 64 | id: 'c25', 65 | color: "#000055", 66 | points: { 67 | show: false 68 | }, 69 | lines: { 70 | show: true, 71 | fill: true 72 | }, 73 | fillBetween: 'c50' 74 | }, { 75 | data: dat75, 76 | id: 'c75', 77 | color: "#000055", 78 | points: { 79 | show: false 80 | }, 81 | lines: { 82 | show: true, 83 | fill: true 84 | }, 85 | fillBetween: 'c50' 86 | }, { 87 | label: "10%/90% percentile", 88 | data: dat10, 89 | id: 'c10', 90 | color: "#a0a0FF", 91 | points: { 92 | show: false 93 | }, 94 | lines: { 95 | show: true, 96 | fill: true 97 | }, 98 | fillBetween: 'c25' 99 | }, { 100 | data: dat90, 101 | id: 'c90', 102 | color: "#a0a0FF", 103 | points: { 104 | show: false 105 | }, 106 | lines: { 107 | show: true, 108 | fill: true 109 | }, 110 | fillBetween: 'c75' 111 | }, { 112 | label: "high", 113 | data: [], 114 | color: '#FFFF00', 115 | }, { 116 | label: "low", 117 | data: [], 118 | color: '#FF0000', 119 | }], { 120 | xaxis: { 121 | mode: "time", 122 | timezone: "browser", 123 | timeformat: "%H:%M", 124 | tickColor: "#555", 125 | }, 126 | yaxis: { 127 | min: 0, 128 | max: convertBg(400), 129 | tickColor: "#555", 130 | }, 131 | grid: { 132 | markings: [{ 133 | color: '#FF0000', 134 | lineWidth: 2, 135 | yaxis: { 136 | from: low, 137 | to: low 138 | } 139 | }, { 140 | color: '#FFFF00', 141 | lineWidth: 2, 142 | yaxis: { 143 | from: high, 144 | to: high 145 | } 146 | }], 147 | //hoverable: true 148 | } 149 | } 150 | ); 151 | }); 152 | }; 153 | -------------------------------------------------------------------------------- /app/report/hourlystats.js: -------------------------------------------------------------------------------- 1 | function generate_report(data, high, low) { 2 | require(["../bloodsugar"], function(convertBg) { 3 | var days = 3 * 30; // months 4 | var config = { low: convertBg(low), high: convertBg(high) }; 5 | var threemonthsago = new Date(Date.now() - days.days()); 6 | threemonthsago.setSeconds(0); 7 | threemonthsago.setMinutes(0); 8 | threemonthsago.setHours(0); 9 | threemonthsago.setMilliseconds(0); 10 | var report = $("#report"); 11 | var stats = []; 12 | var pivotedByHour = {}; 13 | 14 | data = data.filter(function(record) { 15 | data.localBg = parseFloat(data.localBg); 16 | return record.displayTime > threemonthsago; 17 | }); 18 | for (var i = 0; i < 24; i++) { 19 | pivotedByHour[i] = []; 20 | } 21 | data.filter(function(record) { 22 | return "bgValue" in record && /\d+/.test(record.bgValue.toString()); 23 | }).forEach(function(record) { 24 | var d = new Date(record.displayTime); 25 | pivotedByHour[d.getHours()].push(record); 26 | }); 27 | var table = $("
Range% of Readings# of ReadingsMeanMedianSDA1c estimation*
" + range + ": " + Math.floor(100 * rangeRecords.length / data.length) + "%" + rangeRecords.length + "" + Math.floor(10*Statician.mean(localBgs))/10 + "" + rangeRecords[midpoint].localBg + "" + Math.floor(Statician.standard_deviation(localBgs)*10)/10 + " N/AN/AN/A
Overall: " + data.length + "" + Math.round(10*ss.mean(localBgs))/10 + "" + Math.round(10*ss.quantile(localBgs, 0.5))/10+ "" + Math.round(ss.standard_deviation(localBgs)*10)/10 + "
" + Math.round(10*(ss.mean(mgDlBgs)+46.7)/28.7)/10 + "%DCCT | " +Math.round(((ss.mean(mgDlBgs)+46.7)/28.7 - 2.15)*10.929) + "IFCC
N/AN/AN/AN/A
"); 28 | var thead = $(""); 29 | $("").appendTo(thead); 30 | $("").appendTo(thead); 31 | $("").appendTo(thead); 32 | $("").appendTo(thead); 33 | $("").appendTo(thead); 34 | $("").appendTo(thead); 35 | $("").appendTo(thead); 36 | $("").appendTo(thead); 37 | $("").appendTo(thead); 38 | thead.appendTo(table); 39 | 40 | [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23].forEach(function(hour) { 41 | var tr = $(""); 42 | var display = hour % 12; 43 | if (hour === 0) { 44 | display = "12"; 45 | } 46 | display += ":00 "; 47 | if (hour >= 12) { 48 | display += "PM"; 49 | } else { 50 | display += "AM"; 51 | } 52 | 53 | var avg = Math.floor(pivotedByHour[hour].map(function(r) { return r.localBg; }).reduce(function(o,v){ return o+v; }, 0) / pivotedByHour[hour].length); 54 | var d = new Date(hour.hours()); 55 | // d.setHours(hour); 56 | // d.setMinutes(0); 57 | // d.setSeconds(0); 58 | // d.setMilliseconds(0); 59 | 60 | var dev = ss.standard_deviation(pivotedByHour[hour].map(function(r) { return r.localBg; })); 61 | stats.push([ 62 | new Date(d), 63 | ss.quantile(pivotedByHour[hour].map(function(r) { return r.localBg; }), 0.25), 64 | ss.quantile(pivotedByHour[hour].map(function(r) { return r.localBg; }), 0.75), 65 | avg - dev, 66 | avg + dev 67 | // Math.min.apply(Math, pivotedByHour[hour].map(function(r) { return r.localBg; })), 68 | // Math.max.apply(Math, pivotedByHour[hour].map(function(r) { return r.localBg; })) 69 | ]); 70 | $("").appendTo(tr); 71 | $("").appendTo(tr); 72 | $("").appendTo(tr); 73 | $("").appendTo(tr); 74 | $("").appendTo(tr); 75 | $("").appendTo(tr); 76 | $("").appendTo(tr); 77 | $("").appendTo(tr); 78 | $("").appendTo(tr); 79 | table.append(tr); 80 | }); 81 | 82 | report[0].innerHTML = ""; 83 | report.append(table); 84 | 85 | 86 | setTimeout(function() { 87 | // var data = $.plot.candlestick.createCandlestick({ 88 | // label:"my Company", 89 | // data:stats, 90 | // candlestick:{ 91 | // show:true, 92 | // lineWidth:"1" 93 | // } 94 | // }); 95 | $.plot( 96 | "#overviewchart", 97 | [{ 98 | data:stats, 99 | candle:true 100 | }], 101 | { 102 | series: { 103 | candle: true, 104 | lines: false //Somehow it draws lines if you dont disable this. Should investigate and fix this ;) 105 | }, 106 | xaxis: { 107 | mode: "time", 108 | timeFormat: "%h:00", 109 | min: 0, 110 | max: (24).hours()-(1).seconds() 111 | }, 112 | yaxis: { 113 | min: 0, 114 | max: convertBg(400), 115 | show: true 116 | }, 117 | grid: { 118 | show: true 119 | } 120 | } 121 | ); 122 | },100); 123 | 124 | $(".print").click(function(e) { 125 | e.preventDefault(); 126 | window.print(); 127 | }); 128 | }); 129 | } -------------------------------------------------------------------------------- /app/help.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Help 5 | 6 | 7 | 8 | 13 | 14 | 15 |
16 |

Welcome to Nightscout CGM Utility

17 |

Have a seat. Get comfortable. Enjoy having your CGM data on your Mac, your PC, or in the cloud.

18 |

How do I get started?

19 |

There are a few reasons you're using Nightscout CGM Utility. Which one of these matches why you're using this?

20 |

There's a Youtube video showing how to use this, if you'd rather not read.

21 | 27 |

There's other things you can use CGM Utility for.

28 | 31 | 32 |

I want to use Nightscout Remote CGM

33 |

Nightscout setups usually have you buy a phone, plug Dexcom into it, and the phone uploads your CGM data to the cloud. Instead of buying a phone, you can plug Dexcom into your existing computer and get data to Nightscout without spending anything.

34 |

Start by reading Nightscout's Getting Started Guide. Skip the step about the Android App. Open Options in Nightscout CGM Utility, choose the Mongolab tab, and enter the Database and Collection you picked while preforming "Configuring the data Backend." You'll also need to enter an API Key which is different from the normal directions. Press the Test Connection button, and it'll tell you the Mongolab configuration checks out OK or come back with something that needs changed. Once it's OK, press Save Settings.

Now plug in your Dexcom. Press the "Download All" button. It takes about a minute, perhaps two, for all your data to download. Your most recent CGM reading will upload to Mongolab, and Nightscout will magically start coming to life.

Nightscout CGM Utility checks for updated readings every minute. You don't need to press Download All again, unless you're disconnected from computer for more than 18 hours.

35 | 36 |

I already use Nightscout with the Android uploader.

37 |

This meanas your data is already out in Mongolab. Fantastic! Open Nightscout CGM Utility, click Options, choose the Mongolab tab, and enter the Database, Collection and API key from your existing Nightscout setup. You probably have a username/password pair already, but you'll need an API key for this tool to work. Click the "Documentation" link under the API Key textbox to track it down. Press the Test Connection button and it will hopefully tell you the connection is OK or come up with a suggestion about what to fix.

38 |

Once it's OK, press Save Settings. Click the down arror to the right of Download All, and choose From Mongolab. It'll take about 1 second to download every 3 days of data you've collected. It'll tell you when it's done, and now you can run reports on your data.

39 | 40 |

I want to run reports

41 |

Your primary use is probably to treat this like it's Dexcom Studio, like our Windows-using friends can do. Be aware that Studio has more reports, and is generally better. But this has the advantage that it actually works on computers that don't rhyme with Cindows.

42 |
    43 |
  1. Plug in your Dexcom.
  2. 44 |
  3. Start Nightscout CGM Utility
  4. 45 |
  5. Press Download All
  6. 46 |
  7. When it's done, press the Reports menu and choose what you'd like to see.
  8. 47 |
48 |

Nightscout CGM Utility only accesses roughly 45 days of readings from your receiver. Try to plug in once a month so you don't miss any data.

49 |

There is a Print button on each report screen. You can print to a printer, or save it as a PDF and then do whatever you like with it.

50 | 51 |

I want to play with Dexcom as a programmer

52 |

Check out the source code for this on Github. Most of the magic is in app/datasource/dexcom.js.

53 | 54 |

Reports as a PDF File

55 |

There is a Print button on each report screen. You can print to a printer, or save it as a PDF and then do whatever you like with it.

56 |
57 | 58 | -------------------------------------------------------------------------------- /app/report/stats_controls.js: -------------------------------------------------------------------------------- 1 | /* Adrian: 2 | 3 | This script will add two DatePicker (from, to), two arrow buttons to jump to the neighbouring timeframe and a "Print" button to a
with id "stats_controls". 4 | "Generate Report" will pre-filter the data according to the dates given by the DatePickers and then call a function "generate_report(data, high, low);" that has to be provided by the programmer. 5 | 6 | data - array of datapoints in the timerange. 7 | high - the value of the option targetrange.high. 8 | low- the value of the option targetrange.low. 9 | 10 | To use this script in an html-file: 11 | 12 | 1st: Import it: 13 | 2nd: Add a div with id "stats_controls" in your html-file where you want the controls placed. This could look like:
14 | 3rd: Provide the function "generate_report(data, high, low);", that will actually generate the report. 15 | 4th: Import css for a more beautiful DatePicker: 16 | 17 | */ 18 | 19 | var fromold = ""; 20 | var toold = ""; 21 | 22 | var general_generate_report = function() { 23 | require(["../bloodsugar"], function(convertBg) { 24 | var low, high; 25 | Promise.all([ 26 | new Promise(function(ready) { 27 | chrome.storage.local.get(["egvrecords", "config"], function(values) { 28 | if ("config" in values && "targetrange" in values.config) { 29 | low = values.config.targetrange.low || 70; 30 | high = values.config.targetrange.high || 130; 31 | } else { 32 | low = 70; 33 | high = 130; 34 | } 35 | ready(values.egvrecords.map(function(r) { 36 | r.localBg = parseFloat(convertBg(r.bgValue)); 37 | return r; 38 | })); 39 | }); 40 | }) 41 | ]).then(function(o) { 42 | var data = o[0]; 43 | var config = { 44 | low: convertBg(low), 45 | high: convertBg(high) 46 | }; 47 | var one = 1; 48 | var startdate = Date.parse($("#fromdate").val()); 49 | var enddate = Date.parse($("#todate").val()) + one.days(); 50 | 51 | $("#dateselectionerrormessage").empty(); 52 | if(startdate>=enddate){ 53 | $("#fromdate").val(fromold); 54 | $("#todate").val(toold); 55 | $("#dateselectionerrormessage").append("reset to previous date (To was after From)!"); 56 | return; 57 | } 58 | fromold = $("#fromdate").val(); 59 | toold = $("#todate").val(); 60 | var datestring = $("#fromdate").val() + " - " + $("#todate").val(); 61 | $("#dateoutput").empty(); 62 | $("#dateoutput").append(datestring); 63 | data = data.filter(function(record) { 64 | return (record.displayTime >= startdate) && (record.displayTime < enddate); 65 | }); 66 | 67 | generate_report(data, high, low); 68 | }); 69 | }); 70 | } 71 | 72 | 73 | $(function() { 74 | Promise.all([ 75 | new Promise(function(ready) { 76 | var controlshtml = "

From Date: To Date:

"; 77 | ready($("#stats_controls").append($(controlshtml))); 78 | }) 79 | ]).then(function(o) { 80 | //register datepicker 81 | require(["jquery", "/vendor/jquery-ui/jquery-ui.min.js"], function($) { 82 | $("#fromdate").datepicker({onClose: general_generate_report}); 83 | $("#todate").datepicker({onClose: general_generate_report}); 84 | }); 85 | 86 | //add presets for dates 87 | var now = new Date(); 88 | $("#todate").val((now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear()); 89 | toold = $("#todate").val(); 90 | var one = 1; 91 | var then = new Date(Date.now() - one.months()); 92 | $("#fromdate").val((then.getMonth() + 1) + "/" + then.getDate() + "/" + then.getFullYear()); 93 | fromold = $("#fromdate").val(); 94 | 95 | //add handler 96 | $(".print").click(function(e) { 97 | e.preventDefault(); 98 | window.print(); 99 | }); 100 | 101 | $("#dateleft").click(function() { 102 | var from = Date.parse($("#fromdate").val()); 103 | var to = Date.parse($("#todate").val()); 104 | //daylight saving time may make diffs just very close to full days: 105 | var diff = Math.round((to - from)/(1000 * 60 * 60 * 24))*(1000 * 60 * 60 * 24); 106 | var one = 1; 107 | to = from - one.days(); 108 | from = to - diff; 109 | to = new Date(to); 110 | from = new Date(from); 111 | $("#todate").val("" + (to.getMonth()+1) + "/" + to.getDate() + "/" + to.getFullYear()); 112 | $("#fromdate").val("" + (from.getMonth()+1) + "/" + from.getDate() + "/" + from.getFullYear()); 113 | general_generate_report(); 114 | }); 115 | 116 | $("#dateright").click(function() { 117 | var from = Date.parse($("#fromdate").val()); 118 | var to = Date.parse($("#todate").val()); 119 | //daylight saving time may make diffs just very close to full days: 120 | var diff = Math.round((to - from)/(1000 * 60 * 60 * 24))*(1000 * 60 * 60 * 24); 121 | var one = 1; 122 | from = to + one.days(); 123 | to = from + diff; 124 | to = new Date(to); 125 | from = new Date(from); 126 | $("#todate").val("" + (to.getMonth()+1) + "/" + to.getDate() + "/" + to.getFullYear()); 127 | $("#fromdate").val("" + (from.getMonth()+1) + "/" + from.getDate() + "/" + from.getFullYear()); 128 | general_generate_report(); 129 | }); 130 | 131 | 132 | 133 | 134 | }).then(function(x){general_generate_report();}); 135 | 136 | }); 137 | -------------------------------------------------------------------------------- /app/feature/cgm_download.js: -------------------------------------------------------------------------------- 1 | define(["../datasource/dexcom", "../datasource/remotecgm", "../store/egv_records", "/app/config.js!"], function(dexcom, remotecgm, egvrecords, config) { 2 | var cgm = dexcom, 3 | isdownloading = false; 4 | var isWindows = !!~window.navigator.appVersion.indexOf("Win"); 5 | var isMac = !!~window.navigator.appVersion.indexOf("Mac OS X"); 6 | 7 | var pickDatasource = function(datasource) { 8 | if (datasource == "dexcom") { 9 | cgm = dexcom; 10 | } else { 11 | cgm = remotecgm; 12 | } 13 | }; 14 | 15 | config.on("datasource", pickDatasource); 16 | pickDatasource(config.datasource); 17 | var max_allowed; 18 | 19 | // emit events that UI can react to 20 | var connect = function() { 21 | var chrome_notification_id = 0; 22 | var connectionErrorCB = function(notification_id, button) { 23 | chrome.notifications.onButtonClicked.removeListener(connectionErrorCB); 24 | if (notification_id != chrome_notification_id) return; 25 | 26 | if (button === 0) { 27 | attempts = 0; 28 | connect().then(onConnected,onConnectError); // chain to start everything 29 | } 30 | }; 31 | return new Promise(function(resolve, reject) { 32 | if (isdownloading) reject(); 33 | isdownloading = true; 34 | var timer = new Date(); 35 | var max_existing = (egvrecords.length > 0? 36 | (egvrecords[egvrecords.length - 1].displayTime || egvrecords[egvrecords.length - 1].date ): 37 | 0); 38 | max_allowed = new Date(Date.now() + (1).days()); 39 | 40 | console.debug("[cgm_download.js connect] loading"); 41 | cgm.connect().then(function() { // success 42 | console.debug("[cgm_download.js connect] successfully connected to %s", config.datasource); 43 | 44 | chrome.notifications.onButtonClicked.removeListener(connectionErrorCB); 45 | try { 46 | var page = 1; 47 | var d = []; // data 48 | var process = function(d_page) { 49 | console.debug("[cgm_download.js process] read page %i", page); 50 | d = d.concat(d_page); 51 | if(d_page.filter(function(egv) { 52 | return ((+egv.displayTime || +egv.date) > max_existing) 53 | && ((+egv.displayTime || +egv.date) < max_allowed); 54 | }).length == 0) { 55 | console.debug("[cgm_download.js process] stopped reading at page %i", page); 56 | cgm.disconnect(); 57 | isdownloading = false; 58 | console.debug("[cgm_download.js process] spent %i ms downloading", (new Date() - timer)); 59 | resolve(d); 60 | } else { 61 | cgm.readFromReceiver(++page).then(process); 62 | } 63 | } 64 | return cgm.readFromReceiver(page).then(process); 65 | } catch (e) { 66 | console.debug("[cgm_download.js process] %o", e); 67 | reject(e); 68 | } 69 | }, function(e) { // failed to connect 70 | console.debug("[cgm_download connect] failed to connect"); 71 | chrome.notifications.create("", { 72 | type: "basic", 73 | title: "NightScout.info CGM Utility", 74 | message: "Could not connect to Dexcom receiver. Unplug it and plug it back in. Be gentle, Dexcom's USB port is fragile. I like to unplug from the computer's side.", 75 | iconUrl: "/public/assets/error.png", 76 | buttons: [{ 77 | title: "Try again" 78 | }, { 79 | title: "Cancel" 80 | }] 81 | }, function(notification_id) { 82 | console.log(arguments); 83 | chrome_notification_id = notification_id; 84 | attempts = 0; // reset 85 | chrome.notifications.onButtonClicked.addListener(connectionErrorCB); 86 | }); 87 | reject(e); 88 | }); 89 | }); 90 | }, 91 | onConnected = function(data) { // to download from dexcom 92 | var lastNewRecord = Date.now(); 93 | 94 | // update my db 95 | var existing = egvrecords || []; 96 | var max_existing = existing.length > 0? 97 | (existing[existing.length - 1].displayTime || existing[existing.length].date) : 98 | 0; 99 | var new_records = data.filter(function(egv) { 100 | return( +egv.displayTime > max_existing )|| (+egv.date > max_existing); 101 | }).map(function(egv) { 102 | return { 103 | displayTime: +egv.displayTime || +egv.date, 104 | bgValue: egv.bgValue || egv.sgv, 105 | trend: egv.trend || egv.direction, 106 | recordSource: config.datasource 107 | }; 108 | }); 109 | if (new_records.length === 0) { 110 | if (lastNewRecord + (5).minutes() < Date.now()) { 111 | console.warn("[cgm_download.js updateLocalDb] Something's wrong. We should have new data by now."); 112 | } 113 | } else { 114 | lastNewRecord = Date.now(); 115 | } 116 | new_records = new_records.filter(function(row) { 117 | return row.bgValue > 30 && row.displayTime < max_allowed; 118 | }); 119 | egvrecords.addAll(new_records); 120 | 121 | var nextRun = function() { 122 | console.log("[cgmdownload.js nextRun] Attempting to refresh data"); 123 | if (isdownloading) { 124 | setTimeout(nextRun, (60).seconds()); 125 | } else { 126 | connect().then(onConnected, onConnectError); 127 | } 128 | }; 129 | 130 | // again and again 131 | setTimeout(nextRun, (60).seconds()); 132 | }, 133 | onConnectError = function(){ 134 | console.log(arguments); 135 | }; 136 | egvrecords.onLoad.then(function() { 137 | connect().then(onConnected, onConnectError); // chain to start everything 138 | }); 139 | 140 | return { 141 | getAllRecords: function() { 142 | var oldCgm = cgm; 143 | cgm = dexcom; 144 | var p = cgm.getAllRecords(); 145 | p.then(function() { 146 | cgm = oldCgm; 147 | }); 148 | return p; 149 | } 150 | } 151 | }); -------------------------------------------------------------------------------- /app/report/dailystats.js: -------------------------------------------------------------------------------- 1 | require(["../bloodsugar"], function(convertBg) { 2 | var low, high; 3 | Promise.all([ 4 | new Promise(function(ready) { 5 | chrome.storage.local.get(["egvrecords", "config"], function(values) { 6 | if ("config" in values && "targetrange" in values.config) { 7 | low = values.config.targetrange.low || 70; 8 | high = values.config.targetrange.high || 180; 9 | } else { 10 | low = 70; 11 | high = 180; 12 | } 13 | 14 | ready(values.egvrecords.map(function(r) { 15 | r.localBg = convertBg(r.bgValue); 16 | return r; 17 | })); 18 | }); 19 | }) 20 | ]).then(function(o) { 21 | var todo = []; 22 | var data = o[0]; 23 | var days = 7; 24 | var config = { low: convertBg(low), high: convertBg(high) }; 25 | var sevendaysago = Date.now() - days.days(); 26 | var report = $("#report"); 27 | var minForDay, maxForDay; 28 | var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]; 29 | 30 | data = data.filter(function(record) { 31 | return "bgValue" in record && /\d+/.test(record.bgValue.toString()); 32 | }).filter(function(record) { 33 | return record.displayTime > sevendaysago; 34 | }); 35 | var table = $("
TimeReadingsAvgMinQuartile 25MedianQuartile 75MaxSt Dev
" + display + "" + pivotedByHour[hour].length + " (" + Math.floor(100 * pivotedByHour[hour].length / data.length) + "%)" + avg + "" + Math.min.apply(Math, pivotedByHour[hour].map(function(r) { return r.localBg; })) + "" + ss.quantile(pivotedByHour[hour].map(function(r) { return r.localBg; }), 0.25) + "" + ss.quantile(pivotedByHour[hour].map(function(r) { return r.localBg; }), 0.5) + "" + ss.quantile(pivotedByHour[hour].map(function(r) { return r.localBg; }), 0.75) + "" + Math.max.apply(Math, pivotedByHour[hour].map(function(r) { return r.localBg; })) + "" + Math.floor(dev*10)/10 + "
"); 36 | var thead = $(""); 37 | $("").appendTo(thead); 38 | $("").appendTo(thead); 39 | $("").appendTo(thead); 40 | $("").appendTo(thead); 41 | $("").appendTo(thead); 42 | $("").appendTo(thead); 43 | $("").appendTo(thead); 44 | $("").appendTo(thead); 45 | $("").appendTo(thead); 46 | $("").appendTo(thead); 47 | $("").appendTo(thead); 48 | $("").appendTo(thead); 49 | thead.appendTo(table); 50 | 51 | [7,6,5,4,3,2,1].forEach(function(day) { 52 | var tr = $(""); 53 | var dayInQuestion = new Date(Date.now() - (day).days()); 54 | dayInQuestion.setSeconds(0); 55 | dayInQuestion.setMinutes(0); 56 | dayInQuestion.setHours(0); 57 | dayInQuestion.setMilliseconds(0); 58 | var dayEnds = new Date(dayInQuestion).getTime() + (1).days(); 59 | 60 | 61 | 62 | var daysRecords = data.filter(function(r) { 63 | return r.displayTime >= dayInQuestion.getTime() && r.displayTime <= dayEnds; 64 | }); 65 | if (daysRecords.length == 0) { 66 | $("").appendTo(tr); 68 | $("").appendTo(tr); 69 | table.append(tr); 70 | return; 71 | } 72 | todo.push(function() { 73 | var inrange = [ 74 | { 75 | label: "Low", 76 | data: Math.floor(stats.lows * 1000 / daysRecords.length) / 10 77 | }, 78 | { 79 | label: "In range", 80 | data: Math.floor(stats.normal * 1000 / daysRecords.length) / 10 81 | }, 82 | { 83 | label: "High", 84 | data: Math.floor(stats.highs * 1000 / daysRecords.length) / 10 85 | } 86 | ]; 87 | $.plot( 88 | "#chart" + day.toString(), 89 | inrange, 90 | { 91 | series: { 92 | pie: { 93 | show: true 94 | } 95 | }, 96 | colors: ["#f88", "#8f8", "#ff8"] 97 | } 98 | ); 99 | }); 100 | 101 | minForDay = daysRecords[0].localBg; 102 | maxForDay = daysRecords[0].localBg; 103 | var stats = daysRecords.reduce(function(out, record) { 104 | record.localBg = parseFloat(record.localBg); 105 | if (record.localBg < config.low) { 106 | out.lows++; 107 | } else if (record.localBg < config.high) { 108 | out.normal++; 109 | } else { 110 | out.highs++; 111 | } 112 | if (minForDay > record.localBg) minForDay = record.localBg; 113 | if (maxForDay < record.localBg) maxForDay = record.localBg; 114 | return out; 115 | }, { 116 | lows: 0, 117 | normal: 0, 118 | highs: 0 119 | }); 120 | var bgValues = daysRecords.map(function(r) { return r.localBg; }); 121 | $("").appendTo(tr); 122 | todo.push(function() { 123 | var inrange = [ 124 | { 125 | label: "Low", 126 | data: Math.floor(stats.lows * 1000 / daysRecords.length) / 10 127 | }, 128 | { 129 | label: "In range", 130 | data: Math.floor(stats.normal * 1000 / daysRecords.length) / 10 131 | }, 132 | { 133 | label: "High", 134 | data: Math.floor(stats.highs * 1000 / daysRecords.length) / 10 135 | } 136 | ]; 137 | $.plot( 138 | "#chart" + day.toString(), 139 | inrange, 140 | { 141 | series: { 142 | pie: { 143 | show: true 144 | } 145 | }, 146 | colors: ["#f88", "#8f8", "#ff8"] 147 | } 148 | ); 149 | }); 150 | 151 | $("").appendTo(tr); 152 | $("").appendTo(tr); 153 | $("").appendTo(tr); 154 | $("").appendTo(tr); 155 | $("").appendTo(tr); 156 | $("").appendTo(tr); 157 | $("").appendTo(tr); 158 | $("").appendTo(tr); 159 | $("").appendTo(tr); 160 | $("").appendTo(tr); 161 | $("").appendTo(tr); 162 | 163 | table.append(tr); 164 | }); 165 | 166 | report.append(table); 167 | 168 | $(".print").click(function(e) { 169 | e.preventDefault(); 170 | window.print(); 171 | }); 172 | 173 | 174 | setTimeout(function() { 175 | todo.forEach(function(fn) { 176 | fn(); 177 | }); 178 | }, 50); 179 | }); 180 | }); -------------------------------------------------------------------------------- /app/feature/trending_alerts.js: -------------------------------------------------------------------------------- 1 | // todo: use config object 2 | define(["../bloodsugar", "../store/egv_records", "/app/config.js!"], function(convertBg, egvrecords, config) { 3 | var current_direction; 4 | var current_bg = 0; 5 | 6 | var newReading = function(cur_r, last_r) { 7 | 8 | var cur_record = cur_r; 9 | var last_record = last_r; 10 | var high = 400 11 | var low = 0 12 | 13 | high = config.targetrange.high; 14 | low = config.targetrange.low; 15 | 16 | var now_trend = cur_record.trend; 17 | var last_bg = last_record? last_record.bgValue: false; 18 | var now_bg = cur_record.bgValue; 19 | 20 | var at = (function(d) {return function() { 21 | var h = d.getHours() % 12, m = d.getMinutes(); 22 | if (m < 10) m = "0" + m.toString(); 23 | 24 | if (h == 0) h = "12"; 25 | var ampm = d.getHours() >= 12? "pm": "am"; 26 | return " at " + h + ":" + m + ampm; 27 | }; })(new Date()); 28 | 29 | 30 | if (config.notifications == "none"|| (now_bg==current_bg && current_direction == now_trend)) { 31 | //do nothing 32 | 33 | 34 | // falling too fast no other considerations 35 | } else if (now_trend == "DoubleDown" && now_bg < 150) { 36 | doNotify(now_bg, 2, "You're trending double down. #cgmnow " + convertBg(now_bg) + at(), high, low); 37 | 38 | 39 | // falling fast but slowing 40 | } else if (now_trend == "SingleDown" && now_trend == "DoubleDown") { 41 | doNotify(now_bg,1, "Your fall has slowed. You were double down but are now single down. #cgmnow " + convertBg(now_bg) + at(), high, low); 42 | 43 | // falling too fast considering current bg 44 | } else if (now_trend == "SingleDown" && now_bg < 130 && (last_bg? last_bg >= 130: true)) { 45 | doNotify(now_bg,2, "You're trending single down. #cgmnow " + convertBg(now_bg) + at(), high, low); 46 | 47 | 48 | // falling but slowing 49 | } else if (now_trend == "FortyFiveDown" && (["SingleDown", "DoubleDown"].indexOf(now_trend) > -1)) { 50 | doNotify(now_bg,1, "Your fall has slowed. You were " + now_trend + " but are now forty five down down. #cgmnow " + convertBg(now_bg) + at(), high, low); 51 | 52 | // falling too fast considering current bg 53 | } else if (now_trend == "FortyFiveDown" && now_bg < 110 && (last_bg? last_bg >= 110: true)) { 54 | doNotify(2, "You're trending forty five down. #cgmnow " + convertBg(now_bg) + at(), high, low); 55 | 56 | 57 | 58 | // raising too fast 59 | } else if (now_trend == "DoubleUp" && now_bg > 110 && ( last_bg? last_bg <= 110: true)) { 60 | doNotify(now_bg,2, "You're trending double up. #cgmnow " + convertBg(now_bg) + at(), high, low); 61 | 62 | // rising fast but slowing 63 | } else if (now_trend == "SingleUp" && now_trend == "DoubleUp") { 64 | doNotify(now_bg,1, "Your rise has slowed. You were double up but are now single up. #cgmnow " + convertBg(now_bg) + at(), high, low); 65 | 66 | // rising too fast considering current bg 67 | } else if (now_trend == "SingleUp" && now_bg > 130 && (last_bg? last_bg <= 130: true)) { 68 | doNotify(now_bg,2, "You're trending single up. #cgmnow " + convertBg(now_bg) + at(), high, low); 69 | 70 | 71 | // rising but slowing 72 | } else if (now_trend == "FortyFiveUp" && (["SingleUp", "DoubleUp"].indexOf(now_trend) > -1)) { 73 | doNotify(now_bg,1, "Your rise has slowed. You were " + now_trend + " but are now forty five up up. #cgmnow " + convertBg(now_bg) + at()); 74 | 75 | // falling too fast considering current bg 76 | } else if (now_trend == "FortyFiveUp" && now_bg > 150 && (last_bg? last_bg <= 150: true)) { 77 | doNotify(now_bg,2, "You're trending forty five up. #cgmnow " + convertBg(now_bg) + at(), high, low); 78 | 79 | } else if (current_direction && current_direction != now_trend) { 80 | doNotify(now_bg,1, "Trend direction changed to " + now_trend + ". You're #cgmnow " + convertBg(now_bg) + at(), high, low); 81 | 82 | } else if (config.notifications == "all" && (!last_bg || current_bg != now_bg)){ 83 | doNotify(now_bg,3, "You're #cgmnow " + convertBg(now_bg) + at() + ". The trend is " + now_trend +".", high, low); 84 | 85 | } else { 86 | console.log("No notification fit."); 87 | } 88 | current_direction = now_trend; 89 | current_bg = now_bg; 90 | }; 91 | 92 | function doNotify(bg_value,priority, message, high, low){ 93 | Promise.all([ 94 | new Promise(function(ready) { 95 | ready(config.notifications_timeout || "no"); 96 | }), 97 | new Promise(function(ready) { 98 | ready(config.notifications_bignumbers || "no"); 99 | }) 100 | ]).then(function(settings){ 101 | var timeout_funct = function(notification_id){}; 102 | if(settings[0] != "no"){ 103 | timeout_funct = function(notification_id) { 104 | setTimeout(function(){ 105 | chrome.notifications.clear(notification_id, function(notification_id) { 106 | //nothing 107 | }); 108 | }, parseInt(settings[0]).seconds()); 109 | }; 110 | } 111 | 112 | if(settings[1] == "no"){ 113 | chrome.notifications.create("", { 114 | type: "basic", 115 | title: "NightScout.info CGM Utility", 116 | message: "" + message, 117 | iconUrl: "/public/assets/icon.png", 118 | priority: priority, 119 | }, timeout_funct); 120 | } else{ 121 | //create canvas 122 | var canvas = document.createElement('canvas'); 123 | canvas.width = 80; 124 | canvas.height = 45; 125 | var ctx = canvas.getContext('2d'); 126 | ctx.fillStyle = ""; 127 | ctx.fillRect(0, 0, canvas.width,canvas.height); 128 | ctx.fillStyle = "rgb(200,0,0)"; 129 | if (bg_value >= low) ctx.fillStyle = "rgb(0,200,0)"; 130 | if (bg_value > high) ctx.fillStyle = "rgb(250,250,0)"; 131 | ctx.font = "30px Verdana"; 132 | ctx.fillText(convertBg(bg_value),5,35); 133 | var dataURL = canvas.toDataURL('image/png'); 134 | //create notification 135 | chrome.notifications.create("", { 136 | type: "image", 137 | title: "NightScout.info CGM Utility", 138 | message: "" + message, 139 | iconUrl: "/public/assets/icon.png", 140 | imageUrl: dataURL, 141 | priority: priority, 142 | }, timeout_funct); 143 | } 144 | }); 145 | } 146 | egvrecords.onChange(function(new_r, all) { 147 | var cur_record = all[all.length - 1], 148 | last_record = null; 149 | if (all.length > 1) { 150 | last_record = all[all.length - 2]; 151 | } 152 | newReading(cur_record, last_record); 153 | }); 154 | }); 155 | -------------------------------------------------------------------------------- /app/report/success.js: -------------------------------------------------------------------------------- 1 | require(["../store/egv_records", "../bloodsugar", "/app/config.js!"], function(data, convertBg, config) { 2 | var low = parseInt(config.targetrange.low), 3 | high = parseInt(config.targetrange.high); 4 | var config = { 5 | low: convertBg(low), 6 | high: convertBg(high) 7 | }; 8 | var now = Date.now(); 9 | var period = (7).days(); 10 | var firstDataPoint = data.reduce(function(min, record) { 11 | return Math.min(min, record.displayTime); 12 | }, Number.MAX_VALUE); 13 | if (firstDataPoint < 1390000000000) firstDataPoint = 1390000000000; 14 | var quarters = Math.floor((Date.now() - firstDataPoint) / period); 15 | 16 | var grid = $("#grid"); 17 | var table = $("
DateLowsNormalHighReadingsMinMaxStDev25%Median75%
").appendTo(tr); 67 | $("" + (months[dayInQuestion.getMonth()] + " " + dayInQuestion.getDate()) + "No data available
" + (months[dayInQuestion.getMonth()] + " " + dayInQuestion.getDate()) + "" + Math.floor((100 * stats.lows) / daysRecords.length) + "%" + Math.floor((100 * stats.normal) / daysRecords.length) + "%" + Math.floor((100 * stats.highs) / daysRecords.length) + "%" + daysRecords.length +"" + minForDay +"" + maxForDay +"" + Math.floor(ss.standard_deviation(bgValues)) + "" + ss.quantile(bgValues, 0.25) + "" + ss.quantile(bgValues, 0.5) + "" + ss.quantile(bgValues, 0.75) + "
"); 18 | 19 | if (quarters == 0) { 20 | // insufficent data 21 | grid.append("

There is not yet sufficent data to run this report. Try again in a couple days.

"); 22 | return; 23 | } 24 | 25 | var dim = function(n) { 26 | var a = []; 27 | for (i = 0; i < n; i++) { 28 | a[i]=0; 29 | } 30 | return a; 31 | } 32 | var sum = function(a) { 33 | return a.reduce(function(sum,v) { 34 | return sum+v; 35 | }, 0); 36 | } 37 | var averages = { 38 | percentLow: 0, 39 | percentInRange: 0, 40 | percentHigh: 0, 41 | standardDeviation: 0, 42 | lowerQuartile: 0, 43 | upperQuartile: 0, 44 | average: 0 45 | }; 46 | try { 47 | quarters = dim(quarters).map(function(blank, n) { 48 | var starting = new Date(now - (n+1) * period), 49 | ending = new Date(now - n * period); 50 | return { 51 | starting: starting, 52 | ending: ending, 53 | records: data.filter(function(record) { 54 | return record.displayTime > starting && 55 | record.displayTime <= ending && 56 | "bgValue" in record && 57 | /\d+/.test(record.bgValue.toString()); 58 | }) 59 | }; 60 | }).filter(function(quarter) { 61 | return quarter.records.length > 0; 62 | }).map(function(quarter, ix, all) { 63 | var bgValues = quarter.records.map(function(record) { 64 | return parseInt(record.bgValue,10); 65 | }); 66 | quarter.standardDeviation = ss.standard_deviation(bgValues); 67 | quarter.average = bgValues.length > 0? (sum(bgValues) / bgValues.length): "N/A"; 68 | quarter.lowerQuartile = ss.quantile(bgValues, 0.25); 69 | quarter.upperQuartile = ss.quantile(bgValues, 0.75); 70 | quarter.numberLow = bgValues.filter(function(bg) { 71 | return bg < low; 72 | }).length; 73 | quarter.numberHigh = bgValues.filter(function(bg) { 74 | return bg >= high; 75 | }).length; 76 | quarter.numberInRange = bgValues.length - (quarter.numberHigh + quarter.numberLow); 77 | 78 | quarter.percentLow = (quarter.numberLow / bgValues.length) * 100; 79 | quarter.percentInRange = (quarter.numberInRange / bgValues.length) * 100; 80 | quarter.percentHigh = (quarter.numberHigh / bgValues.length) * 100; 81 | 82 | averages.percentLow += quarter.percentLow / all.length; 83 | averages.percentInRange += quarter.percentInRange / all.length; 84 | averages.percentHigh += quarter.percentHigh / all.length; 85 | averages.lowerQuartile += quarter.lowerQuartile / all.length; 86 | averages.upperQuartile += quarter.upperQuartile / all.length; 87 | averages.average += quarter.average / all.length; 88 | averages.standardDeviation += quarter.standardDeviation / all.length; 89 | return quarter; 90 | }); 91 | } catch (e) { 92 | console.log(e); 93 | } 94 | 95 | var lowComparison = function(quarter, averages, field, invert) { 96 | if (quarter[field] < averages[field] * 0.8) { 97 | return (invert? "bad": "good"); 98 | } else if (quarter[field] > averages[field] * 1.2) { 99 | return (invert? "good": "bad"); 100 | } else { 101 | return ""; 102 | } 103 | } 104 | 105 | var lowQuartileEvaluation = function(quarter, averages) { 106 | if (quarter.lowerQuartile < low) { 107 | return "bad"; 108 | } else { 109 | return lowComparison(quarter, averages, "lowerQuartile"); 110 | } 111 | } 112 | 113 | var upperQuartileEvaluation = function(quarter, averages) { 114 | if (quarter.upperQuartile > high) { 115 | return "bad"; 116 | } else { 117 | return lowComparison(quarter, averages, "upperQuartile"); 118 | } 119 | } 120 | 121 | var averageEvaluation = function(quarter, averages) { 122 | if (quarter.average > high) { 123 | return "bad"; 124 | } else if (quarter.average < low) { 125 | return "bad"; 126 | } else { 127 | return lowComparison(quarter, averages, "average", true); 128 | } 129 | } 130 | 131 | table.append(""); 132 | table.append("" + quarters.filter(function(quarter) { 133 | return quarter.records.length > 0; 134 | }).map(function(quarter) { 135 | try { 136 | var INVERT = true; 137 | return "" + [ 138 | quarter.starting.format("M d Y") + " - " + quarter.ending.format("M d Y"), 139 | { 140 | klass: lowComparison(quarter, averages, "percentLow"), 141 | text: Math.round(quarter.percentLow) + "%" 142 | }, 143 | { 144 | klass: lowComparison(quarter, averages, "percentInRange", INVERT), 145 | text: Math.round(quarter.percentInRange) + "%" 146 | }, 147 | { 148 | klass: lowComparison(quarter, averages, "percentHigh"), 149 | text: Math.round(quarter.percentHigh) + "%" 150 | }, 151 | { 152 | klass: lowComparison(quarter, averages, "standardDeviation"), 153 | text: (quarter.standardDeviation > 10? Math.round(quarter.standardDeviation): quarter.standardDeviation.toFixed(1)) 154 | }, 155 | { 156 | klass: lowQuartileEvaluation(quarter, averages), 157 | text: convertBg(quarter.lowerQuartile) 158 | }, 159 | { 160 | klass: lowComparison(quarter, averages, "average"), 161 | text: convertBg(quarter.average) 162 | }, 163 | { 164 | klass: upperQuartileEvaluation(quarter, averages), 165 | text: convertBg(quarter.upperQuartile) 166 | } 167 | ].map(function(v) { 168 | if (typeof v == "object") { 169 | return ""; 170 | } else { 171 | return ""; 172 | } 173 | }).join("") + ""; 174 | } 175 | catch (e) { 176 | console.log(e); 177 | } 178 | }).join("") + ""); 179 | table.appendTo(grid); 180 | $(".print").click(function(e) { 181 | e.preventDefault(); 182 | window.print(); 183 | }); 184 | }); -------------------------------------------------------------------------------- /app/receiver.js: -------------------------------------------------------------------------------- 1 | require(["/app/config.js!"], function(config) { 2 | function putTheChartOnThePage(remotecgmuri) { 3 | $("#receiverui").html(""); 4 | if (typeof remotecgmuri == "string" && remotecgmuri.length > 0) { 5 | if (remotecgmuri.indexOf("://") == -1) { 6 | remotecgmuri = "http://" + remotecgmuri; 7 | } 8 | // load remote 9 | console.log("[app.js putTheChartOnThePage] Using remote CGM monitor"); 10 | $("#receiverui").append($("
").append($("").attr({ 11 | src: remotecgmuri 12 | }))); 13 | } else { 14 | // load hosted 15 | console.log("[app.js putTheChartOnThePage] Using built-in chart"); 16 | $("#receiverui").load('receiver.html', launchReceiverUI); 17 | } 18 | } 19 | 20 | config.on("remotecgmuri", putTheChartOnThePage); 21 | 22 | $(function() { 23 | putTheChartOnThePage(config.remotecgmuri); 24 | }); 25 | }); 26 | 27 | function launchReceiverUI() { 28 | 29 | require(["bloodsugar", "/app/config.js!", "store/egv_records"], function(convertBg, config, egvrecords) { 30 | var jqShow = $.fn.show; 31 | $.fn.show = function(domid) { 32 | var o = jqShow.apply(this, [domid]); 33 | if (this.selector === "#receiverui") { 34 | window.requestAnimationFrame(firstLoad); 35 | } 36 | return o; 37 | } 38 | 39 | var currData = null; 40 | $("#dexcomtrend").bind("plothover", function (event, pos, item) { 41 | if (item != null) { 42 | if ((currData == null) || currData[0] != item.datapoint[0] || currData[1] != item.datapoint[1]) { 43 | currData = item.datapoint; 44 | $("#hover").remove(); 45 | var date = new Date(item.datapoint[0]); 46 | hover(item.pageX, item.pageY, '' + date.format("D n/j H:i") + '- ' + item.datapoint[1]); 47 | } 48 | } else { 49 | $("#hover").remove(); 50 | currData = null; 51 | } 52 | }); 53 | 54 | function hover(x, y, contents) { 55 | //Adrian: Had to use workaround with container as maximum opacity is inherited from parent. 56 | //Make text opaque and background transparent. 57 | var hovercontainer = jQuery('
').css({ 58 | position: 'absolute', 59 | top: y + 8, 60 | left: x + 8 61 | }); 62 | 63 | var hovertext = jQuery('
' + contents + '
').css( { 64 | position: 'relative', 65 | top: 0, 66 | left: 0, 67 | width: '100%', 68 | height: '100%', 69 | padding: '2px', 70 | 'text-align': 'center', 71 | 'font-size': '120%', 72 | 'z-index': 2, 73 | opacity: 1 74 | }); 75 | 76 | var hoverbg = jQuery('
').css( { 77 | 'background-color': '#fff', 78 | position: 'absolute', 79 | top: 0, 80 | left: 0, 81 | width: '100%', 82 | height: '100%', 83 | border: '2px outset #fff', 84 | 'z-index': 1, 85 | opacity: .75 86 | }); 87 | hovercontainer.append(hovertext); 88 | hovercontainer.append(hoverbg); 89 | hovercontainer.appendTo("body").fadeIn(200); 90 | } 91 | 92 | function drawReceiverChart(data) { 93 | var low = config.targetrange.low, high = config.targetrange.high, time = config.trenddisplaytime; 94 | var t = time; 95 | var now = (new Date()).getTime(); 96 | var trend = data.map(function(plot) { 97 | return [ 98 | +plot.displayTime, 99 | parseFloat(convertBg(plot.bgValue)) 100 | ]; 101 | }).filter(function(plot) { 102 | return plot[0] + t.hours() > now && plot[0] < Date.now(); 103 | }); 104 | 105 | high = parseFloat(convertBg(high)); 106 | low = parseFloat(convertBg(low)); 107 | 108 | var trendIn = trend.filter(function(plot){ 109 | return plot[1]<=high && plot[1]>=low; 110 | }); 111 | var trendHigh = trend.filter(function(plot){ 112 | return plot[1]>high; 113 | }); 114 | var trendLow = trend.filter(function(plot){ 115 | return plot[1]24){ 125 | ticksz = [1, "day"]; 126 | timeformat = "%m/%d" 127 | } 128 | 129 | $.plot( 130 | "#dexcomtrend", 131 | [ 132 | { 133 | data: trendIn, 134 | color: "#00FF00", 135 | points: { 136 | show: true 137 | }, 138 | lines: { 139 | show: false 140 | } 141 | }, 142 | { 143 | data: trendHigh, 144 | color: "#FFFF00", 145 | points: { 146 | show: true, 147 | fill: true, 148 | fillColor: "#FFDD00" 149 | }, 150 | lines: { 151 | show: false 152 | } 153 | }, 154 | { 155 | data: trendLow, 156 | color: "#FF0000", 157 | points: { 158 | show: true 159 | }, 160 | lines: { 161 | show: false 162 | } 163 | } 164 | ], 165 | { 166 | xaxis: { 167 | mode: "time", 168 | timezone: "browser", 169 | timeformat: timeformat, 170 | minTickSize: ticksz, 171 | tickColor: "#555", 172 | }, 173 | yaxis: { 174 | min: 0, 175 | max: convertBg(400), 176 | tickColor: "#555", 177 | }, 178 | grid: { 179 | markings: [ 180 | { 181 | color: '#FF0000', 182 | lineWidth: 2, 183 | yaxis: { 184 | from: low, 185 | to: low 186 | } 187 | }, 188 | { 189 | color: '#FFFF00', 190 | lineWidth: 2, 191 | yaxis: { 192 | from: high, 193 | to: high 194 | } 195 | } 196 | ], 197 | hoverable: true 198 | } 199 | } 200 | ); 201 | if (data.length) { 202 | $("#cgmnow").text(convertBg(data[data.length - 1].bgValue)); 203 | $("#cgmdirection").text(data[data.length - 1].trend); 204 | $("#cgmtime").text((new Date(data[data.length - 1].displayTime)).format("h:ia")); 205 | } 206 | } 207 | 208 | // updated database 209 | egvrecords.onChange(function(new_r, all) { 210 | drawReceiverChart(all); 211 | }); 212 | config.on("trenddisplaytime", function() { 213 | drawReceiverChart(egvrecords); 214 | }); 215 | 216 | config.on("targetrange", function() { 217 | drawReceiverChart(egvrecords); 218 | }); 219 | 220 | $(function() { 221 | //Adrian: Timeframe(ZOOM)-handlers: 222 | $("[data-hours]").click(function() { 223 | config.set("trenddisplaytime", parseInt($(this).attr("data-hours"), 10)); 224 | }); 225 | }); 226 | 227 | // first load, before receiver's returned data 228 | var firstLoad = function() { // called in overriden $.fn.show above 229 | drawReceiverChart(egvrecords); 230 | }; 231 | 232 | $(".dropdown-toggle").dropdown(); 233 | }); 234 | 235 | } -------------------------------------------------------------------------------- /app/options.js: -------------------------------------------------------------------------------- 1 | require(["feature/mongolab.js"], function(mongolab) { 2 | function getValue(param, options) { 3 | var parts = param.split("."); 4 | var key = parts.shift(); 5 | if (parts.length > 0) { 6 | return getValue(parts.join("."), options[key]); 7 | } else { 8 | return (typeof options == "object" && key in options)? options[key]: ""; 9 | } 10 | } 11 | 12 | $("#optionsui input,#optionsui select").map(function(ix) { 13 | $(this).val(getValue(this.name, config)); 14 | }); 15 | 16 | $("#optionsui").on("click", "#savesettings", function(){ 17 | var newConfig = $("#optionsui input, #optionsui select").toArray().reduce(function(out, field) { 18 | var parts = field.name.split("."); 19 | var key = parts.shift(); 20 | var working = out; 21 | while (parts.length > 0) { 22 | if (!(key in working)) { 23 | working[key] = {}; 24 | } 25 | working = working[key]; 26 | key = parts.shift(); 27 | } 28 | working[key] = field.value; 29 | return out; 30 | }, {}); 31 | Object.keys(newConfig).forEach(function(key) { 32 | config.set(key,newConfig[key]); 33 | }); 34 | 35 | window.close(); 36 | }); 37 | $("#optionsui").on("click", "#resetchanged", function(){ 38 | window.close(); 39 | }); 40 | 41 | $(document).on("click", "#testconnection", function(){ 42 | var config = $("#optionsdatabase input").toArray().reduce(function(out, field) { 43 | out[field.name] = field.value; 44 | return out; 45 | }, {}); 46 | var worker = function() { }; 47 | var applyChoice = function(notification_id, button) { 48 | worker.apply(this,arguments); 49 | }; 50 | chrome.notifications.onButtonClicked.removeListener(applyChoice); 51 | mongolab.testConnection(config["mongolab.apikey"], config["mongolab.database"], config["mongolab.collection"]).then(function ok() { 52 | console.log("[mongolab] connection check ok"); 53 | chrome.notifications.create("", { 54 | type: "basic", 55 | title: "NightScout.info CGM Utility", 56 | message: "This mongolab configuration checks out ok", 57 | iconUrl: "/public/assets/icon.png" 58 | }, function(chrome_notification_id) { }); 59 | }, function fail(error) { 60 | console.log("[mongolab] " + error.error, error.avlb); 61 | if (error.type == "database") { 62 | chrome.notifications.create("", { 63 | type: (error.avlb.length > 0? "list": "basic"), 64 | title: error.error + ": " + error.selected, 65 | message: "The " + error.type + " was not correct", 66 | iconUrl: "/public/assets/icon.png", 67 | buttons: (error.avlb.length > 0 && error.avlb.length <= 2)? error.avlb.map(function(choice) { 68 | return { title: "Use " + choice }; 69 | }) : undefined, 70 | items: error.avlb.map(function(option) { 71 | return { 72 | title: option, 73 | message: error.type 74 | }; 75 | }) 76 | }, function(chrome_notification_id) { 77 | worker = function(notification_id, button) { 78 | if (notification_id == chrome_notification_id) { 79 | var selection = error.avlb[button]; 80 | var fields = { 81 | database: "#options-database-name", 82 | collection: "#options-database-collection", 83 | apikey: "#options-database-apiuser" 84 | }; 85 | $(fields[error.type]).val(selection); 86 | } 87 | chrome.notifications.onButtonClicked.removeListener(applyChoice); 88 | }; 89 | chrome.notifications.onButtonClicked.addListener(applyChoice); 90 | }); 91 | } else if (error.type == "collection") { 92 | if (error.avlb.length > 0) { 93 | var choices = [{ 94 | title: "Keep " + error.selected + " (creates new collection)", 95 | selection: error.selected 96 | }].concat(error.avlb.filter(function(option) { 97 | return ["devicestatus", "profile", "treatments"].indexOf(option) == -1; 98 | }).map(function(choice) { 99 | return { title: "Use " + choice, selection: choice }; 100 | })).filter(function(option, ix) { 101 | if (ix == 0) { 102 | return error.selected.length > 0; 103 | } else if (ix == 1) { 104 | return true; 105 | } else if (ix == 2) { 106 | return error.selected.length == 0; 107 | } else { 108 | return false; 109 | } 110 | }); 111 | chrome.notifications.create("", { 112 | type: "list", 113 | iconUrl: "/public/assets/icon.png", 114 | title: "This collection was not found", 115 | message: "Possible collections", 116 | items: [{ 117 | title: "The indicated collection (" + error.selected + ") was not found.", 118 | message: "Suggested resolutions:" 119 | }], 120 | buttons: choices.map(function(choice) { 121 | return { title: choice.title }; 122 | }) 123 | }, function(chrome_notification_id) { 124 | worker = function(notification_id, button) { 125 | console.log(button); 126 | if (notification_id == chrome_notification_id && button > 0) { 127 | var selection = choices[button].selection; 128 | var fields = { 129 | database: "#options-database-name", 130 | collection: "#options-database-collection", 131 | apikey: "#options-database-apiuser" 132 | }; 133 | $(fields[error.type]).val(selection); 134 | } 135 | chrome.notifications.onButtonClicked.removeListener(applyChoice); 136 | }; 137 | chrome.notifications.onButtonClicked.addListener(applyChoice); 138 | }); 139 | } else { 140 | console.log("[options.js testConnection] collection name not found but it will be automatically made"); 141 | } 142 | } else { 143 | chrome.notifications.create("", { 144 | type: error.avlb.length > 0? "list": "basic", 145 | title: error.error + ": " + error.selected, 146 | message: "The " + error.type + " was not correct", 147 | iconUrl: "/public/assets/icon.png", 148 | buttons: (error.avlb.length > 0 && error.avlb.length <= 2)? error.avlb.map(function(choice) { 149 | return { title: "Use " + choice }; 150 | }) : undefined, 151 | items: error.avlb.map(function(option) { 152 | return { 153 | title: option, 154 | message: error.type 155 | }; 156 | }) 157 | }, function(chrome_notification_id) { 158 | worker = function(notification_id, button) { 159 | if (notification_id == chrome_notification_id) { 160 | var selection = error.avlb[button]; 161 | var fields = { 162 | database: "#options-database-name", 163 | collection: "#options-database-collection", 164 | apikey: "#options-database-apiuser" 165 | }; 166 | $(fields[error.type]).val(selection); 167 | } 168 | chrome.notifications.onButtonClicked.removeListener(applyChoice); 169 | }; 170 | chrome.notifications.onButtonClicked.addListener(applyChoice); 171 | }); 172 | } 173 | }); 174 | }); 175 | }); -------------------------------------------------------------------------------- /lib/bootstrap-confirmation.js: -------------------------------------------------------------------------------- 1 | /// https://github.com/Tavicu/bootstrap-confirmation 2 | +function ($) { 3 | 'use strict'; 4 | 5 | //var for check event at body can have only one. 6 | var event_body = false; 7 | 8 | // CONFIRMATION PUBLIC CLASS DEFINITION 9 | // =============================== 10 | var Confirmation = function (element, options) { 11 | var that = this; 12 | 13 | this.init('confirmation', element, options); 14 | 15 | 16 | $(element).on('show.bs.confirmation', function(e) { 17 | that.options.onShow(e, this); 18 | 19 | $(this).addClass('open'); 20 | 21 | var options = that.options; 22 | var all = options.all_selector; 23 | 24 | if(options.singleton) { 25 | $(all+'.in').not(that.$element).confirmation('hide'); 26 | } 27 | }); 28 | 29 | $(element).on('hide.bs.confirmation', function(e) { 30 | that.options.onHide(e, this); 31 | 32 | $(this).removeClass('open'); 33 | }); 34 | 35 | $(element).on('shown.bs.confirmation', function(e) { 36 | var options = that.options; 37 | var all = options.all_selector; 38 | 39 | that.$element.on('click.dismiss.bs.confirmation', '[data-dismiss="confirmation"]', $.proxy(that.hide, that)); 40 | 41 | if(that.isPopout()) { 42 | if(!event_body) { 43 | event_body = $('body').on('click', function (e) { 44 | if(that.$element.is(e.target)) return; 45 | if(that.$element.has(e.target).length) return; 46 | if($('.popover').has(e.target).length) return; 47 | 48 | that.$element.confirmation('hide'); 49 | 50 | $('body').unbind(e); 51 | 52 | event_body = false; 53 | 54 | return; 55 | }); 56 | } 57 | } 58 | }); 59 | 60 | $(element).on('click', function(e) { 61 | e.preventDefault(); 62 | }); 63 | } 64 | 65 | if (!$.fn.popover || !$.fn.tooltip) throw new Error('Confirmation requires popover.js and tooltip.js'); 66 | 67 | Confirmation.DEFAULTS = $.extend({}, $.fn.popover.Constructor.DEFAULTS, { 68 | placement : 'right', 69 | title : 'Are you sure?', 70 | btnOkClass : 'btn btn-sm btn-danger', 71 | btnOkLabel : 'Delete', 72 | btnOkIcon : 'glyphicon glyphicon-ok', 73 | btnCancelClass : 'btn btn-sm btn-default', 74 | btnCancelLabel : 'Cancel', 75 | btnCancelIcon : 'glyphicon glyphicon-remove', 76 | href : '#', 77 | target : '_self', 78 | singleton : true, 79 | popout : true, 80 | onShow : function(event, element){}, 81 | onHide : function(event, element){}, 82 | onConfirm : function(event, element){}, 83 | onCancel : function(event, element){}, 84 | template : '
' 85 | + '

' 86 | + '
' 87 | + 'Yes' 88 | + ' No' 89 | + '
' 90 | + '
' 91 | }); 92 | 93 | 94 | // NOTE: CONFIRMATION EXTENDS popover.js 95 | // ================================ 96 | Confirmation.prototype = $.extend({}, $.fn.popover.Constructor.prototype); 97 | 98 | Confirmation.prototype.constructor = Confirmation; 99 | 100 | Confirmation.prototype.getDefaults = function () { 101 | return Confirmation.DEFAULTS; 102 | } 103 | 104 | Confirmation.prototype.setContent = function () { 105 | var that = this; 106 | var $tip = this.tip(); 107 | var title = this.getTitle(); 108 | var $btnOk = $tip.find('[data-apply="confirmation"]'); 109 | var $btnCancel = $tip.find('[data-dismiss="confirmation"]'); 110 | var options = this.options 111 | 112 | $btnOk.addClass(this.getBtnOkClass()) 113 | .html(this.getBtnOkLabel()) 114 | .prepend($('').addClass(this.getBtnOkIcon()), " ") 115 | .attr('href', this.getHref()) 116 | .attr('target', this.getTarget()) 117 | .off('click').on('click', function(event) { 118 | options.onConfirm(event, that.$element); 119 | 120 | that.$element.confirmation('hide'); 121 | }); 122 | 123 | $btnCancel.addClass(this.getBtnCancelClass()) 124 | .html(this.getBtnCancelLabel()) 125 | .prepend($('').addClass(this.getBtnCancelIcon()), " ") 126 | .off('click').on('click', function(event){ 127 | options.onCancel(event, that.$element); 128 | 129 | that.$element.confirmation('hide'); 130 | }); 131 | 132 | $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title); 133 | 134 | $tip.removeClass('fade top bottom left right in'); 135 | 136 | // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do 137 | // this manually by checking the contents. 138 | if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide(); 139 | } 140 | 141 | Confirmation.prototype.getBtnOkClass = function () { 142 | var $e = this.$element; 143 | var o = this.options; 144 | 145 | return $e.attr('data-btnOkClass') || (typeof o.btnOkClass == 'function' ? o.btnOkClass.call($e[0]) : o.btnOkClass); 146 | } 147 | 148 | Confirmation.prototype.getBtnOkLabel = function () { 149 | var $e = this.$element; 150 | var o = this.options; 151 | 152 | return $e.attr('data-btnOkLabel') || (typeof o.btnOkLabel == 'function' ? o.btnOkLabel.call($e[0]) : o.btnOkLabel); 153 | } 154 | 155 | Confirmation.prototype.getBtnOkIcon = function () { 156 | var $e = this.$element; 157 | var o = this.options; 158 | 159 | return $e.attr('data-btnOkIcon') || (typeof o.btnOkIcon == 'function' ? o.btnOkIcon.call($e[0]) : o.btnOkIcon); 160 | } 161 | 162 | Confirmation.prototype.getBtnCancelClass = function () { 163 | var $e = this.$element; 164 | var o = this.options; 165 | 166 | return $e.attr('data-btnCancelClass') || (typeof o.btnCancelClass == 'function' ? o.btnCancelClass.call($e[0]) : o.btnCancelClass); 167 | } 168 | 169 | Confirmation.prototype.getBtnCancelLabel = function () { 170 | var $e = this.$element; 171 | var o = this.options; 172 | 173 | return $e.attr('data-btnCancelLabel') || (typeof o.btnCancelLabel == 'function' ? o.btnCancelLabel.call($e[0]) : o.btnCancelLabel); 174 | } 175 | 176 | Confirmation.prototype.getBtnCancelIcon = function () { 177 | var $e = this.$element; 178 | var o = this.options; 179 | 180 | return $e.attr('data-btnCancelIcon') || (typeof o.btnCancelIcon == 'function' ? o.btnCancelIcon.call($e[0]) : o.btnCancelIcon); 181 | } 182 | 183 | Confirmation.prototype.getHref = function () { 184 | var $e = this.$element; 185 | var o = this.options; 186 | 187 | return $e.attr('data-href') || (typeof o.href == 'function' ? o.href.call($e[0]) : o.href); 188 | } 189 | 190 | Confirmation.prototype.getTarget = function () { 191 | var $e = this.$element; 192 | var o = this.options; 193 | 194 | return $e.attr('data-target') || (typeof o.target == 'function' ? o.target.call($e[0]) : o.target); 195 | } 196 | 197 | Confirmation.prototype.isPopout = function () { 198 | var popout; 199 | var $e = this.$element; 200 | var o = this.options; 201 | 202 | popout = $e.attr('data-popout') || (typeof o.popout == 'function' ? o.popout.call($e[0]) : o.popout); 203 | 204 | if(popout == 'false') popout = false; 205 | 206 | return popout 207 | } 208 | 209 | 210 | // CONFIRMATION PLUGIN DEFINITION 211 | // ========================= 212 | var old = $.fn.confirmation; 213 | 214 | $.fn.confirmation = function (option) { 215 | var that = this; 216 | 217 | return this.each(function () { 218 | var $this = $(this); 219 | var data = $this.data('bs.confirmation'); 220 | var options = typeof option == 'object' && option; 221 | 222 | options = options || {}; 223 | options.all_selector = that.selector; 224 | 225 | if (!data && option == 'destroy') return; 226 | if (!data) $this.data('bs.confirmation', (data = new Confirmation(this, options))); 227 | if (typeof option == 'string') data[option](); 228 | }); 229 | } 230 | 231 | $.fn.confirmation.Constructor = Confirmation 232 | 233 | 234 | // CONFIRMATION NO CONFLICT 235 | // =================== 236 | $.fn.confirmation.noConflict = function () { 237 | $.fn.confirmation = old; 238 | 239 | return this; 240 | } 241 | }(jQuery); -------------------------------------------------------------------------------- /app/app.js: -------------------------------------------------------------------------------- 1 | require(["feature/cgm_download", "feature/mongolab", "feature/trending_alerts", "waiting", "store/egv_records", "/app/config.js!", "blinken_lights", "console"], function(cgm, mongolab, alerts, waiting, egvrecords, config, blinkenLights, console) { 2 | 3 | // OS Flags 4 | // Windows needs a different COM port than everything else because Windows. 5 | // I don't have an older version of OSX to troubleshoot this against 6 | var isWindows = !!~window.navigator.appVersion.indexOf("Win"); 7 | var isMac = !!~window.navigator.appVersion.indexOf("Mac OS X"); 8 | var macVersion; 9 | if (isMac) { 10 | var identifier = "Mac OS X"; 11 | var ixVersion = window.navigator.appVersion.indexOf(identifier) + identifier.length; 12 | if (ixVersion > identifier.length) { 13 | var v = window.navigator.appVersion.indexOf(")", ixVersion); 14 | identifier = window.navigator.appVersion.substring(ixVersion, v).trim().split("_").map(function(r) { return parseInt(r, 10); }); 15 | 16 | const MAJOR = 0, MINOR = 1, BUGFIX = 2; 17 | if (identifier[MAJOR] == 10 && identifier[MINOR] >= 7 && identifier[MINOR] <= 10) { 18 | // ok 19 | } else if (identifier[MAJOR] == 10 && identifier[MINOR] > 10) { 20 | // probably ok 21 | } else if (identifier[MAJOR] > 10) { 22 | // *shrugs* 23 | setTimeout(waiting.show("You're on a much newer version of OSX than this has been tested against. Please provide feedback on what happens."), (10).seconds()); 24 | } else { 25 | // fail 26 | setTimeout(waiting.show("You're on an old version of OSX and this is unlikely to work."), (10).seconds()); 27 | } 28 | } 29 | } 30 | 31 | $(function() { 32 | $.ajax("https://twitter.com/cgmtools4chrome").then(function(page) { 33 | var tweets = $(".js-tweet-text", page.replace(//g, "").replace(//g, "")); 34 | var important = tweets.filter(function(b) { return this.innerText.indexOf("#update") > -1 }); 35 | if (important.length > 0) { 36 | var mostRecent = important.map(function() { return this.innerText.replace(" #update", ""); })[0]; 37 | if (mostRecent.indexOf("http") > -1) { 38 | var linkStart = mostRecent.indexOf("http"); 39 | if (linkStart > -1) { 40 | var endsAt = mostRecent.indexOf(" ", linkStart); 41 | if (endsAt > -1) { 42 | endsAt -= linkStart; 43 | } else { 44 | endsAt = mostRecent.length - endsAt; 45 | } 46 | mostRecent = mostRecent.substr(0, linkStart) + '' + mostRecent.substr(linkStart, endsAt) + "" + mostRecent.substr(linkStart + endsAt); 47 | } 48 | } 49 | $("#updateText").html(mostRecent); 50 | } 51 | }) 52 | // event handlers 53 | $("#disclaimer").modal(); 54 | $("#disclaimer").show(); 55 | $("#acknowledge-agree").click(function() { 56 | $("#disclaimer.modal").modal('hide'); 57 | $("#receiverui").show(); 58 | }); 59 | $("#acknowledge-disagree").click(function() { 60 | window.close(); 61 | }); 62 | $("#openhelp").click(function(e) { 63 | chrome.app.window.create('app/help.html', { 64 | id: "help", 65 | bounds: { 66 | width: 800, 67 | height: 600 68 | } 69 | }); 70 | e.preventDefault(); 71 | }); 72 | 73 | $("#backfilldatabase").click(function() { 74 | mongolab.publish(egvrecords).then(function() { 75 | chrome.notifications.create("", { 76 | type: "basic", 77 | title: "NightScout.info CGM Utility", 78 | message: "Published " + local.egvrecords.length + " records to MongoLab", 79 | iconUrl: "/public/assets/icon.png", 80 | }, function(notification_id) { 81 | }); 82 | console.log("[app.js publishtomongolab] publish complete, %i records", local.egvrecords.length); 83 | }); 84 | }); 85 | 86 | $('#reset').confirmation({ 87 | title: "Are you sure? This will delete all your local data and cannot be undone.", 88 | onConfirm: egvrecords.removeAll 89 | }); 90 | 91 | $(".downloadallfromdexcom").click(cgm.getAllRecords); 92 | 93 | $("#fixit").click(function() { 94 | $("#errorrreporting").modal(); 95 | $("#errorrreporting").show(); 96 | $("#whatswrong").val(""); 97 | }); 98 | 99 | $('.dropdown-toggle').dropdown(); 100 | $("a.new_window").click(function() { 101 | chrome.app.window.create($(this).attr("href"), { 102 | id: this.href.replace(/[\/\.:]/g, ""), 103 | bounds: { 104 | width: parseInt($(this).attr("data-width"), 10), 105 | height: parseInt($(this).attr("data-height"), 10) 106 | } 107 | }, function(w) { 108 | w.contentWindow.console = console; 109 | }); 110 | return false; 111 | }); 112 | $("a#options").click(function() { 113 | chrome.app.window.create($(this).attr("href"), { 114 | id: this.href.replace(/[\/\.:]/g, ""), 115 | bounds: { 116 | width: parseInt($(this).attr("data-width"), 10), 117 | height: parseInt($(this).attr("data-height"), 10) 118 | } 119 | }, function(w) { 120 | w.contentWindow.console = console; 121 | w.contentWindow.config = config; 122 | }); 123 | return false; 124 | }); 125 | $("#pulldatabase").click(function() { 126 | mongolab.populateLocalStorage().then(function(r, ml) { 127 | chrome.notifications.create("", { 128 | type: "basic", 129 | title: "NightScout.info CGM Utility", 130 | message: "Pulled " + r.raw_data.length + " records from MongoLab. You might have already had some, and any duplicates were discarded.", 131 | iconUrl: "/public/assets/icon.png" 132 | }, function(chrome_notification_id) { }); 133 | }); 134 | }); 135 | $("#errorreporting-agree").click(function(){ 136 | var github = "https://api.github.com"; 137 | // console.debug(config); 138 | $.ajax({ 139 | url: github + "/gists", 140 | accept: "application/vnd.github.v3+json", 141 | dataType: "json", 142 | data: JSON.stringify({ 143 | "description": $("#whatswrong").val() || "Console details", 144 | "public": false, 145 | "files": { 146 | "console": { 147 | "content":console.fixMyStuff() 148 | } 149 | } 150 | }), 151 | type: "POST", 152 | contentType: "application/json" 153 | }).then(function(r) { 154 | $("#errorrreporting").modal('hide'); 155 | window.open("https://twitter.com/intent/tweet?text=" + encodeURIComponent("@cgmtools4chrome I have a problem with Nightscout CGM Uploader") + "&url=" + encodeURIComponent(r.html_url)) 156 | }); 157 | }) 158 | $("#errorreporting-disagree").click(function() { 159 | $("#errorrreporting").modal('hide'); 160 | }); 161 | $("#export").click(function() { 162 | Promise.all([ 163 | new Promise(function(done) { 164 | chrome.fileSystem.chooseEntry({ 165 | type: 'saveFile', 166 | suggestedName: "blood sugars.csv" 167 | }, function(writableFileEntry) { 168 | writableFileEntry.createWriter(done); 169 | }); 170 | }), 171 | new Promise(function(done) { 172 | require(["./bloodsugar"], done); 173 | }) 174 | ]).then(function(params) { 175 | var writer = params[0], 176 | convertBg = params[1]; 177 | writer.write(new Blob( 178 | egvrecords.map(function(record) { 179 | return [ 180 | (new Date(record.displayTime)).format("M j Y H:i"), 181 | convertBg(record.bgValue), 182 | record.trend 183 | ].join(",") + "\n"; 184 | }), { 185 | type: 'text/plain' 186 | } 187 | )); 188 | }) 189 | }); 190 | 191 | blinkenLights.on("output", (function() { 192 | var to = false; 193 | var tx = $("#tx"); 194 | var txLabel = tx.next(); 195 | tx.css("background-color", "#040"); 196 | txLabel.css("color", "#666"); 197 | return function() { 198 | tx.css("background-color", "#0f0"); 199 | txLabel.css("color", "#aaa"); 200 | if (to) clearTimeout(to); 201 | to = setTimeout(function() { 202 | tx.css("background-color", "#040"); 203 | txLabel.css("color", "#666"); 204 | }, 300); 205 | }; 206 | }).call()); 207 | 208 | blinkenLights.on("input", (function() { 209 | var to = false; 210 | var rx = $("#rx"); 211 | var rxLabel = rx.next(); 212 | rx.css("background-color", "#400"); 213 | rxLabel.css("color", "#666"); 214 | return function(a) { 215 | if (a[0].length == 2) return; 216 | rx.css("background-color", "#f00"); 217 | rxLabel.css("color", "#aaa"); 218 | if (to) clearTimeout(to); 219 | to = setTimeout(function() { 220 | rx.css("background-color", "#400"); 221 | rxLabel.css("color", "#666"); 222 | }, 500); 223 | }; 224 | }).call()); 225 | }); 226 | 227 | }); 228 | -------------------------------------------------------------------------------- /app/feature/mongolab.js: -------------------------------------------------------------------------------- 1 | define(["../waiting", "../store/egv_records", "/app/config.js!"], function(waiting, egvrecords, config) { 2 | var mongolabUrl = "https://api.mongolab.com/api/1/databases/"; 3 | 4 | var mongolab = { }; 5 | 6 | navigator.getBattery().then(function(battery) { 7 | var update = function() { 8 | console.debug("[Mongolab] Setting battery to %i in Mongolab", battery.level * 100) 9 | $.ajax({ 10 | url: mongolabUrl + config.mongolab.database + "/collections/devicestatus?apiKey=" + config.mongolab.apikey + "&u=true&q={\"id\":\"config\"}", 11 | data: JSON.stringify({ 12 | "$set": { 13 | uploaderBattery: battery.level * 100 14 | } 15 | }), 16 | type: "PUT", 17 | contentType: "application/json" 18 | }); 19 | } 20 | if (config.mongolab && config.mongolab.apikey) { 21 | update(); 22 | battery.addEventListener('levelchange', update); 23 | } 24 | }); 25 | 26 | // http://stackoverflow.com/a/8462701 27 | function formatFloat(num,casasDec,sepDecimal,sepMilhar) { 28 | if (num < 0) 29 | { 30 | num = -num; 31 | sinal = -1; 32 | } else 33 | sinal = 1; 34 | var resposta = ""; 35 | var part = ""; 36 | if (num != Math.floor(num)) // decimal values present 37 | { 38 | part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded) 39 | while (part.length < casasDec) 40 | part = '0'+part; 41 | if (casasDec > 0) 42 | { 43 | resposta = sepDecimal+part; 44 | num = Math.floor(num); 45 | } else 46 | num = Math.round(num); 47 | } // end of decimal part 48 | while (num > 0) // integer part 49 | { 50 | part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits 51 | num = Math.floor(num/1000); 52 | if (num > 0) 53 | while (part.length < 3) // 123.023.123 if sepMilhar = '.' 54 | part = '0'+part; // 023 55 | resposta = part+resposta; 56 | if (num > 0) 57 | resposta = sepMilhar+resposta; 58 | } 59 | if (sinal < 0) 60 | resposta = '-'+resposta; 61 | return resposta; 62 | } 63 | 64 | var formatDate = function(d) { 65 | return (d.getFullYear()) + "/" + (d.getMonth() + 1) + "/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes(); 66 | }; 67 | 68 | var structureData = function(plot) { 69 | return { 70 | device: "dexcom", 71 | date: plot.displayTime, 72 | dateString: (new Date(plot.displayTime)).format("c"), 73 | sgv: formatFloat(plot.bgValue, 2, "."), 74 | direction: plot.trend, 75 | type: "sgv" 76 | }; 77 | }; 78 | 79 | var formatData = function(plot) { 80 | return JSON.stringify(structureData(plot)); 81 | }; 82 | mongolab.insert = function(plot) { 83 | if (!plot) return; 84 | 85 | // have a unique constraint on date to keep it from inserting too much data. 86 | // mongolab returns a 400 when duplicate attempted 87 | 88 | if (!("mongolab" in config)) return; 89 | if (!("apikey" in config.mongolab && config.mongolab.apikey.length > 0)) return; 90 | if (!("collection" in config.mongolab && config.mongolab.collection.length > 0)) return; 91 | if (!("database" in config.mongolab && config.mongolab.database.length > 0)) return; 92 | 93 | console.log("[mongolab.js insert] Writing record to MongoLab %o", plot); 94 | 95 | $.ajax({ 96 | url: mongolabUrl + config.mongolab.database + "/collections/" + config.mongolab.collection + "?apiKey=" + config.mongolab.apikey, 97 | data: formatData(plot), 98 | type: "POST", 99 | contentType: "application/json" 100 | }); 101 | }; 102 | 103 | mongolab.populateLocalStorage = function() { // (download from mongolab) 104 | waiting.show("Downloading from Mongolab"); 105 | return new Promise(function(complete) { 106 | // have a unique constraint on date to keep it from inserting too much data. 107 | // mongolab returns a 400 when duplicate attempted 108 | 109 | console.log("[mongolab] Requesting all data from MongoLab"); 110 | if (!("mongolab" in config)) return; 111 | if (!("apikey" in config.mongolab && config.mongolab.apikey.length > 0)) return; 112 | if (!("collection" in config.mongolab && config.mongolab.collection.length > 0)) return; 113 | if (!("database" in config.mongolab && config.mongolab.database.length > 0)) return; 114 | 115 | // get count (can't transfer more than 1000 at a time) 116 | $.getJSON(mongolabUrl + config.mongolab.database + "/collections/" + config.mongolab.collection + "?c=true&apiKey=" + config.mongolab.apikey).then(function(total) { 117 | var requests = []; 118 | do { 119 | requests.push(mongolabUrl + config.mongolab.database + "/collections/" + config.mongolab.collection + "?apiKey=" + config.mongolab.apikey + "&l=1000&sk=" + 1000 * requests.length); 120 | total -= 1000; 121 | } while (total > 0); 122 | Promise.all(requests.map(function(url) { 123 | return $.getJSON(url); 124 | })).then(function() { 125 | var data = []; 126 | var args = Array.prototype.slice.call(arguments, 0); 127 | while (args.length) data = Array.prototype.concat.apply(data, args.shift()); 128 | var existing = egvrecords.map(function(egv_r) { 129 | return egv_r.displayDate; 130 | }); 131 | var records = data.filter(function(record) { 132 | if (Object.keys(record).indexOf("type") > -1) { 133 | return record.type == "sgv"; 134 | } else { 135 | return true; 136 | } 137 | }).map(function(record) { 138 | return { 139 | displayTime: Date.parse(record.dateString) || record.date, 140 | bgValue: parseInt(record.sgv), 141 | trend: record.direction, 142 | recordSource: "mongolab" 143 | }; 144 | }).filter(function(record){ 145 | return (existing.indexOf(record.displayTime) == -1); 146 | }).filter(function(record) { 147 | return record.displayTime < Date.now(); 148 | }).filter(function(rec, ix, all) { 149 | if (rec.bgValue <= 30) return false; 150 | if (ix == 0) return true; 151 | return all[ix - 1].displayTime != rec.displayTime; 152 | }); 153 | try { 154 | egvrecords.addAll(records); 155 | } catch (e) { 156 | console.log(e) 157 | } 158 | complete({ new_records: records, raw_data: data }); 159 | waiting.hide(); 160 | }); 161 | }); 162 | }); 163 | }; 164 | 165 | mongolab.publish = function(records) { // (backfill mongolab) 166 | var uxWaiting = function() { 167 | if (records.length > 1000) { 168 | waiting.show("Sending entire history to MongoLab"); 169 | return waiting.hide.bind(waiting); 170 | } else { 171 | return function() { }; 172 | } 173 | }; 174 | 175 | return (new Promise(function(complete) { 176 | // have a unique constraint on date to keep it from inserting too much data. 177 | // mongolab returns a 400 when duplicate attempted 178 | if (records.length == 0) return complete(); 179 | 180 | console.log("[mongolab] Publishing all data to MongoLab"); 181 | if (!("mongolab" in config)) return; 182 | if (!("apikey" in config.mongolab && config.mongolab.apikey.length > 0)) return; 183 | if (!("collection" in config.mongolab && config.mongolab.collection.length > 0)) return; 184 | if (!("database" in config.mongolab && config.mongolab.database.length > 0)) return; 185 | 186 | var record_sections = []; 187 | do { 188 | record_sections.push(records.slice(record_sections.length * 1000, (record_sections.length + 1) * 1000)); 189 | } while ((record_sections.length * 1000) < records.length); 190 | 191 | Promise.all(record_sections.map(function(records) { 192 | return $.ajax({ 193 | url: mongolabUrl + config.mongolab.database + "/collections/" + config.mongolab.collection + "?apiKey=" + config.mongolab.apikey, 194 | data: JSON.stringify(records.map(structureData)), 195 | type: "POST", 196 | contentType: "application/json" 197 | }); 198 | })).then(complete); 199 | })).then(uxWaiting()); 200 | }; 201 | 202 | mongolab.testConnection = function(apikey, databasename, collectionname) { 203 | return new Promise(function(ok, fail) { 204 | $.getJSON(mongolabUrl + "?apiKey=" + apikey).then(function(r) { 205 | // db ok 206 | if (r.filter(function(ml_db_name) { 207 | return ml_db_name == databasename; 208 | }).length > 0) { 209 | $.getJSON(mongolabUrl + databasename + "/collections?apiKey=" + apikey).then(function(r) { 210 | // db ok 211 | if (r.filter(function(ml_col_name) { 212 | return ml_col_name == collectionname; 213 | }).length > 0) { 214 | ok(); 215 | } else { 216 | fail({ error: "Bad collection name", type: "collection", avlb: r.filter(function(choice) { 217 | return choice.substr(0,7) !== "system."; 218 | }), selected: collectionname }); 219 | } 220 | }, function(r) { 221 | // db fail 222 | fail({ error: "Bad API Key", type: "apikey", avlb: [], selected: apikey }); 223 | }); 224 | } else { 225 | fail({ error: "Bad database name", type: "database", avlb: r, selected: databasename }); 226 | } 227 | }, function(r) { 228 | // db fail 229 | fail({ error: "Bad API Key", type: "apikey", avlb: [], selected: apikey }); 230 | }); 231 | }); 232 | }; 233 | 234 | // updated database 235 | egvrecords.onChange(function(new_r, all) { 236 | var datasource = "dexcom"; 237 | if ("datasource" in config) datasource = config.datasource || "dexcom"; 238 | if (datasource == "dexcom") { 239 | mongolab.publish(new_r.filter(function(egv) { 240 | return egv.recordSource != "mongolab"; 241 | })); 242 | } 243 | }); 244 | 245 | return mongolab; 246 | }); 247 | -------------------------------------------------------------------------------- /app/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NightScout.info CGM Utility 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 28 | 29 | 30 |
31 |
32 | 33 | 41 | 42 |
43 |
44 |
45 | Where would you like to pull data from? 46 |
47 | 48 |
49 | 50 | 51 |
52 | 56 |
57 |
58 | 59 |

If you use Android Uploader, pick Remote 60 | CGM and this will refresh from Mongolab. Pick Dexcom G4 if 61 | you'd rather plug in to this computer. Maybe one day 62 | Enlight will be here too.

63 | 64 | 65 |
66 |
67 | If you use Nightscout, you'll want data stored in Mongolab. 68 |
69 | 70 |
71 | 72 | 73 |
74 | 75 | 76 | 77 |

Find API key via Mongolab's documentation.

78 |
79 |
80 | 81 |
82 |
83 |
84 |
85 |
86 |

Testing the connection checks the vality of this API key (case sensitive) and then attempts to figure out database name and collection name.

87 |
88 |
89 | 90 |
91 | 92 | 93 |
94 | 95 |
96 |
97 | 98 |
99 | 100 | 101 |
102 | 103 |
104 |
105 | 106 |
107 | 108 | 109 |
110 | 111 | 112 |
113 | 114 |

Will replace simple graph with the Remote CGM Monitors (buys you projections and such).

115 |
116 |
117 | 118 | 119 | 139 | 140 |
141 |
142 | Dexcom always appears to use mg/dL underneath the covers but I'll attempt to show numbers using 143 | your units of choice, here. 144 |
145 |
146 | 147 | 148 |
149 | 153 |
154 |
155 |
156 | 157 | 158 |
159 |
160 |

Enter these numbers in mg/dL even if you have this 161 | configured to otherwise use mmo/L.

162 |

NOTE: If you entered a URI for Nightscout Remote CGM Monitor, these settings will not change the high/low configuration of that.

163 |
164 | 165 |
166 | 167 | 168 |
169 | 170 |
171 |
172 | 173 |
174 | 175 | 176 |
177 | 178 |
179 |
180 |
181 | 182 | 183 | 184 |
185 |
186 | You can get pop up alerts on your screen. 187 |
188 |
189 | 190 | 191 |
192 | 197 |
198 |
199 |
200 | 201 | 202 |
203 | 207 |
208 |
209 |
210 | 211 | 212 |
213 | 220 |
221 |
222 |
223 | 224 |
225 | 226 | 227 | 228 |
229 |
230 | 231 | 232 | 233 | -------------------------------------------------------------------------------- /app/time.js: -------------------------------------------------------------------------------- 1 | if (!("milliseconds" in Number.prototype)) 2 | Number.prototype.milliseconds = function() { return this; }; 3 | if (!("seconds" in Number.prototype)) 4 | Number.prototype.seconds = function() { return this.milliseconds() * 1000; }; 5 | if (!("minutes" in Number.prototype)) 6 | Number.prototype.minutes = function() { return this.seconds() * 60; }; 7 | if (!("hours" in Number.prototype)) 8 | Number.prototype.hours = function() { return this.minutes() * 60; }; 9 | if (!("days" in Number.prototype)) 10 | Number.prototype.days = function() { return this.hours() * 24; }; 11 | if (!("weeks" in Number.prototype)) 12 | Number.prototype.weeks = function() { return this.days() * 7; }; 13 | if (!("months" in Number.prototype)) 14 | Number.prototype.months = function() { return this.days() * 30; }; 15 | 16 | if (!("toDays" in Number.prototype)) 17 | Number.prototype.toDays = function() { return this.toHours() / 24; }; 18 | if (!("toHours" in Number.prototype)) 19 | Number.prototype.toHours = function() { return this.toMinutes() / 60; }; 20 | if (!("toMinutes" in Number.prototype)) 21 | Number.prototype.toMinutes = function() { return this.toSeconds() / 60; }; 22 | if (!("toSeconds" in Number.prototype)) 23 | Number.prototype.toSeconds = function() { return this.toMilliseconds() / 1000; }; 24 | if (!("toMilliseconds" in Number.prototype)) 25 | Number.prototype.toMilliseconds = function() { return this; }; 26 | 27 | Date.prototype.format = function(format) { 28 | // discuss at: http://phpjs.org/functions/date/ 29 | // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com) 30 | // original by: gettimeofday 31 | // parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html) 32 | // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 33 | // improved by: MeEtc (http://yass.meetcweb.com) 34 | // improved by: Brad Touesnard 35 | // improved by: Tim Wiel 36 | // improved by: Bryan Elliott 37 | // improved by: David Randall 38 | // improved by: Theriault 39 | // improved by: Theriault 40 | // improved by: Brett Zamir (http://brett-zamir.me) 41 | // improved by: Theriault 42 | // improved by: Thomas Beaucourt (http://www.webapp.fr) 43 | // improved by: JT 44 | // improved by: Theriault 45 | // improved by: Rafał Kukawski (http://blog.kukawski.pl) 46 | // improved by: Theriault 47 | // input by: Brett Zamir (http://brett-zamir.me) 48 | // input by: majak 49 | // input by: Alex 50 | // input by: Martin 51 | // input by: Alex Wilson 52 | // input by: Haravikk 53 | // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 54 | // bugfixed by: majak 55 | // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) 56 | // bugfixed by: Brett Zamir (http://brett-zamir.me) 57 | // bugfixed by: omid (http://phpjs.org/functions/380:380#comment_137122) 58 | // bugfixed by: Chris (http://www.devotis.nl/) 59 | // note: Uses global: php_js to store the default timezone 60 | // note: Although the function potentially allows timezone info (see notes), it currently does not set 61 | // note: per a timezone specified by date_default_timezone_set(). Implementers might use 62 | // note: this.php_js.currentTimezoneOffset and this.php_js.currentTimezoneDST set by that function 63 | // note: in order to adjust the dates in this function (or our other date functions!) accordingly 64 | // example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400); 65 | // returns 1: '09:09:40 m is month' 66 | // example 2: date('F j, Y, g:i a', 1062462400); 67 | // returns 2: 'September 2, 2003, 2:26 am' 68 | // example 3: date('Y W o', 1062462400); 69 | // returns 3: '2003 36 2003' 70 | // example 4: x = date('Y m d', (new Date()).getTime()/1000); 71 | // example 4: (x+'').length == 10 // 2009 01 09 72 | // returns 4: true 73 | // example 5: date('W', 1104534000); 74 | // returns 5: '53' 75 | // example 6: date('B t', 1104534000); 76 | // returns 6: '999 31' 77 | // example 7: date('W U', 1293750000.82); // 2010-12-31 78 | // returns 7: '52 1293750000' 79 | // example 8: date('W', 1293836400); // 2011-01-01 80 | // returns 8: '52' 81 | // example 9: date('W Y-m-d', 1293974054); // 2011-01-02 82 | // returns 9: '52 2011-01-02' 83 | 84 | var that = this, timestamp = this; 85 | var jsdate, f; 86 | // Keep this here (works, but for code commented-out below for file size reasons) 87 | // var tal= []; 88 | var txt_words = [ 89 | 'Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur', 90 | 'January', 'February', 'March', 'April', 'May', 'June', 91 | 'July', 'August', 'September', 'October', 'November', 'December' 92 | ]; 93 | // trailing backslash -> (dropped) 94 | // a backslash followed by any character (including backslash) -> the character 95 | // empty string -> empty string 96 | var formatChr = /\\?(.?)/gi; 97 | var formatChrCb = function(t, s) { 98 | return f[t] ? f[t]() : s; 99 | }; 100 | var _pad = function(n, c) { 101 | n = String(n); 102 | while (n.length < c) { 103 | n = '0' + n; 104 | } 105 | return n; 106 | }; 107 | f = { 108 | // Day 109 | d: function() { // Day of month w/leading 0; 01..31 110 | return _pad(f.j(), 2); 111 | }, 112 | D: function() { // Shorthand day name; Mon...Sun 113 | return f.l() 114 | .slice(0, 3); 115 | }, 116 | j: function() { // Day of month; 1..31 117 | return jsdate.getDate(); 118 | }, 119 | l: function() { // Full day name; Monday...Sunday 120 | return txt_words[f.w()] + 'day'; 121 | }, 122 | N: function() { // ISO-8601 day of week; 1[Mon]..7[Sun] 123 | return f.w() || 7; 124 | }, 125 | S: function() { // Ordinal suffix for day of month; st, nd, rd, th 126 | var j = f.j(); 127 | var i = j % 10; 128 | if (i <= 3 && parseInt((j % 100) / 10, 10) == 1) { 129 | i = 0; 130 | } 131 | return ['st', 'nd', 'rd'][i - 1] || 'th'; 132 | }, 133 | w: function() { // Day of week; 0[Sun]..6[Sat] 134 | return jsdate.getDay(); 135 | }, 136 | z: function() { // Day of year; 0..365 137 | var a = new Date(f.Y(), f.n() - 1, f.j()); 138 | var b = new Date(f.Y(), 0, 1); 139 | return Math.round((a - b) / 864e5); 140 | }, 141 | 142 | // Week 143 | W: function() { // ISO-8601 week number 144 | var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3); 145 | var b = new Date(a.getFullYear(), 0, 4); 146 | return _pad(1 + Math.round((a - b) / 864e5 / 7), 2); 147 | }, 148 | 149 | // Month 150 | F: function() { // Full month name; January...December 151 | return txt_words[6 + f.n()]; 152 | }, 153 | m: function() { // Month w/leading 0; 01...12 154 | return _pad(f.n(), 2); 155 | }, 156 | M: function() { // Shorthand month name; Jan...Dec 157 | return f.F() 158 | .slice(0, 3); 159 | }, 160 | n: function() { // Month; 1...12 161 | return jsdate.getMonth() + 1; 162 | }, 163 | t: function() { // Days in month; 28...31 164 | return (new Date(f.Y(), f.n(), 0)) 165 | .getDate(); 166 | }, 167 | 168 | // Year 169 | L: function() { // Is leap year?; 0 or 1 170 | var j = f.Y(); 171 | return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0; 172 | }, 173 | o: function() { // ISO-8601 year 174 | var n = f.n(); 175 | var W = f.W(); 176 | var Y = f.Y(); 177 | return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0); 178 | }, 179 | Y: function() { // Full year; e.g. 1980...2010 180 | return jsdate.getFullYear(); 181 | }, 182 | y: function() { // Last two digits of year; 00...99 183 | return f.Y() 184 | .toString() 185 | .slice(-2); 186 | }, 187 | 188 | // Time 189 | a: function() { // am or pm 190 | return jsdate.getHours() > 11 ? 'pm' : 'am'; 191 | }, 192 | A: function() { // AM or PM 193 | return f.a() 194 | .toUpperCase(); 195 | }, 196 | B: function() { // Swatch Internet time; 000..999 197 | var H = jsdate.getUTCHours() * 36e2; 198 | // Hours 199 | var i = jsdate.getUTCMinutes() * 60; 200 | // Minutes 201 | var s = jsdate.getUTCSeconds(); // Seconds 202 | return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3); 203 | }, 204 | g: function() { // 12-Hours; 1..12 205 | return f.G() % 12 || 12; 206 | }, 207 | G: function() { // 24-Hours; 0..23 208 | return jsdate.getHours(); 209 | }, 210 | h: function() { // 12-Hours w/leading 0; 01..12 211 | return _pad(f.g(), 2); 212 | }, 213 | H: function() { // 24-Hours w/leading 0; 00..23 214 | return _pad(f.G(), 2); 215 | }, 216 | i: function() { // Minutes w/leading 0; 00..59 217 | return _pad(jsdate.getMinutes(), 2); 218 | }, 219 | s: function() { // Seconds w/leading 0; 00..59 220 | return _pad(jsdate.getSeconds(), 2); 221 | }, 222 | u: function() { // Microseconds; 000000-999000 223 | return _pad(jsdate.getMilliseconds() * 1000, 6); 224 | }, 225 | 226 | // Timezone 227 | e: function() { // Timezone identifier; e.g. Atlantic/Azores, ... 228 | // The following works, but requires inclusion of the very large 229 | // timezone_abbreviations_list() function. 230 | /* return that.date_default_timezone_get(); 231 | */ 232 | throw 'Not supported (see source code of date() for timezone on how to add support)'; 233 | }, 234 | I: function() { // DST observed?; 0 or 1 235 | // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC. 236 | // If they are not equal, then DST is observed. 237 | var a = new Date(f.Y(), 0); 238 | // Jan 1 239 | var c = Date.UTC(f.Y(), 0); 240 | // Jan 1 UTC 241 | var b = new Date(f.Y(), 6); 242 | // Jul 1 243 | var d = Date.UTC(f.Y(), 6); // Jul 1 UTC 244 | return ((a - c) !== (b - d)) ? 1 : 0; 245 | }, 246 | O: function() { // Difference to GMT in hour format; e.g. +0200 247 | var tzo = jsdate.getTimezoneOffset(); 248 | var a = Math.abs(tzo); 249 | return (tzo > 0 ? '-' : '+') + _pad(Math.floor(a / 60) * 100 + a % 60, 4); 250 | }, 251 | P: function() { // Difference to GMT w/colon; e.g. +02:00 252 | var O = f.O(); 253 | return (O.substr(0, 3) + ':' + O.substr(3, 2)); 254 | }, 255 | T: function() { // Timezone abbreviation; e.g. EST, MDT, ... 256 | // The following works, but requires inclusion of the very 257 | // large timezone_abbreviations_list() function. 258 | /* var abbr, i, os, _default; 259 | if (!tal.length) { 260 | tal = that.timezone_abbreviations_list(); 261 | } 262 | if (that.php_js && that.php_js.default_timezone) { 263 | _default = that.php_js.default_timezone; 264 | for (abbr in tal) { 265 | for (i = 0; i < tal[abbr].length; i++) { 266 | if (tal[abbr][i].timezone_id === _default) { 267 | return abbr.toUpperCase(); 268 | } 269 | } 270 | } 271 | } 272 | for (abbr in tal) { 273 | for (i = 0; i < tal[abbr].length; i++) { 274 | os = -jsdate.getTimezoneOffset() * 60; 275 | if (tal[abbr][i].offset === os) { 276 | return abbr.toUpperCase(); 277 | } 278 | } 279 | } 280 | */ 281 | return 'UTC'; 282 | }, 283 | Z: function() { // Timezone offset in seconds (-43200...50400) 284 | return -jsdate.getTimezoneOffset() * 60; 285 | }, 286 | 287 | // Full Date/Time 288 | c: function() { // ISO-8601 date. 289 | return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb); 290 | }, 291 | r: function() { // RFC 2822 292 | return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb); 293 | }, 294 | U: function() { // Seconds since UNIX epoch 295 | return jsdate / 1000 | 0; 296 | } 297 | }; 298 | this.date = function(format, timestamp) { 299 | that = this; 300 | jsdate = (timestamp === undefined ? new Date() : // Not provided 301 | (timestamp instanceof Date) ? new Date(timestamp) : // JS Date() 302 | new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int) 303 | ); 304 | return format.replace(formatChr, formatChrCb); 305 | }; 306 | return this.date(format, timestamp); 307 | } 308 | 309 | // http://stackoverflow.com/questions/11887934/check-if-daylight-saving-time-is-in-effect-and-if-it-is-for-how-many-hours 310 | Date.prototype.stdTimezoneOffset = function() { 311 | var jan = new Date(this.getFullYear(), 0, 1); 312 | var jul = new Date(this.getFullYear(), 6, 1); 313 | return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()); 314 | }; 315 | 316 | Date.prototype.dst = function() { 317 | return this.getTimezoneOffset() < this.stdTimezoneOffset(); 318 | }; -------------------------------------------------------------------------------- /app/datasource/dexcom.js: -------------------------------------------------------------------------------- 1 | define(function () { 2 | // http://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back 3 | var lastSerialPort = false; 4 | function intFromBytes(x) { 5 | var val = 0; 6 | for (var i = 0; i < x.length; ++i) { 7 | val += x[i]; 8 | if (i < x.length-1) { 9 | val = val << 8; 10 | } 11 | } 12 | return val; 13 | } 14 | function getInt64Bytes(x) { 15 | var bytes = []; 16 | var i = 8; 17 | do { 18 | bytes[--i] = x & (255); 19 | x = x>>8; 20 | } while ( i ); 21 | return bytes; 22 | } 23 | 24 | function calculateCRC16(buff, start, end) { 25 | var crc = new Uint16Array(1); 26 | var buffer = new Uint8Array(buff); 27 | crc[0] = 0; 28 | for (var i = start; i < end; i++) { 29 | crc[0] = (crc[0] >>> 8) | (crc[0] << 8) & 0xffff; 30 | crc[0] ^= (buffer[i] & 0xff); 31 | crc[0] ^= ((crc[0] & 0xff) >> 4); 32 | crc[0] ^= (crc[0] << 12) & 0xffff; 33 | crc[0] ^= ((crc[0] & 0xff) << 5) & 0xffff; 34 | } 35 | crc[0] &= 0xffff; 36 | return crc[0]; 37 | } 38 | 39 | function int32at(jsBytes, ixStart, byteLength) { 40 | var u8 = new Uint8Array(jsBytes); 41 | var slice = u8.buffer.slice(ixStart, ixStart + byteLength); 42 | return (new Int32Array(slice))[0]; 43 | } 44 | 45 | function bytesOfInt(int32) { 46 | var a = new Int32Array(1); 47 | a[0] = int32; 48 | var bytes = new Uint8Array(a.buffer); 49 | return bytes; 50 | } 51 | 52 | var dexcom = { 53 | connected: false, 54 | connection: null, 55 | port: null, 56 | buffer: [], 57 | connect: function(serialport) { 58 | if (lastSerialPort) { 59 | return new Promise(function(resolve, reject) { 60 | dexcom.oldConnect(lastSerialPort, true).then(resolve, function() { 61 | dexcom.scanForDexcom.then(resolve, reject); 62 | }) 63 | }); 64 | } else if (serialport) { 65 | return new Promise(function(resolve, reject) { 66 | chrome.serial.getDevices(function(ports) { 67 | for (var i=0; i ports.length) { 88 | return reject(); 89 | } 90 | var port = ports[i]; 91 | setTimeout(function() { 92 | dexcom.oldConnect(port, true).then(function() { 93 | dexcom.ping().then(function(d) { 94 | if (d.length) { 95 | lastSerialPort = port; 96 | resolve(port); 97 | } else { 98 | dexcom.disconnect(); 99 | tryPort(++i); 100 | } 101 | }, function() { 102 | dexcom.disconnect(); 103 | tryPort(++i); 104 | }); 105 | }, function() { 106 | tryPort(++i); 107 | }); 108 | }, 250); 109 | } 110 | tryPort(0); 111 | }); 112 | }); 113 | }, 114 | oldConnect: function(serialport, foundActualDevice) { 115 | console.debug("[dexcom.oldConnect] getDevices with device: %o", serialport); 116 | return new Promise(function(resolve, reject) { 117 | if (dexcom.connected) { 118 | return reject(new Error("Wait for existing process to finish")); 119 | } 120 | var connected = function(conn) { 121 | if (conn && "connectionId" in conn) { 122 | dexcom.connection = conn; 123 | dexcom.connected = true; 124 | console.debug("[dexcom.oldConnect.connected] successfully connected to port %o", conn); 125 | setTimeout(resolve, 100); 126 | lastSerialPort = serialport; 127 | chrome.serial.onReceive.addListener(dexcom.serialOnReceiveListener); 128 | } else { 129 | if (conn) console.error("[dexcom.oldConnect.connected] Couldn't open USB connection to port %o", conn); 130 | reject(new Error( 131 | "Couldn't open USB connection. Unplug your Dexcom, plug it back in, and try again." 132 | )); 133 | } 134 | }; 135 | var tryPort = function(port) { 136 | console.debug("[dexcom.oldConnect.tryPort] Trying port: %o", port); 137 | if (!foundActualDevice && 138 | (port.path.substr(0,serialport.length).toLowerCase() != serialport.toLowerCase())) { 139 | return; 140 | } 141 | dexcom.port = port; 142 | chrome.serial.connect(dexcom.port.path, { bitrate: 115200 }, connected); 143 | }; 144 | if (foundActualDevice) { 145 | tryPort(serialport); 146 | } else { 147 | chrome.serial.getDevices(function(ports) { 148 | console.debug("[dexcom.oldConnect.getDevices] returned ports: %o", ports); 149 | ports.forEach(tryPort); 150 | if (dexcom.port === null) { 151 | lastSerialPort = false; 152 | reject(new Error( 153 | "Didn't find a Dexcom receiver plugged in" 154 | )); 155 | } 156 | }); 157 | } 158 | }); 159 | }, 160 | serialOnReceiveListener: function(info) { 161 | if (dexcom.connected && info.connectionId == dexcom.connection.connectionId && info.data) { 162 | var bufView=new Uint8Array(info.data); 163 | console.debug("[dexcom.serialOnReceiverListener] connection (low-level)] incoming data; %i bytes", bufView.byteLength); 164 | for (var i=0; i= bytes) { 172 | packet = dexcom.buffer.slice(0,bytes); 173 | console.info("0x" + packet.map(function(byte) { return ("0" + byte.toString(16)).substr(-2); }).join("") ); 174 | dexcom.buffer = dexcom.buffer.slice(0 - bytes); 175 | callback(packet); 176 | } else if (to === 0) { 177 | packet = dexcom.buffer; 178 | dexcom.buffer = []; 179 | console.info("0x" + packet.map(function(byte) { return ("0" + byte.toString(16)).substr(-2); }).join("") ); 180 | callback(packet); 181 | } else { 182 | var delta = Math.max(0, to - 50); 183 | setTimeout(function() { 184 | dexcom.readSerial(bytes, delta, callback); 185 | }, 50); 186 | } 187 | }, 188 | disconnect: function() { 189 | if (!dexcom.connected) { 190 | throw new Error("Not connected"); 191 | } 192 | chrome.serial.disconnect(dexcom.connection.connectionId, function() { 193 | console.debug("[dexcom.disconnect] completed"); 194 | }); 195 | dexcom.connected = false; 196 | dexcom.connection = null; 197 | dexcom.port = null; 198 | dexcom.buffer = []; 199 | chrome.serial.onReceive.removeListener(dexcom.serialOnReceiveListener); 200 | console.debug("[dexcom.disconnect] attempted"); 201 | }, 202 | writeSerial: function(bytes, callback) { 203 | dexcom.buffer = []; 204 | chrome.serial.send(dexcom.connection.connectionId, bytes, callback); 205 | console.debug("[dexcom.writeSerial (low level)] wrote command to serial"); 206 | }, 207 | readFromReceiver: function(pageOffset, callback) { 208 | return new Promise(function(resolve,reject) { 209 | try { 210 | console.debug("[dexcom.readFromReceiver] read page %i from serial", pageOffset); 211 | dexcom.getEGVDataPageRange(function(dexcomPageRange) { 212 | dexcom.getLastFourPages(dexcomPageRange, pageOffset, function(databasePages) { 213 | databasePages = databasePages.slice(4); // why? i dunno 214 | var data = dexcom.parseDatabasePages(databasePages); 215 | if (typeof callback == "function") 216 | callback(data); 217 | resolve(data); 218 | }); 219 | }); 220 | } catch (e) { 221 | reject(e); 222 | } 223 | }); 224 | //locate the EGV data pages 225 | }, 226 | ping: function() { 227 | // ping is command 10 228 | return new Promise(function(done, reject) { 229 | if (!dexcom.connected) { 230 | return reject(new Error("Not connected")); 231 | } 232 | var buf = new ArrayBuffer(7); 233 | readEGVDataPageRange =new Uint8Array(buf); 234 | readEGVDataPageRange[0] = 0x01; // sof 235 | readEGVDataPageRange[1] = 0x07; // length 236 | readEGVDataPageRange[3] = 0x00; // null because why? 237 | readEGVDataPageRange[4] = 0x0a; // command 238 | var crc = bytesOfInt(calculateCRC16(readEGVDataPageRange, 0, 5)); 239 | readEGVDataPageRange[5] = crc[0]; 240 | readEGVDataPageRange[6] = crc[1]; 241 | dexcom.writeSerial(buf, function() { 242 | dexcom.readSerial(6, 200, done); 243 | }); 244 | console.debug("[dexcom.ping] dispatched"); 245 | }); 246 | }, 247 | getDexcomSystemTime: function() { 248 | return new Promise(function(done, reject) { 249 | return done(new Date()); // I just don't need it. YOU make it work! :) 250 | }); 251 | }, 252 | getEGVDataPageRange: function(callback) { 253 | if (!dexcom.connected) { 254 | throw new Error("Not connected"); 255 | } 256 | var buf = new ArrayBuffer(7); 257 | readEGVDataPageRange =new Uint8Array(buf); 258 | readEGVDataPageRange[0] = 0x01; 259 | readEGVDataPageRange[1] = 0x07; 260 | readEGVDataPageRange[3] = 0x10; 261 | readEGVDataPageRange[4] = 0x04; 262 | var crc = bytesOfInt(calculateCRC16(readEGVDataPageRange, 0, 5)); 263 | readEGVDataPageRange[5] = crc[0]; 264 | readEGVDataPageRange[6] = crc[1]; 265 | dexcom.writeSerial(buf, function() { 266 | dexcom.readSerial(256, 200, callback); 267 | }); 268 | console.debug("[dexcom.getEGVDataPageRange]"); 269 | }, 270 | getLastFourPages: function(dexcomPageRangeJS, pageOffset,callback) { 271 | if (dexcomPageRangeJS.length === 0) { 272 | throw new Error( 273 | "Didn't receive response from Dexcom. Unplug, plug it back in, and try again." 274 | ); 275 | } 276 | var endPage = int32at(dexcomPageRangeJS, 8, 4); 277 | var getLastFour = endPage - 4 * pageOffset + 1; 278 | var b = bytesOfInt(getLastFour); 279 | 280 | var buf = new ArrayBuffer(12); 281 | getLastEGVPage =new Uint8Array(buf); 282 | 283 | getLastEGVPage[0] = 0x01; 284 | getLastEGVPage[1] = 0x0c; 285 | getLastEGVPage[2] = 0x00; 286 | getLastEGVPage[3] = 0x11; 287 | getLastEGVPage[4] = 0x04; 288 | getLastEGVPage[5] = b[0]; // reverse these 4? 289 | getLastEGVPage[6] = b[1]; 290 | getLastEGVPage[7] = b[2]; 291 | getLastEGVPage[8] = b[3]; 292 | getLastEGVPage[9] = 0x04; 293 | 294 | var checksum = bytesOfInt(calculateCRC16(getLastEGVPage, 0, 10)); 295 | 296 | getLastEGVPage[10] = checksum[0]; 297 | getLastEGVPage[11] = checksum[1]; 298 | 299 | dexcom.writeSerial(buf, function() { 300 | dexcom.readSerial(2118, 10000, callback); 301 | }); 302 | console.debug("[dexcom.getLastFourPages] called"); 303 | }, 304 | parseDatabasePages: function(databasePages) { 305 | var fourPages = []; 306 | var recordCounts = []; 307 | var totalRecordCount = 0; 308 | var i = 0; 309 | var dexcomTime = -800; //PST 310 | var localTime = (new Date().toString().match(/([-\+][0-9]+)\s/)[1]); 311 | delta = dexcomTime - localTime; 312 | var delta = { 313 | h: Math.floor(delta/100), 314 | m: delta % 100 315 | }; 316 | 317 | // God, I hope this doesn't bite me when DST starts again 318 | // delta.h++ was running already but... Ugh. 319 | // if ((new Date()).dst()) { 320 | delta.h++; 321 | // } 322 | delta.ms = (delta.h < 0? -1: 1) * (Math.abs(delta.h).hours() + delta.m.minutes()); 323 | 324 | console.debug("[dexcom.parseDatabasePages] parsing raw results to eGV records"); 325 | 326 | //we parse 4 pages at a time, calculate total record count while we do this 327 | for (i = 0; i < 4; i++) { 328 | fourPages[i] = databasePages.slice(528 * i, 528 * (i + 1)); 329 | recordCounts[i] = fourPages[i][4]; 330 | totalRecordCount += recordCounts[i]; 331 | } 332 | var recordsToReturn = []; 333 | var k = 0, j = 0; 334 | 335 | //parse each record, plenty of room for improvement 336 | var tempRecord = []; 337 | for (i = 0; i < 4; i++) { 338 | for (j = 0; j < recordCounts[i]; j++) { 339 | tempRecord = fourPages[i].slice(28 + j * 13, 28 + (j + 1) * 13); 340 | var eGValue = [tempRecord[8], tempRecord[9]]; 341 | var bGValue = ((eGValue[1]<<8) + (eGValue[0] & 0xff)) & 0x3ff; 342 | 343 | var dt = intFromBytes([tempRecord[7], tempRecord[6], tempRecord[5], tempRecord[4]]); 344 | var d = 1230793200000 + dt * 1000 + delta.ms; // Jan 1 2009 12:00:00a 345 | var display = new Date(d); 346 | 347 | var trendArrow = getInt64Bytes(tempRecord[10] & 15)[7]; 348 | var trend = "Not Calculated"; 349 | var trendA = "--X"; 350 | switch (trendArrow) { 351 | case 0: 352 | trend = "None"; 353 | trendA = String.fromCharCode(0x2194); 354 | break; 355 | case 1: 356 | trend = "DoubleUp"; 357 | trendA = String.fromCharCode(0x21C8); 358 | break; 359 | case (2): 360 | trendA = String.fromCharCode(0x2191); 361 | trend = "SingleUp"; 362 | break; 363 | case (3): 364 | trendA = String.fromCharCode(0x2197); 365 | trend = "FortyFiveUp"; 366 | break; 367 | case (4): 368 | trendA = String.fromCharCode(0x2192); 369 | trend = "Flat"; 370 | break; 371 | case (5): 372 | trendA = String.fromCharCode(0x2198); 373 | trend = "FortyFiveDown"; 374 | break; 375 | case (6): 376 | trendA = String.fromCharCode(0x2193); 377 | trend = "SingleDown"; 378 | break; 379 | case (7): 380 | trendA = String.fromCharCode(0x21ca); 381 | trend = "DoubleDown"; 382 | break; 383 | case (8): 384 | trendA = String.fromCharCode(0x2194); 385 | trend = "NOT COMPUTABLE"; 386 | break; 387 | case (9): 388 | trendA = String.fromCharCode(0x2194); 389 | trend = "OUT OF RANGE"; 390 | bGValue = undefined; 391 | break; 392 | } 393 | 394 | recordsToReturn.push({ 395 | bgValue: bGValue, 396 | displayTime: display, 397 | trend: trend, 398 | trendArrow: trendA 399 | }); 400 | } 401 | } 402 | console.debug("[dexcom.parseDatabasePages] done"); 403 | return recordsToReturn; 404 | }, 405 | 406 | getAllRecords: function() { 407 | var i = 1; 408 | var data = []; 409 | var callback = function() { }; 410 | 411 | var compile = function(i) { 412 | return new Promise(function(resolve,reject) { 413 | try { 414 | dexcom.readFromReceiver(i).then(function(d) { 415 | data.push(d); 416 | 417 | if (d.length) { 418 | resolve(d); 419 | } else { 420 | reject(); 421 | } 422 | }); 423 | } catch (e) { 424 | reject(e); 425 | } 426 | }); 427 | }, 428 | reader = function() { 429 | compile(i).then(function() { 430 | waiting.setProgress(i); 431 | i++; 432 | reader(); 433 | }, function() { // no more data 434 | var existing = egvrecords; 435 | var existing_ts = existing.map(function(row) { 436 | return row.displayTime; 437 | }); 438 | var new_records = Array.prototype.concat.apply([], data).map(function(egv) { 439 | return { 440 | displayTime: +egv.displayTime, 441 | bgValue: egv.bgValue, 442 | trend: egv.trend 443 | }; 444 | }).filter(function(row) { 445 | return existing_ts.filter(function(ts) { 446 | return ts == row.displayTime; 447 | }).length === 0; 448 | }).filter(function(row) { 449 | return row.bgValue > 30; 450 | }); 451 | egvrecords.addAll(new_records); 452 | console.debug("[dexcom.getAllRecords.reader] %i new records", new_records.length); 453 | dexcom.disconnect(); 454 | callback(new_records); 455 | }); 456 | }; 457 | return new Promise(function(done) { 458 | callback = done; 459 | dexcom.connect().then(reader) 460 | }); 461 | } 462 | }; 463 | return dexcom; 464 | }); 465 | -------------------------------------------------------------------------------- /app/window.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NightScout.info CGM Utility 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 263 | 264 | 265 | 283 | 284 | 302 | 303 | 364 |
365 |
366 | 367 | 368 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------
PeriodLowsIn RangeHighsStandard
Deviation
Low
Quartile
AverageUpper
Quartile
" + v.text + "" + v + "