Skip to content

Commit

Permalink
Fix cadence accuracy.
Browse files Browse the repository at this point in the history
There are two issues here. The first and main issue is that the cadence
value reported by Zwift and other apps was 4.8576% higher than actual.
The root cause is the conversion from milliseconds to 1/1024ths was
using the wrong (inverted) scale. The second issue is flapping, i.e.
when using bot mode set to 100 rpm, we expect Zwift to report exactly
100 rpm but it flaps between 99rpm and 100rpm. The root cause is the
crank revolution timestamps were being calculated using the system clock
on every simulated pedal stroke which is subject to some amount of
jitter. The fix is to simply calculate each crank revolution timestamp
from the previous one, by adding the current cadence interval to it.

Co-authored-by: Jeremy Klein <[email protected]>
  • Loading branch information
ptx2 and jeremydk committed Sep 20, 2020
1 parent 9fe1e09 commit f807cb4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
10 changes: 6 additions & 4 deletions src/app/simulation.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export class Simulation extends EventEmitter {
* @emits Simulation#pedal
* @private
*/
onPedal() {
this._lastPedalTime = Date.now();
onPedal(timestamp) {
this._lastPedalTime = Number.isFinite(timestamp) ? timestamp : Date.now();
/**
* Pedal event.
* @event Simulation#pedal
Expand All @@ -56,10 +56,12 @@ export class Simulation extends EventEmitter {
schedulePedal() {
if (this._interval === Infinity) return;

let timeSinceLast = Date.now() - this._lastPedalTime;
let now = Date.now();
let timeSinceLast = now - this._lastPedalTime;
let timeUntilNext = Math.max(0, this._interval - timeSinceLast);
let nextPedalTime = now - timeSinceLast + this._interval;
this._timeoutId = setTimeout(() => {
this.onPedal();
this.onPedal(nextPedalTime);
this.schedulePedal();
}, timeUntilNext);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Characteristic, Descriptor} from '@abandonware/bleno';

const FLAG_HASCRANKDATA = (1<<5);
const CRANK_TIMESTAMP_SCALE = 1000 / 1024; // timestamp resolution is 1/1024 sec
const CRANK_TIMESTAMP_SCALE = 1024 / 1000; // timestamp resolution is 1/1024 sec

/**
* Bluetooth LE GATT Cycling Power Measurement Characteristic implementation.
Expand Down Expand Up @@ -41,7 +41,7 @@ export class CyclingPowerMeasurementCharacteristic extends Characteristic {
// include crank data if provided
if (crank) {
const revolutions16bit = crank.revolutions & 0xffff;
const timestamp16bit = Math.floor(crank.timestamp * CRANK_TIMESTAMP_SCALE) & 0xffff;
const timestamp16bit = Math.round(crank.timestamp * CRANK_TIMESTAMP_SCALE) & 0xffff;
value.writeUInt16LE(revolutions16bit, 4);
value.writeUInt16LE(timestamp16bit, 6);
flags |= FLAG_HASCRANKDATA;
Expand Down

0 comments on commit f807cb4

Please sign in to comment.