diff --git a/static/js/BLE.js b/static/js/BLE.js index baae75a..1315105 100644 --- a/static/js/BLE.js +++ b/static/js/BLE.js @@ -1,3 +1,7 @@ +let socket = null; +let characteristic = null; +let prevRes = null; + function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } @@ -13,10 +17,35 @@ async function connect(props) { console.log("Getting Service..."); const service = await server.getPrimaryService("cycling_speed_and_cadence"); console.log("Getting Characteristic..."); - const characteristic = await service.getCharacteristic("csc_measurement"); + characteristic = await service.getCharacteristic("csc_measurement"); await characteristic.startNotifications(); console.log("> Notifications started"); characteristic.addEventListener("characteristicvaluechanged", props.onChange); + console.log("> Characteristic value changed event listener added"); + socket = io(); + + socket.on("disconnect", (reason) => { + if (reason === "io server disconnect") { + // the disconnection was initiated by the server, you need to reconnect manually + socket.connect(); + } + // else the socket will automatically try to reconnect + }); +} + +async function disconnect() { + if (characteristic) { + try { + await characteristic.stopNotifications(); + log("> Notifications stopped"); + characteristic.removeEventListener( + "characteristicvaluechanged", + handleNotifications + ); + } catch (error) { + log("Argh! " + error); + } + } } function parseCSC(e) { @@ -44,21 +73,23 @@ function parseCSC(e) { index += 2; } console.log("CSC", res); - const pre = document.createElement("pre"); - pre.style.border = "1px solid red"; - pre.textContent = JSON.stringify(res, null, 2); - document.body.appendChild(pre); + if (prevRes) { + let rpm = revsToRPM(prevRes, res); + if (rpm > 0) + socket.emit("message", { rpm: parseFloat(rpm.toFixed(2)), id: 1 }); + } + prevRes = res; return res; } -function revsToRPM(t1, t2) { - const deltaRevs = t2.revs - t1.revs; +function revsToRPM(prevRes, res) { + const deltaRevs = res.crankRevs - prevRes.crankRevs; if (deltaRevs === 0) { // no rotation return 0; } - let deltaTime = (t2.time - t1.time) / 1024; + let deltaTime = (res.crankTime - prevRes.crankTime) / 1024; if (deltaTime < 0) { // time counter wraparound deltaTime += Math.pow(2, 16) / 1024; diff --git a/templates/base.html b/templates/base.html index 4f7b76b..0fb3d1b 100644 --- a/templates/base.html +++ b/templates/base.html @@ -6,7 +6,8 @@