From 123d4814696eafc50062b774a62b7fdc90b80518 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Mon, 4 Apr 2022 12:22:04 -0500 Subject: [PATCH 01/14] Running setScan with active: true --- apps/bthrm/settings.js | 2 +- apps/health/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/bthrm/settings.js b/apps/bthrm/settings.js index 4b564d670..9f409880a 100644 --- a/apps/bthrm/settings.js +++ b/apps/bthrm/settings.js @@ -127,7 +127,7 @@ }); }; } - }, { filters: [{services: [ "180d" ]}]}); + }, { active: true, filters: [{services: [ "180d" ]}]}); } diff --git a/apps/health/README.md b/apps/health/README.md index f44854e3e..e3a84068b 100644 --- a/apps/health/README.md +++ b/apps/health/README.md @@ -2,7 +2,7 @@ Logs health data to a file every 10 minutes, and provides an app to view it -**BETA - requires firmware 2v11** +**BETA - requires firmware 2v11 or later** ## Usage From d27deac8aadfa6f9393e31aa26c4c69bb4f39dd2 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Mon, 4 Apr 2022 14:47:17 -0500 Subject: [PATCH 02/14] Adding 'active: true' to NRF.requestDevice call made when btname is set --- apps/bthrm/boot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 3a1f1cc4c..93e72b83b 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -370,7 +370,7 @@ filters = [{name: settings.btname}]; } log("Requesting device with filters", filters); - promise = NRF.requestDevice({ filters: filters }); + promise = NRF.requestDevice({ filters: filters, active: true }); if (settings.gracePeriodRequest){ log("Add " + settings.gracePeriodRequest + "ms grace period after request"); From d89db8f7d7f680c11aa73780c50483364972059b Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Mon, 4 Apr 2022 15:55:14 -0500 Subject: [PATCH 03/14] Removing call to function that doesn't exist --- apps/bthrm/boot.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 93e72b83b..227f78c1a 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -108,7 +108,7 @@ var sensorContact; if (flags & 2){ - sensorContact = (flags & 4) ? true : false; + sensorContact = !!(flags & 4); } var idx = 2 + (flags&1); @@ -297,7 +297,7 @@ }); } else if (newCharacteristic.read){ result = result.then(()=>{ - readData(newCharacteristic); + // readData(newCharacteristic); log("Reading data for " + newCharacteristic); return newCharacteristic.read().then((data)=>{ supportedCharacteristics[newCharacteristic.uuid].handler(data); From 75c4e5b54b54181c054bbb2a68603435f02761cf Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Mon, 4 Apr 2022 16:48:15 -0500 Subject: [PATCH 04/14] bthrm fixes for reading characteristics generally and displaying location --- apps/bthrm/boot.js | 17 +++++++++-------- apps/bthrm/bthrm.js | 13 +++++++++++-- typescript/types/globals.d.ts | 6 +++--- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 227f78c1a..dd25634e5 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -168,14 +168,14 @@ //Body sensor location handler: function(data){ if (!lastReceivedData["0x180d"]) lastReceivedData["0x180d"] = {}; - if (!lastReceivedData["0x180d"]["0x2a38"]) lastReceivedData["0x180d"]["0x2a38"] = data.target.value; + lastReceivedData["0x180d"]["0x2a38"] = parseInt(data.buffer, 10); } }, "0x2a19": { //Battery handler: function (event){ - if (!lastReceivedData["0x180f"]) lastReceivedData["0x180f"] = {}; - if (!lastReceivedData["0x180f"]["0x2a19"]) lastReceivedData["0x180f"]["0x2a19"] = event.target.value.getUint8(0); + if (!lastReceivedData["0x180f"]) lastReceivedData["0x180f"] = { "0x2a19": null }; + lastReceivedData["0x180f"]["0x2a19"] = event.target.value.getUint8(0); } } @@ -295,12 +295,13 @@ } return startPromise; }); - } else if (newCharacteristic.read){ + } else if (newCharacteristic.readValue){ result = result.then(()=>{ - // readData(newCharacteristic); - log("Reading data for " + newCharacteristic); - return newCharacteristic.read().then((data)=>{ - supportedCharacteristics[newCharacteristic.uuid].handler(data); + log("Reading data for " + JSON.stringify(newCharacteristic)); + return newCharacteristic.readValue().then((data)=>{ + if (supportedCharacteristics[newCharacteristic.uuid] && supportedCharacteristics[newCharacteristic.uuid].handler) { + supportedCharacteristics[newCharacteristic.uuid].handler(data); + } }); }); } diff --git a/apps/bthrm/bthrm.js b/apps/bthrm/bthrm.js index cc533eedd..5ab3b0018 100644 --- a/apps/bthrm/bthrm.js +++ b/apps/bthrm/bthrm.js @@ -1,7 +1,16 @@ -var btm = g.getHeight()-1; var intervalInt; var intervalBt; +var BODY_LOCS = { + 0: 'Other', + 1: 'Chest', + 2: 'Wrist', + 3: 'Finger', + 4: 'Hand', + 5: 'Ear Lobe', + 6: 'Foot', +} + function clear(y){ g.reset(); g.clearRect(0,y,g.getWidth(),y+75); @@ -25,7 +34,7 @@ function draw(y, type, event) { if (event.battery) str += " Bat: " + (event.battery ? event.battery : ""); g.setFontVector(12).drawString(str,px,y+40); str= ""; - if (event.location) str += "Loc: " + event.location.toFixed(0) + "ms"; + if (event.location) str += "Loc: " + BODY_LOCS[event.location]; if (event.rr && event.rr.length > 0) str += " RR: " + event.rr.join(","); g.setFontVector(12).drawString(str,px,y+50); str= ""; diff --git a/typescript/types/globals.d.ts b/typescript/types/globals.d.ts index 2ef52dcdf..442140e70 100644 --- a/typescript/types/globals.d.ts +++ b/typescript/types/globals.d.ts @@ -158,9 +158,9 @@ declare type Image = { }; declare type GraphicsApi = { - reset: () => void; + reset: () => GraphicsApi; flip: () => void; - setColor: (color: string) => void; // TODO we can most likely type color more usefully than this + setColor: (color: string) => GraphicsApi; // TODO we can most likely type color more usefully than this drawImage: ( image: string | Image | ArrayBuffer, xOffset: number, @@ -169,7 +169,7 @@ declare type GraphicsApi = { rotate?: number; scale?: number; } - ) => void; + ) => GraphicsApi; // TODO add more }; From d19a68e5117904689b9a35706fceeb64f3bd04fc Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Mon, 4 Apr 2022 17:29:20 -0500 Subject: [PATCH 05/14] Fix how events and reads were handled differently --- apps/bthrm/boot.js | 55 +++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index dd25634e5..0a6af55b6 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -31,7 +31,7 @@ function addNotificationHandler(characteristic){ log("Setting notification handler: " + supportedCharacteristics[characteristic.uuid].handler); - characteristic.on('characteristicvaluechanged', supportedCharacteristics[characteristic.uuid].handler); + characteristic.on('characteristicvaluechanged', (ev) => supportedCharacteristics[characteristic.uuid].handler(ev.target.value)); } function writeCache(cache){ @@ -92,15 +92,14 @@ services: [ "180d" ] }]; - supportedServices = [ + var supportedServices = [ "0x180d", "0x180f" ]; var supportedCharacteristics = { "0x2a37": { //Heart rate measurement - handler: function (event){ - var dv = event.target.value; + handler: function (dv){ var flags = dv.getUint8(0); var bpm = (flags & 1) ? (dv.getUint16(1) / 100 /* ? */ ) : dv.getUint8(1); // 8 or 16 bit @@ -121,7 +120,7 @@ var interval; if (flags & 16) { interval = []; - maxIntervalBytes = (dv.byteLength - idx); + var maxIntervalBytes = (dv.byteLength - idx); log("Found " + (maxIntervalBytes / 2) + " rr data fields"); for(var i = 0 ; i < maxIntervalBytes / 2; i++){ interval[i] = dv.getUint16(idx,1); // in milliseconds @@ -140,14 +139,14 @@ } if (settings.replace){ - var newEvent = { + var repEvent = { bpm: bpm, confidence: (sensorContact || sensorContact === undefined)? 100 : 0, src: "bthrm" }; - log("Emitting HRM: ", newEvent); - Bangle.emit("HRM", newEvent); + log("Emitting HRM: ", repEvent); + Bangle.emit("HRM", repEvent); } var newEvent = { @@ -159,23 +158,23 @@ if (energyExpended) newEvent.energy = energyExpended; if (battery) newEvent.battery = battery; if (sensorContact) newEvent.contact = sensorContact; - + log("Emitting BTHRM: ", newEvent); Bangle.emit("BTHRM", newEvent); } }, "0x2a38": { //Body sensor location - handler: function(data){ + handler: function(dv){ if (!lastReceivedData["0x180d"]) lastReceivedData["0x180d"] = {}; - lastReceivedData["0x180d"]["0x2a38"] = parseInt(data.buffer, 10); + lastReceivedData["0x180d"]["0x2a38"] = parseInt(dv.buffer, 10); } }, "0x2a19": { //Battery - handler: function (event){ - if (!lastReceivedData["0x180f"]) lastReceivedData["0x180f"] = { "0x2a19": null }; - lastReceivedData["0x180f"]["0x2a19"] = event.target.value.getUint8(0); + handler: function (dv){ + if (!lastReceivedData["0x180f"]) lastReceivedData["0x180f"] = {}; + lastReceivedData["0x180f"]["0x2a19"] = dv.getUint8(0); } } @@ -282,6 +281,18 @@ function createCharacteristicPromise(newCharacteristic){ log("Create characteristic promise: ", newCharacteristic); var result = Promise.resolve(); + // For values that can be read, go ahead and read them, even if we might be notified in the future + // Allows for getting initial state of infrequently updating characteristics, like battery + if (newCharacteristic.readValue){ + result = result.then(()=>{ + log("Reading data for " + JSON.stringify(newCharacteristic)); + return newCharacteristic.readValue().then((data)=>{ + if (supportedCharacteristics[newCharacteristic.uuid] && supportedCharacteristics[newCharacteristic.uuid].handler) { + supportedCharacteristics[newCharacteristic.uuid].handler(data); + } + }); + }); + } if (newCharacteristic.properties.notify){ result = result.then(()=>{ log("Starting notifications for: ", newCharacteristic); @@ -295,15 +306,6 @@ } return startPromise; }); - } else if (newCharacteristic.readValue){ - result = result.then(()=>{ - log("Reading data for " + JSON.stringify(newCharacteristic)); - return newCharacteristic.readValue().then((data)=>{ - if (supportedCharacteristics[newCharacteristic.uuid] && supportedCharacteristics[newCharacteristic.uuid].handler) { - supportedCharacteristics[newCharacteristic.uuid].handler(data); - } - }); - }); } return result.then(()=>log("Handled characteristic: ", newCharacteristic)); } @@ -526,10 +528,9 @@ } }; } - - + var fallbackInterval; - + function switchInternalHrm(){ if (settings.allowFallback && !fallbackInterval){ log("Fallback to HRM enabled"); @@ -558,7 +559,7 @@ } switchInternalHrm(); } - + E.on("kill", ()=>{ if (gatt && gatt.connected){ log("Got killed, trying to disconnect"); From d9908ee6a2a77eab3b6371ade461a1ea449eec87 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 5 Apr 2022 09:53:52 -0500 Subject: [PATCH 06/14] Switch from setScan to findDevices --- apps/bthrm/boot.js | 8 +-- apps/bthrm/settings.js | 110 +++++++++++++---------------------------- 2 files changed, 38 insertions(+), 80 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 0a6af55b6..ad3c85591 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -24,7 +24,7 @@ function getCache(){ var cache = require('Storage').readJSON("bthrm.cache.json", true) || {}; - if (settings.btname && settings.btname == cache.name) return cache; + if (settings.btid && settings.btid == cache.id) return cache; clearCache(); return {}; } @@ -368,9 +368,9 @@ if (!device){ var filters = serviceFilters; - if (settings.btname){ - log("Configured device name", settings.btname); - filters = [{name: settings.btname}]; + if (settings.btid){ + log("Configured device id", settings.btid); + filters = [{id: settings.btid }]; } log("Requesting device with filters", filters); promise = NRF.requestDevice({ filters: filters, active: true }); diff --git a/apps/bthrm/settings.js b/apps/bthrm/settings.js index 9f409880a..b376d6a2d 100644 --- a/apps/bthrm/settings.js +++ b/apps/bthrm/settings.js @@ -5,14 +5,14 @@ require('Storage').writeJSON(FILE, s); readSettings(); } - + function readSettings(){ settings = Object.assign( require('Storage').readJSON("bthrm.default.json", true) || {}, require('Storage').readJSON(FILE, true) || {} ); } - + var FILE="bthrm.json"; var settings; readSettings(); @@ -61,12 +61,13 @@ } }; - if (settings.btname){ - var name = "Clear " + settings.btname; + if (settings.btname || settings.btid){ + var name = "Clear " + (settings.btname || settings.btid); mainmenu[name] = function() { - E.showPrompt("Clear current device name?").then((r)=>{ + E.showPrompt("Clear current device?").then((r)=>{ if (r) { writeSettings("btname",undefined); + writeSettings("btid",undefined); } E.showMenu(buildMainMenu()); }); @@ -78,9 +79,7 @@ mainmenu.Debug = function() { E.showMenu(submenu_debug); }; return mainmenu; } - - var submenu_debug = { '' : { title: "Debug"}, '< Back': function() { E.showMenu(buildMainMenu()); }, @@ -103,35 +102,39 @@ function createMenuFromScan(){ E.showMenu(); - E.showMessage("Scanning"); + E.showMessage("Scanning for 4 seconds"); var submenu_scan = { - '' : { title: "Scan"}, '< Back': function() { E.showMenu(buildMainMenu()); } }; - var packets=10; - var scanStart=Date.now(); - NRF.setScan(function(d) { - packets--; - if (packets<=0 || Date.now() - scanStart > 5000){ - NRF.setScan(); - E.showMenu(submenu_scan); - } else if (d.name){ - print("Found device", d); - submenu_scan[d.name] = function(){ - E.showPrompt("Set "+d.name+"?").then((r)=>{ - if (r) { - writeSettings("btname",d.name); - } - E.showMenu(buildMainMenu()); + NRF.findDevices(function(devices) { + submenu_scan[''] = { title: `Scan (${devices.length} found)`}; + if (devices.length === 0) { + E.showAlert("No devices found") + .then(() => E.showMenu(buildMainMenu())); + return; + } else { + devices.forEach((d) => { + print("Found device", d); + var shown = (d.name || d.id.substr(0, 17)); + submenu_scan[shown] = function () { + E.showPrompt("Set " + shown + "?").then((r) => { + if (r) { + writeSettings("btid", d.id); + // Store the name for displaying later. Will connect by ID + if (d.name) { + writeSettings("btname", d.name); + } + } + E.showMenu(buildMainMenu()); + }); + }; }); - }; } - }, { active: true, filters: [{services: [ "180d" ]}]}); + E.showMenu(submenu_scan); + }, { timeout: 4000, active: true, filters: [{services: [ "180d" ]}]}); } - - var submenu_custom = { '' : { title: "Custom mode"}, '< Back': function() { E.showMenu(buildMainMenu()); }, @@ -167,7 +170,7 @@ } }, }; - + var submenu_grace = { '' : { title: "Grace periods"}, '< Back': function() { E.showMenu(submenu_debug); }, @@ -212,51 +215,6 @@ } } }; - - var submenu = { - '' : { title: "Grace periods"}, - '< Back': function() { E.showMenu(buildMainMenu()); }, - 'Request': { - value: settings.gracePeriodRequest, - min: 0, - max: 3000, - step: 100, - format: v=>v+"ms", - onchange: v => { - writeSettings("gracePeriodRequest",v); - } - }, - 'Connect': { - value: settings.gracePeriodConnect, - min: 0, - max: 3000, - step: 100, - format: v=>v+"ms", - onchange: v => { - writeSettings("gracePeriodConnect",v); - } - }, - 'Notification': { - value: settings.gracePeriodNotification, - min: 0, - max: 3000, - step: 100, - format: v=>v+"ms", - onchange: v => { - writeSettings("gracePeriodNotification",v); - } - }, - 'Service': { - value: settings.gracePeriodService, - min: 0, - max: 3000, - step: 100, - format: v=>v+"ms", - onchange: v => { - writeSettings("gracePeriodService",v); - } - } - }; - + E.showMenu(buildMainMenu()); -}) +}); From 88a785df7f7d0e05023fbcd69b7ae71e85a6fb8b Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 5 Apr 2022 20:58:33 -0500 Subject: [PATCH 07/14] Update some types --- typescript/types/globals.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript/types/globals.d.ts b/typescript/types/globals.d.ts index 442140e70..7af19700b 100644 --- a/typescript/types/globals.d.ts +++ b/typescript/types/globals.d.ts @@ -140,7 +140,7 @@ declare const require: ((module: 'heatshrink') => { declare const Bangle: { // functions - buzz: () => void; + buzz: (duration: number, intensity: number) => Promise; drawWidgets: () => void; isCharging: () => boolean; // events From 908a41d5237f2b6e30eca2c2bfd00954dd329051 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 5 Apr 2022 20:58:47 -0500 Subject: [PATCH 08/14] Try to bond --- apps/bthrm/boot.js | 79 ++++++++++++++++++++++++--------------------- apps/bthrm/bthrm.js | 6 ++-- 2 files changed, 46 insertions(+), 39 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index ad3c85591..8e18b3e34 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -3,7 +3,7 @@ require('Storage').readJSON("bthrm.default.json", true) || {}, require('Storage').readJSON("bthrm.json", true) || {} ); - + var log = function(text, param){ if (settings.debuglog){ var logline = new Date().toISOString() + " - " + text; @@ -13,9 +13,9 @@ print(logline); } }; - + log("Settings: ", settings); - + if (settings.enabled){ function clearCache(){ @@ -24,25 +24,24 @@ function getCache(){ var cache = require('Storage').readJSON("bthrm.cache.json", true) || {}; - if (settings.btid && settings.btid == cache.id) return cache; + if (settings.btid && settings.btid === cache.id) return cache; clearCache(); return {}; } - + function addNotificationHandler(characteristic){ log("Setting notification handler: " + supportedCharacteristics[characteristic.uuid].handler); characteristic.on('characteristicvaluechanged', (ev) => supportedCharacteristics[characteristic.uuid].handler(ev.target.value)); } - + function writeCache(cache){ var oldCache = getCache(); - if (oldCache != cache) { + if (oldCache !== cache) { log("Writing cache"); require('Storage').writeJSON("bthrm.cache.json", cache) } else { log("No changes, don't write cache"); } - } function characteristicsToCache(characteristics){ @@ -177,7 +176,6 @@ lastReceivedData["0x180f"]["0x2a19"] = dv.getUint8(0); } } - }; var device; @@ -185,7 +183,7 @@ var characteristics = []; var blockInit = false; var currentRetryTimeout; - var initialRetryTime = 40; + var initialRetryTime = 1000; var maxRetryTime = 60000; var retryTime = initialRetryTime; @@ -214,7 +212,6 @@ }; } - if (settings.replace){ var origIsHRMOn = Bangle.isHRMOn; @@ -309,14 +306,14 @@ } return result.then(()=>log("Handled characteristic: ", newCharacteristic)); } - + function attachCharacteristicPromise(promise, characteristic){ return promise.then(()=>{ log("Handling characteristic:", characteristic); return createCharacteristicPromise(characteristic); }); } - + function createCharacteristicsPromise(newCharacteristics){ log("Create characteristics promise: ", newCharacteristics); var result = Promise.resolve(); @@ -327,12 +324,12 @@ if (c.properties.notify){ addNotificationHandler(c); } - + result = attachCharacteristicPromise(result, c); } return result.then(()=>log("Handled characteristics")); } - + function createServicePromise(service){ log("Create service promise: ", service); var result = Promise.resolve(); @@ -342,11 +339,11 @@ }); return result.then(()=>log("Handled service" + service.uuid)); } - + function attachServicePromise(promise, service){ return promise.then(()=>createServicePromise(service)); } - + var reUseCounter = 0; function initBt() { @@ -363,9 +360,9 @@ gatt=undefined; reUseCounter = 0; } - + var promise; - + if (!device){ var filters = serviceFilters; if (settings.btid){ @@ -374,27 +371,26 @@ } log("Requesting device with filters", filters); promise = NRF.requestDevice({ filters: filters, active: true }); - + if (settings.gracePeriodRequest){ log("Add " + settings.gracePeriodRequest + "ms grace period after request"); } - + promise = promise.then((d)=>{ log("Got device: ", d); d.on('gattserverdisconnected', onDisconnect); device = d; }); - + promise = promise.then(()=>{ log("Wait after request"); return waitingPromise(settings.gracePeriodRequest); }); - } else { promise = Promise.resolve(); log("Reuse device: ", device); } - + promise = promise.then(()=>{ if (gatt){ log("Reuse GATT: ", gatt); @@ -402,7 +398,7 @@ log("GATT is new: ", gatt); characteristics = []; var cachedName = getCache().name; - if (device.name != cachedName){ + if (device.name !== cachedName){ log("Device name changed from " + cachedName + " to " + device.name + ", clearing cache"); clearCache(); } @@ -411,10 +407,10 @@ writeCache(newCache); gatt = device.gatt; } - + return Promise.resolve(gatt); }); - + promise = promise.then((gatt)=>{ if (!gatt.connected){ var connectPromise = gatt.connect(connectSettings); @@ -430,16 +426,28 @@ return Promise.resolve(); } }); - + + promise = promise.then(() => { + log(JSON.stringify(gatt.getSecurityStatus())); + if (gatt.getSecurityStatus()['bonded']) { + log("Already bonded"); + return Promise.resolve(); + } else { + log("Start bonding"); + return gatt.startBonding() + .then(() => console.log(gatt.getSecurityStatus())); + } + }); + promise = promise.then(()=>{ - if (!characteristics || characteristics.length == 0){ + if (!characteristics || characteristics.length === 0){ characteristics = characteristicsFromCache(); } }); promise = promise.then(()=>{ var characteristicsPromise = Promise.resolve(); - if (characteristics.length == 0){ + if (characteristics.length === 0){ characteristicsPromise = characteristicsPromise.then(()=>{ log("Getting services"); return gatt.getPrimaryServices(); @@ -462,17 +470,16 @@ } return result; }); - } else { for (var characteristic of characteristics){ characteristicsPromise = attachCharacteristicPromise(characteristicsPromise, characteristic, true); } } - + return characteristicsPromise; }); - promise = promise.then(()=>{ + return promise.then(()=>{ log("Connection established, waiting for notifications"); reUseCounter = 0; characteristicsToCache(characteristics); @@ -490,7 +497,7 @@ if (Bangle._PWR===undefined) Bangle._PWR={}; if (Bangle._PWR.BTHRM===undefined) Bangle._PWR.BTHRM=[]; if (isOn && !Bangle._PWR.BTHRM.includes(app)) Bangle._PWR.BTHRM.push(app); - if (!isOn && Bangle._PWR.BTHRM.includes(app)) Bangle._PWR.BTHRM = Bangle._PWR.BTHRM.filter(a=>a!=app); + if (!isOn && Bangle._PWR.BTHRM.includes(app)) Bangle._PWR.BTHRM = Bangle._PWR.BTHRM.filter(a=>a!==app); isOn = Bangle._PWR.BTHRM.length; // so now we know if we're really on if (isOn) { @@ -513,7 +520,7 @@ } } }; - + var origSetHRMPower = Bangle.setHRMPower; if (settings.startWithHrm){ @@ -563,7 +570,7 @@ E.on("kill", ()=>{ if (gatt && gatt.connected){ log("Got killed, trying to disconnect"); - var promise = gatt.disconnect().then(()=>log("Disconnected on kill")).catch((e)=>log("Error during disconnnect on kill", e)); + gatt.disconnect().then(()=>log("Disconnected on kill")).catch((e)=>log("Error during disconnnect on kill", e)); } }); } diff --git a/apps/bthrm/bthrm.js b/apps/bthrm/bthrm.js index 5ab3b0018..dd9230386 100644 --- a/apps/bthrm/bthrm.js +++ b/apps/bthrm/bthrm.js @@ -24,13 +24,13 @@ function draw(y, type, event) { g.setFontAlign(0,0); g.setFontVector(40).drawString(str,px,y+20); str = "Event: " + type; - if (type == "HRM") { + if (type === "HRM") { str += " Confidence: " + event.confidence; g.setFontVector(12).drawString(str,px,y+40); str = " Source: " + (event.src ? event.src : "internal"); g.setFontVector(12).drawString(str,px,y+50); } - if (type == "BTHRM"){ + if (type === "BTHRM"){ if (event.battery) str += " Bat: " + (event.battery ? event.battery : ""); g.setFontVector(12).drawString(str,px,y+40); str= ""; @@ -54,7 +54,7 @@ function onBtHrm(e) { firstEventBt = false; } draw(100, "BTHRM", e); - if (e.bpm == 0){ + if (e.bpm === 0){ Bangle.buzz(100,0.2); } if (intervalBt){ From 31fd2344a8ffb7e9ec9bf97635a155e8f75bf429 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 5 Apr 2022 21:05:03 -0500 Subject: [PATCH 09/14] Fix for buzz type updated in previous commit --- typescript/types/globals.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript/types/globals.d.ts b/typescript/types/globals.d.ts index 7af19700b..e82c3da3d 100644 --- a/typescript/types/globals.d.ts +++ b/typescript/types/globals.d.ts @@ -140,7 +140,7 @@ declare const require: ((module: 'heatshrink') => { declare const Bangle: { // functions - buzz: (duration: number, intensity: number) => Promise; + buzz: (duration?: number, intensity?: number) => Promise; drawWidgets: () => void; isCharging: () => boolean; // events From 9eb4d8eb73684eca9ee4d0eadc8aec94bf467d6c Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Thu, 7 Apr 2022 15:58:39 -0500 Subject: [PATCH 10/14] Remove bonding for now --- apps/bthrm/boot.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 8e18b3e34..f9de2ee5d 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -427,7 +427,7 @@ } }); - promise = promise.then(() => { +/* promise = promise.then(() => { log(JSON.stringify(gatt.getSecurityStatus())); if (gatt.getSecurityStatus()['bonded']) { log("Already bonded"); @@ -437,7 +437,7 @@ return gatt.startBonding() .then(() => console.log(gatt.getSecurityStatus())); } - }); + });*/ promise = promise.then(()=>{ if (!characteristics || characteristics.length === 0){ From 7eeeca52ca25b2c633aed8a99c7fa12701e6d69c Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Thu, 7 Apr 2022 22:04:47 -0500 Subject: [PATCH 11/14] Update README and follow linting instructions --- apps/bthrm/README.md | 13 ++-- apps/bthrm/boot.js | 124 ++++++++++++++++++--------------------- apps/bthrm/metadata.json | 2 +- 3 files changed, 66 insertions(+), 73 deletions(-) diff --git a/apps/bthrm/README.md b/apps/bthrm/README.md index 42ad619bd..8d5872670 100644 --- a/apps/bthrm/README.md +++ b/apps/bthrm/README.md @@ -2,7 +2,7 @@ When this app is installed it overrides Bangle.js's build in heart rate monitor with an external Bluetooth one. -HRM is requested it searches on Bluetooth for a heart rate monitor, connects, and sends data back using the `Bangle.on('HRM'` event as if it came from the on board monitor. +HRM is requested it searches on Bluetooth for a heart rate monitor, connects, and sends data back using the `Bangle.on('HRM')` event as if it came from the on board monitor. This means it's compatible with many Bangle.js apps including: @@ -16,19 +16,23 @@ as that requires live sensor data (rather than just BPM readings). Just install the app, then install an app that uses the heart rate monitor. -Once installed it'll automatically try and connect to the first bluetooth -heart rate monitor it finds. +Once installed you will have to go into this app's settings while your heart rate monitor + is available for bluetooth pairing and scan for devices. **To disable this and return to normal HRM, uninstall the app** ## Compatible Heart Rate Monitors This works with any heart rate monitor providing the standard Bluetooth -Heart Rate Service (`180D`) and characteristic (`2A37`). +Heart Rate Service (`180D`) and characteristic (`2A37`). It additionally supports +the location (`2A38`) characteristic and the Battery Service (`180F`), reporting +that information in the `BTHRM` event when they are available. So far it has been tested on: * CooSpo Bluetooth Heart Rate Monitor +* Polar H10 +* Polar OH1 * Wahoo TICKR X 2 ## Internals @@ -38,7 +42,6 @@ This replaces `Bangle.setHRMPower` with its own implementation. ## TODO * A widget to show connection state? -* Specify a specific device by address? ## Creator diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index f9de2ee5d..064f65eac 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -18,33 +18,33 @@ if (settings.enabled){ - function clearCache(){ + var clearCache = function() { return require('Storage').erase("bthrm.cache.json"); - } + }; - function getCache(){ + var getCache = function() { var cache = require('Storage').readJSON("bthrm.cache.json", true) || {}; if (settings.btid && settings.btid === cache.id) return cache; clearCache(); return {}; - } + }; - function addNotificationHandler(characteristic){ + var addNotificationHandler = function(characteristic) { log("Setting notification handler: " + supportedCharacteristics[characteristic.uuid].handler); characteristic.on('characteristicvaluechanged', (ev) => supportedCharacteristics[characteristic.uuid].handler(ev.target.value)); - } + }; - function writeCache(cache){ + var writeCache = function(cache) { var oldCache = getCache(); if (oldCache !== cache) { log("Writing cache"); - require('Storage').writeJSON("bthrm.cache.json", cache) + require('Storage').writeJSON("bthrm.cache.json", cache); } else { log("No changes, don't write cache"); } - } + }; - function characteristicsToCache(characteristics){ + var characteristicsToCache = function(characteristics) { log("Cache characteristics"); var cache = getCache(); if (!cache.characteristics) cache.characteristics = {}; @@ -59,9 +59,9 @@ }; } writeCache(cache); - } + }; - function characteristicsFromCache(){ + var characteristicsFromCache = function() { log("Read cached characteristics"); var cache = getCache(); if (!cache.characteristics) return []; @@ -80,19 +80,16 @@ restored.push(r); } return restored; - } + }; log("Start"); var lastReceivedData={ }; - var serviceFilters = [{ - services: [ "180d" ] - }]; - var supportedServices = [ - "0x180d", "0x180f" + "0x180d", // Heart Rate + "0x180f", // Battery ]; var supportedCharacteristics = { @@ -100,17 +97,17 @@ //Heart rate measurement handler: function (dv){ var flags = dv.getUint8(0); - + var bpm = (flags & 1) ? (dv.getUint16(1) / 100 /* ? */ ) : dv.getUint8(1); // 8 or 16 bit - + var sensorContact; - + if (flags & 2){ sensorContact = !!(flags & 4); } - + var idx = 2 + (flags&1); - + var energyExpended; if (flags & 8){ energyExpended = dv.getUint16(idx,1); @@ -123,7 +120,7 @@ log("Found " + (maxIntervalBytes / 2) + " rr data fields"); for(var i = 0 ; i < maxIntervalBytes / 2; i++){ interval[i] = dv.getUint16(idx,1); // in milliseconds - idx += 2 + idx += 2; } } @@ -143,7 +140,7 @@ confidence: (sensorContact || sensorContact === undefined)? 100 : 0, src: "bthrm" }; - + log("Emitting HRM: ", repEvent); Bangle.emit("HRM", repEvent); } @@ -151,7 +148,7 @@ var newEvent = { bpm: bpm }; - + if (location) newEvent.location = location; if (interval) newEvent.rr = interval; if (energyExpended) newEvent.energy = energyExpended; @@ -183,7 +180,7 @@ var characteristics = []; var blockInit = false; var currentRetryTimeout; - var initialRetryTime = 1000; + var initialRetryTime = 40; var maxRetryTime = 60000; var retryTime = initialRetryTime; @@ -192,7 +189,7 @@ maxInterval: 1500 }; - function waitingPromise(timeout) { + var waitingPromise = function(timeout) { return new Promise(function(resolve){ log("Start waiting for " + timeout); setTimeout(()=>{ @@ -200,7 +197,7 @@ resolve(); }, timeout); }); - } + }; if (settings.enabled){ Bangle.isBTHRMOn = function(){ @@ -225,15 +222,15 @@ }; } - function clearRetryTimeout(){ + var clearRetryTimeout = function() { if (currentRetryTimeout){ log("Clearing timeout " + currentRetryTimeout); clearTimeout(currentRetryTimeout); currentRetryTimeout = undefined; } - } + }; - function retry(){ + var retry = function() { log("Retry"); if (!currentRetryTimeout){ @@ -255,10 +252,10 @@ } else { log("Already in retry..."); } - } + }; var buzzing = false; - function onDisconnect(reason) { + var onDisconnect = function(reason) { log("Disconnect: " + reason); log("GATT: ", gatt); log("Characteristics: ", characteristics); @@ -273,9 +270,9 @@ if (Bangle.isBTHRMOn()){ retry(); } - } + }; - function createCharacteristicPromise(newCharacteristic){ + var createCharacteristicPromise = function(newCharacteristic) { log("Create characteristic promise: ", newCharacteristic); var result = Promise.resolve(); // For values that can be read, go ahead and read them, even if we might be notified in the future @@ -298,23 +295,23 @@ log("Add " + settings.gracePeriodNotification + "ms grace period after starting notifications"); startPromise = startPromise.then(()=>{ log("Wait after connect"); - waitingPromise(settings.gracePeriodNotification) + return waitingPromise(settings.gracePeriodNotification); }); } return startPromise; }); } return result.then(()=>log("Handled characteristic: ", newCharacteristic)); - } + }; - function attachCharacteristicPromise(promise, characteristic){ + var attachCharacteristicPromise = function(promise, characteristic) { return promise.then(()=>{ log("Handling characteristic:", characteristic); return createCharacteristicPromise(characteristic); }); - } + }; - function createCharacteristicsPromise(newCharacteristics){ + var createCharacteristicsPromise = function(newCharacteristics) { log("Create characteristics promise: ", newCharacteristics); var result = Promise.resolve(); for (var c of newCharacteristics){ @@ -328,9 +325,9 @@ result = attachCharacteristicPromise(result, c); } return result.then(()=>log("Handled characteristics")); - } + }; - function createServicePromise(service){ + var createServicePromise = function(service) { log("Create service promise: ", service); var result = Promise.resolve(); result = result.then(()=>{ @@ -338,15 +335,13 @@ return service.getCharacteristics().then((c)=>createCharacteristicsPromise(c)); }); return result.then(()=>log("Handled service" + service.uuid)); - } + }; - function attachServicePromise(promise, service){ + var attachServicePromise = function(promise, service) { return promise.then(()=>createServicePromise(service)); - } + }; - var reUseCounter = 0; - - function initBt() { + var initBt = function () { log("initBt with blockInit: " + blockInit); if (blockInit){ retry(); @@ -355,19 +350,15 @@ blockInit = true; - if (reUseCounter > 10){ - log("Reuse counter to high"); - gatt=undefined; - reUseCounter = 0; - } - var promise; + var filters; if (!device){ - var filters = serviceFilters; if (settings.btid){ log("Configured device id", settings.btid); - filters = [{id: settings.btid }]; + filters = [{ id: settings.btid }]; + } else { + return; } log("Requesting device with filters", filters); promise = NRF.requestDevice({ filters: filters, active: true }); @@ -397,13 +388,13 @@ } else { log("GATT is new: ", gatt); characteristics = []; - var cachedName = getCache().name; - if (device.name !== cachedName){ - log("Device name changed from " + cachedName + " to " + device.name + ", clearing cache"); + var cachedId = getCache().id; + if (device.id !== cachedId){ + log("Device ID changed from " + cachedId + " to " + device.id + ", clearing cache"); clearCache(); } var newCache = getCache(); - newCache.name = device.name; + newCache.id = device.id; writeCache(newCache); gatt = device.gatt; } @@ -465,7 +456,7 @@ log("Add " + settings.gracePeriodService + "ms grace period after services"); result = result.then(()=>{ log("Wait after services"); - return waitingPromise(settings.gracePeriodService) + return waitingPromise(settings.gracePeriodService); }); } return result; @@ -478,10 +469,9 @@ return characteristicsPromise; }); - + return promise.then(()=>{ log("Connection established, waiting for notifications"); - reUseCounter = 0; characteristicsToCache(characteristics); clearRetryTimeout(); }).catch((e) => { @@ -489,7 +479,7 @@ log("Error:", e); onDisconnect(e); }); - } + }; Bangle.setBTHRMPower = function(isOn, app) { // Do app power handling @@ -538,7 +528,7 @@ var fallbackInterval; - function switchInternalHrm(){ + var switchInternalHrm = function() { if (settings.allowFallback && !fallbackInterval){ log("Fallback to HRM enabled"); origSetHRMPower(1, "bthrm_fallback"); @@ -551,7 +541,7 @@ } }, settings.fallbackTimeout); } - } + }; if (settings.replace){ log("Replace HRM event"); diff --git a/apps/bthrm/metadata.json b/apps/bthrm/metadata.json index b35ebd6af..faff72d0f 100644 --- a/apps/bthrm/metadata.json +++ b/apps/bthrm/metadata.json @@ -6,7 +6,7 @@ "description": "Overrides Bangle.js's build in heart rate monitor with an external Bluetooth one.", "icon": "app.png", "type": "app", - "tags": "health,bluetooth", + "tags": "health,bluetooth,hrm", "supports": ["BANGLEJS","BANGLEJS2"], "readme": "README.md", "storage": [ From ab11b7068115b6678d69e70c21b7787bba778ece Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 19 Apr 2022 16:54:27 -0500 Subject: [PATCH 12/14] Default custom values to the same as default mode so you can choose which pieces to change knowing the rest is the same --- apps/bthrm/default.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/bthrm/default.json b/apps/bthrm/default.json index 64e638b8a..fb284bcd2 100644 --- a/apps/bthrm/default.json +++ b/apps/bthrm/default.json @@ -7,10 +7,10 @@ "allowFallback": true, "warnDisconnect": false, "fallbackTimeout": 10, - "custom_replace": false, + "custom_replace": true, "custom_debuglog": false, - "custom_startWithHrm": false, - "custom_allowFallback": false, + "custom_startWithHrm": true, + "custom_allowFallback": true, "custom_warnDisconnect": false, "custom_fallbackTimeout": 10, "gracePeriodNotification": 0, From dbecd1ae6f009220f84b989d2bfc3666ebf27ca2 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 19 Apr 2022 16:54:50 -0500 Subject: [PATCH 13/14] Adding tag to find 'hrm' more easily --- apps/bthrm/metadata.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/bthrm/metadata.json b/apps/bthrm/metadata.json index faff72d0f..85c19ab33 100644 --- a/apps/bthrm/metadata.json +++ b/apps/bthrm/metadata.json @@ -6,7 +6,7 @@ "description": "Overrides Bangle.js's build in heart rate monitor with an external Bluetooth one.", "icon": "app.png", "type": "app", - "tags": "health,bluetooth,hrm", + "tags": "health,bluetooth,hrm,bthrm", "supports": ["BANGLEJS","BANGLEJS2"], "readme": "README.md", "storage": [ From 650d2bd288e47bbf95f94aef62949ad22aefdd32 Mon Sep 17 00:00:00 2001 From: Salim Blume Date: Tue, 19 Apr 2022 16:55:04 -0500 Subject: [PATCH 14/14] Scaled retryTime for clampedTime instead of itself --- apps/bthrm/boot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/bthrm/boot.js b/apps/bthrm/boot.js index 064f65eac..e9e640563 100644 --- a/apps/bthrm/boot.js +++ b/apps/bthrm/boot.js @@ -245,7 +245,7 @@ initBt(); }, clampedTime); - retryTime = Math.pow(retryTime, 1.1); + retryTime = Math.pow(clampedTime, 1.1); if (retryTime > maxRetryTime){ retryTime = maxRetryTime; }