diff --git a/lib/profile/carbs.js b/lib/profile/carbs.js index f365294b..6f274a54 100644 --- a/lib/profile/carbs.js +++ b/lib/profile/carbs.js @@ -1,8 +1,10 @@ var getTime = require('../medtronic-clock'); -function carbRatioLookup (inputs, profile) { - var now = new Date(); +function carbRatioLookup (inputs, profile, now) { + if (now === 'undefined') { + now = new Date(); + } var carbratio_data = inputs.carbratio; if (typeof(carbratio_data) !== "undefined" && typeof(carbratio_data.schedule) !== "undefined") { var carbRatio; @@ -13,14 +15,15 @@ function carbRatioLookup (inputs, profile) { for (var i = 0; i < carbratio_data.schedule.length - 1; i++) { if ((now >= getTime(carbratio_data.schedule[i].offset)) && (now < getTime(carbratio_data.schedule[i + 1].offset))) { carbRatio = carbratio_data.schedule[i]; - // disallow impossibly high/low carbRatios due to bad decoding - if (carbRatio < 3 || carbRatio > 150) { - console.error("Error: carbRatio of " + carbRatio + " out of bounds."); - return; - } break; } } + // disallow impossibly high/low carbRatios due to bad decoding + if (carbRatio.ratio < 3 || carbRatio.ratio > 150) { + console.error("Error: carbRatio of " + carbRatio.ratio + " out of bounds."); + return; + } + if (carbratio_data.units === "exchanges") { carbRatio.ratio = 12 / carbRatio.ratio } diff --git a/tests/profile-carbs.test.js b/tests/profile-carbs.test.js new file mode 100644 index 00000000..09589198 --- /dev/null +++ b/tests/profile-carbs.test.js @@ -0,0 +1,51 @@ +'use strict'; + +require('should'); +var _ = require('lodash'); +var carb_ratios = require('../lib/profile/carbs'); + +describe('Carb Ratio Profile', function() { + var carbratio_input = { + units: 'grams', + schedule: [ + { offset: 0, ratio: 15, start: '00:00:00' }, + { offset: 180, ratio: 18, start: '03:00:00' }, + { offset: 360, ratio: 20, start: '06:00:00' } + ] + }; + + it('should return current carb ratio from schedule', function() { + var now = new Date('2025-01-26T02:00:00'); + var ratio = carb_ratios.carbRatioLookup({carbratio: carbratio_input}, null, now); + ratio.should.equal(15); + }); + + it('should handle ratio schedule changes', function() { + var now = new Date('2025-01-26T04:00:00'); + var ratio = carb_ratios.carbRatioLookup({carbratio: carbratio_input}, null, now); + ratio.should.equal(18); + }); + + it('should handle exchanges unit conversion', function() { + var exchange_input = { + units: 'exchanges', + schedule: [ + { offset: 0, ratio: 12, start: '00:00:00' } + ] + }; + var now = new Date('2025-01-26T04:00:00'); + var ratio = carb_ratios.carbRatioLookup({carbratio: exchange_input}, null, now); + ratio.should.equal(1); // 12 grams per exchange + }); + + it('should reject invalid ratios', function() { + var invalid_input = { + units: 'grams', + schedule: [ + { offset: 0, ratio: 2, start: '00:00:00' } // Less than min of 3 + ] + }; + var ratio = carb_ratios.carbRatioLookup({carbratio: invalid_input}); + should.not.exist(ratio); + }); +});