Attempt to use web bluetooth from chrome mobile to stream cadence rather then dedicated hardware

This commit is contained in:
Peter Stockings
2023-01-26 12:06:26 +11:00
parent e7087aedbb
commit c507d879e7
2 changed files with 78 additions and 0 deletions

68
static/js/BLE.js Normal file
View File

@@ -0,0 +1,68 @@
async function connect(props) {
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ["cycling_speed_and_cadence"] }],
acceptAllDevices: false,
});
console.log(`%c\n👩🏼‍⚕️`, "font-size: 82px;", "Starting CSC...\n\n");
const server = await device.gatt.connect();
const service = await server.getPrimaryService("cycling_speed_and_cadence");
const char = await service.getCharacteristic("csc_measurement");
char.oncharacteristicvaluechanged = props.onChange;
char.startNotifications();
return char;
}
function parseCSC({ value }) {
const flags = value.getUint8(0, true);
const hasWheel = !!(flags & 0x01);
const hasCrank = !!(flags & 0x02);
let index = 1;
const res = {
wheelRevs: null,
wheelTime: null,
crankRevs: null,
crankTime: null,
};
if (hasWheel) {
res.wheelRevs = value.getUint32(index, true);
index += 4;
res.wheelTime = value.getUint16(index, true);
index += 2;
}
if (hasCrank) {
res.crankRevs = value.getUint16(index, true);
index += 2;
res.crankTime = value.getUint16(index, true);
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);
return res;
}
function revsToRPM(t1, t2) {
const deltaRevs = t2.revs - t1.revs;
if (deltaRevs === 0) {
// no rotation
return 0;
}
let deltaTime = (t2.time - t1.time) / 1024;
if (deltaTime < 0) {
// time counter wraparound
deltaTime += Math.pow(2, 16) / 1024;
}
deltaTime /= 60; // seconds to minutes
const rpm = deltaRevs / deltaTime;
return rpm;
}
document.querySelector("#ble-connect").addEventListener("click", () =>
connect({
onChange: parseCSC,
}).catch(console.error)
);

View File

@@ -51,8 +51,18 @@
</div>
</div>
</div>
<button
class="p-0 w-16 h-16 bg-red-600 rounded-full hover:bg-red-700 active:shadow-lg mouse shadow transition ease-in duration-200 focus:outline-none"
id="ble-connect">
<svg viewBox="0 0 20 20" enable-background="new 0 0 20 20" class="w-6 h-6 inline-block">
<path fill="#FFFFFF" d="M16,10c0,0.553-0.048,1-0.601,1H11v4.399C11,15.951,10.553,16,10,16c-0.553,0-1-0.049-1-0.601V11H4.601
C4.049,11,4,10.553,4,10c0-0.553,0.049-1,0.601-1H9V4.601C9,4.048,9.447,4,10,4c0.553,0,1,0.048,1,0.601V9h4.399
C15.952,9,16,9.447,16,10z" />
</svg>
</button>
</main>
</div>
<script src="/static/js/BLE.js"></script>
</body>
</html>