Broadcast rpm to socket server from mobile web

This commit is contained in:
Peter Stockings
2023-01-26 15:36:36 +11:00
parent 8c49dea474
commit eae0d264cc
2 changed files with 44 additions and 9 deletions

View File

@@ -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;