├── .gitignore ├── run.sh ├── keiser.service ├── package.json ├── BLE ├── static-read-characteristic.js ├── cycling-power-service.js ├── ftms-service.js ├── fitness-machine-status-characteristic.js ├── indoor-bike-data-characteristic.js ├── cycling-power-measurement-characteristic.js └── keiserBLE.js ├── .vscode └── launch.json ├── index.js ├── keiserParser.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | hciconfig hci0 up 4 | hciconfig hci1 up 5 | /home/pi/.config/nvm/versions/node/v10.22.0/bin/node index.js 6 | 7 | -------------------------------------------------------------------------------- /keiser.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=KeiserM3 3 | After=network.target 4 | 5 | [Service] 6 | ExecStart=/home/pi/code/keiser/run.sh 7 | WorkingDirectory=/home/pi/code/keiser 8 | Type=idle 9 | Restart=always 10 | StandardOutput=syslog 11 | SyslogIdentifier=keiserm3 12 | 13 | [Install] 14 | WantedBy=multi-user.target 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "keiser2zwift", 3 | "version": "1.0.0", 4 | "description": "Adapter for Keiser m3i bikes to Zwift", 5 | "main": "index.js", 6 | "scripts": { 7 | "debug": "node --nolazy --inspect-brk=9229 index.js", 8 | "start": "node index.js" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "@abandonware/bleno": "^0.5.1-2", 14 | "@abandonware/noble": "^1.9.2-9", 15 | "atob": "^2.1.2" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /BLE/static-read-characteristic.js: -------------------------------------------------------------------------------- 1 | const Bleno = require('@abandonware/bleno'); 2 | 3 | class StaticReadCharacteristic extends Bleno.Characteristic { 4 | constructor(uuid, description, value) { 5 | super({ 6 | uuid: uuid, 7 | properties: ['read'], 8 | value: null, 9 | descriptors: [ 10 | new Bleno.Descriptor({ 11 | uuid: '2901', 12 | value: description 13 | }) 14 | ] 15 | }); 16 | this.uuid = uuid; 17 | this.description = description; 18 | this._value = Buffer.isBuffer(value) ? value : new Buffer(value); 19 | } 20 | 21 | onReadRequest(offset, callback) { 22 | console.log('OnReadRequest : ' + this.description); 23 | callback(this.RESULT_SUCCESS, this._value.slice(offset, this._value.length)); 24 | }; 25 | } 26 | 27 | module.exports = StaticReadCharacteristic; -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Attach by Process ID", 9 | "processId": "${command:PickProcess}", 10 | "request": "attach", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "type": "pwa-node" 15 | }, 16 | { 17 | "name": "Launch Program", 18 | "program": "${workspaceFolder}/index.js", 19 | "request": "launch", 20 | "type": "pwa-node", 21 | }, 22 | { 23 | "type": "node", 24 | "name": "Launch via NPM", 25 | "cwd": "${workspaceFolder}", 26 | "request": "launch", 27 | "runtimeExecutable": "npm", 28 | "runtimeArgs": ["run-script", "debug"], 29 | "port": 9229 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /BLE/cycling-power-service.js: -------------------------------------------------------------------------------- 1 | const Bleno = require('@abandonware/bleno'); 2 | 3 | const CyclingPowerMeasurementCharacteristic = require('./cycling-power-measurement-characteristic'); 4 | const StaticReadCharacteristic = require('./static-read-characteristic'); 5 | 6 | // https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.cycling_power.xml 7 | class CyclingPowerService extends Bleno.PrimaryService { 8 | 9 | constructor() { 10 | let powerMeasurement = new CyclingPowerMeasurementCharacteristic(); 11 | super({ 12 | uuid: '1818', 13 | //uuid: '1515', 14 | characteristics: [ 15 | powerMeasurement, 16 | new StaticReadCharacteristic('2A65', 'Cycling Power Feature', [0x08, 0, 0, 0]), // 0x08 - crank revolutions 17 | new StaticReadCharacteristic('2A5D', 'Sensor Location', [13]) // 13 = rear hub 18 | ] 19 | }); 20 | 21 | this.powerMeasurement = powerMeasurement; 22 | } 23 | 24 | notify(event) { 25 | this.powerMeasurement.notify(event); 26 | return this.RESULT_SUCCESS; 27 | }; 28 | } 29 | 30 | module.exports = CyclingPowerService; 31 | -------------------------------------------------------------------------------- /BLE/ftms-service.js: -------------------------------------------------------------------------------- 1 | // Doc: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.service.fitness_machine.xml 2 | const Bleno = require('@abandonware/bleno'); 3 | 4 | const IndoorBikeDataCharacteristic = require('./indoor-bike-data-characteristic'); 5 | const StaticReadCharacteristic = require('./static-read-characteristic'); 6 | const FitnessMachineStatusCharacteristic = require('./fitness-machine-status-characteristic'); 7 | 8 | class FitnessMachineService extends Bleno.PrimaryService { 9 | 10 | constructor() { 11 | 12 | let indoorBikeData = new IndoorBikeDataCharacteristic(); 13 | let fitnessMachineStatus = new FitnessMachineStatusCharacteristic() 14 | 15 | super({ 16 | uuid: '1826', 17 | characteristics: [ 18 | new StaticReadCharacteristic('2ACC', 'Fitness Machine Feature', [0x02, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), // Feature Characteristics 19 | indoorBikeData, 20 | fitnessMachineStatus 21 | ] 22 | }); 23 | 24 | this.indoorBikeData = indoorBikeData; 25 | } 26 | 27 | /* 28 | * Transfer event from Kettler USB to the given characteristics 29 | */ 30 | notify(event) { 31 | this.indoorBikeData.notify(event); 32 | }; 33 | 34 | } 35 | 36 | module.exports = FitnessMachineService; 37 | -------------------------------------------------------------------------------- /BLE/fitness-machine-status-characteristic.js: -------------------------------------------------------------------------------- 1 | const Bleno = require('@abandonware/bleno'); 2 | var DEBUG = false; 3 | 4 | // Spec 5 | // Status op code 6 | var StatusOpCode = { 7 | reservedForFutureUse: 0x00, 8 | reset: 0x01, 9 | stoppedPausedUser: 0x02, 10 | stoppedPausedSyfety: 0x03, 11 | startedResumedUser: 0x04, 12 | targetSpeedChanged: 0x05, 13 | targetInclineChanged: 0x06, 14 | targetResistanceLevelChanged: 0x07, 15 | targetPowerChanged: 0x08, 16 | targetHeartRateChanged: 0x09, 17 | targetExpendedEnergyChanged: 0x0a, 18 | targetNumberStepsChanged: 0x0b, 19 | targetNumberStridesChanged: 0x0c, 20 | targetDistanceChanged: 0x0d, 21 | targetTrainingTimeChanged: 0x0e, 22 | indoorBikeSimulationParametersChanged: 0x12, 23 | wheelCircumferenceChanged: 0x13 24 | } 25 | 26 | class FitnessMachineStatusCharacteristic extends Bleno.Characteristic { 27 | constructor () { 28 | super({ 29 | uuid: '2ADA', 30 | value: null, 31 | properties: ['notify'], 32 | descriptors: [] 33 | }) 34 | this._updateValueCallback = null 35 | } 36 | 37 | onSubscribe (maxValueSize, updateValueCallback) { 38 | if (DEBUG) console.log('[fitness-machine-status-characteristic.js] - client subscribed') 39 | this._updateValueCallback = updateValueCallback 40 | return this.RESULT_SUCCESS 41 | } 42 | 43 | onUnsubscribe () { 44 | if (DEBUG) console.log('[fitness-machine-status-characteristic.js] - client unsubscribed') 45 | this._updateValueCallback = null 46 | return this.RESULT_UNLIKELY_ERROR 47 | } 48 | 49 | notify (event) { 50 | if (DEBUG) console.log('[fitness-machine-status-characteristic.js] - notify') 51 | var buffer = new Buffer.from(2) 52 | // speed + power + heart rate 53 | buffer.writeUInt8(StatusOpCode.startedResumedUser, 0) 54 | 55 | if (this._updateValueCallback) { 56 | this._updateValueCallback(buffer) 57 | } else { 58 | if (DEBUG) console.log('[fitness-machine-status-characteristic.js] - nobody is listening') 59 | } 60 | return this.RESULT_SUCCESS 61 | } 62 | } 63 | 64 | module.exports = FitnessMachineStatusCharacteristic -------------------------------------------------------------------------------- /BLE/indoor-bike-data-characteristic.js: -------------------------------------------------------------------------------- 1 | var Bleno = require('@abandonware/bleno'); 2 | var DEBUG = false; 3 | 4 | class IndoorBikeDataCharacteristic extends Bleno.Characteristic { 5 | 6 | constructor() { 7 | super({ 8 | uuid: '2AD2', 9 | value: null, 10 | properties: ['notify'], 11 | descriptors: [] 12 | }); 13 | this._updateValueCallback = null; 14 | } 15 | 16 | onSubscribe(maxValueSize, updateValueCallback) { 17 | if (DEBUG) console.log('[IndoorBikeDataCharacteristic] client subscribed'); 18 | this._updateValueCallback = updateValueCallback; 19 | return this.RESULT_SUCCESS; 20 | }; 21 | 22 | onUnsubscribe() { 23 | if (DEBUG) console.log('[IndoorBikeDataCharacteristic] client unsubscribed'); 24 | this._updateValueCallback = null; 25 | return this.RESULT_UNLIKELY_ERROR; 26 | }; 27 | 28 | notify(event) { 29 | if (!('power' in event) && !('hr' in event)) { 30 | // ignore events with no power and no hr data 31 | return this.RESULT_SUCCESS; 32 | } 33 | 34 | if (this._updateValueCallback) { 35 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] Notify"); 36 | var buffer = new Buffer(10); 37 | // speed + power + heart rate 38 | buffer.writeUInt8(0x44, 0); 39 | buffer.writeUInt8(0x02, 1); 40 | 41 | var index = 2; 42 | if ('speed' in event) { 43 | var speed = parseInt(event.speed); 44 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] speed: " + speed); 45 | buffer.writeInt16LE(speed, index); 46 | index += 2; 47 | } 48 | 49 | if ('rpm' in event) { 50 | var rpm = event.rpm; 51 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] rpm: " + rpm); 52 | buffer.writeInt16LE(rpm * 2, index); 53 | index += 2; 54 | } 55 | 56 | if ('power' in event) { 57 | var power = event.power; 58 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] power: " + power); 59 | buffer.writeInt16LE(power, index); 60 | index += 2; 61 | } 62 | 63 | if ('hr' in event) { 64 | var hr = event.hr; 65 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] hr : " + hr); 66 | buffer.writeUInt16LE(hr, index); 67 | index += 2; 68 | } 69 | this._updateValueCallback(buffer); 70 | } 71 | else 72 | { 73 | if (DEBUG) console.log("[IndoorBikeDataCharacteristic] nobody is listening"); 74 | } 75 | return this.RESULT_SUCCESS; 76 | } 77 | 78 | }; 79 | 80 | module.exports = IndoorBikeDataCharacteristic; 81 | -------------------------------------------------------------------------------- /BLE/cycling-power-measurement-characteristic.js: -------------------------------------------------------------------------------- 1 | 2 | var Bleno = require('@abandonware/bleno'); 3 | var DEBUG = false; 4 | 5 | // Spec 6 | //https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.cycling_power_measurement.xml 7 | 8 | class CyclingPowerMeasurementCharacteristic extends Bleno.Characteristic { 9 | 10 | constructor() { 11 | super({ 12 | uuid: '2A63', 13 | value: null, 14 | properties: ['notify'], 15 | descriptors: [ 16 | new Bleno.Descriptor({ 17 | uuid: '2901', 18 | value: 'Cycling Power Measurement' 19 | }), 20 | new Bleno.Descriptor({ 21 | // Server Characteristic Configuration 22 | uuid: '2903', 23 | value: Buffer.alloc(2) 24 | }) 25 | ] 26 | }); 27 | this._updateValueCallback = null; 28 | } 29 | 30 | onSubscribe(maxValueSize, updateValueCallback) { 31 | if (DEBUG) console.log('[powerService] client subscribed to PM'); 32 | this._updateValueCallback = updateValueCallback; 33 | return this.RESULT_SUCCESS; 34 | }; 35 | 36 | onUnsubscribe() { 37 | if (DEBUG) console.log('[powerService] client unsubscribed from PM'); 38 | this._updateValueCallback = null; 39 | return this.RESULT_UNLIKELY_ERROR; 40 | }; 41 | 42 | notify(event) { 43 | if (!('power' in event) && !('rpm' in event)) { 44 | // ignore events with no power and no crank data 45 | return this.RESULT_SUCCESS;; 46 | } 47 | 48 | if (this._updateValueCallback) { 49 | if (DEBUG) console.log("[powerService] Notify"); 50 | var buffer = new Buffer(8); 51 | // flags 52 | // 00000001 - 1 - 0x001 - Pedal Power Balance Present 53 | // 00000010 - 2 - 0x002 - Pedal Power Balance Reference 54 | // 00000100 - 4 - 0x004 - Accumulated Torque Present 55 | // 00001000 - 8 - 0x008 - Accumulated Torque Source 56 | // 00010000 - 16 - 0x010 - Wheel Revolution Data Present 57 | // 00100000 - 32 - 0x020 - Crank Revolution Data Present 58 | // 01000000 - 64 - 0x040 - Extreme Force Magnitudes Present 59 | // 10000000 - 128 - 0x080 - Extreme Torque Magnitudes Present 60 | 61 | buffer.writeUInt16LE(0x0000, 0); 62 | 63 | if ('power' in event) { 64 | var power = event.power; 65 | if (DEBUG) console.log("[powerService] power: " + power); 66 | buffer.writeInt16LE(power, 2); 67 | } 68 | 69 | if ('rpm' in event) { 70 | var rpm = event.rpm; 71 | if (DEBUG) console.log("[powerService] rpm: " + event.rpm); 72 | buffer.writeUInt16LE(rpm * 2, 4); 73 | } 74 | this._updateValueCallback(buffer); 75 | } 76 | return this.RESULT_SUCCESS; 77 | } 78 | 79 | 80 | }; 81 | 82 | module.exports = CyclingPowerMeasurementCharacteristic; 83 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | // Setup multi role support and two different adapters for Peripheral and Central 2 | process.env['NOBLE_MULTI_ROLE'] = 1 3 | process.env['NOBLE_REPORT_ALL_HCI_EVENTS'] = 1 4 | process.env['BLENO_HCI_DEVICE_ID'] = 0 5 | process.env['NOBLE_HCI_DEVICE_ID'] = 1 6 | 7 | const noble = require('@abandonware/noble'); 8 | const keiserParser = require('./keiserParser.js') 9 | const KeiserBLE = require('./BLE/keiserBLE') 10 | 11 | var fillInTimer = null; 12 | var dataToSend = null; 13 | var connectedCount = 0; 14 | var targetDeviceId = -1; 15 | 16 | console.log("Starting"); 17 | 18 | var keiserBLE = new KeiserBLE(); 19 | 20 | keiserBLE.on('advertisingStart', (client) => { 21 | //oled.displayBLE('Started'); 22 | }); 23 | keiserBLE.on('accept', (client) => { 24 | connectedCount++; 25 | //oled.displayBLE('Connected'); 26 | }); 27 | keiserBLE.on('disconnect', (client) => { 28 | connectedCount--; 29 | //oled.displayBLE('Disconnected'); 30 | }); 31 | 32 | noble.on('stateChange', async (state) => { 33 | console.log(`[Central] State changed to ${state}`); 34 | if (state === 'poweredOn') { 35 | console.log(`[Central] starting scan`); 36 | await noble.startScanningAsync(null, true); 37 | } else if (state === 'poweredOff') { 38 | console.log('No adapter detected, exiting in 5 seconds'); 39 | setTimeout(() => { 40 | process.exit(); 41 | }, 5000); 42 | } 43 | }); 44 | 45 | function sendFillInData() { 46 | if (!dataToSend || (connectedCount < 1)) { 47 | console.log("Aborting nothing to send"); 48 | } 49 | 50 | console.log("Sending fill in data"); 51 | keiserBLE.notifyFTMS(dataToSend); 52 | fillInTimer = setTimeout(sendFillInData, 1000); 53 | } 54 | 55 | noble.on('discover', (peripheral) => { 56 | 57 | //console.log(`[Central] Found device ${peripheral.advertisement.localName} ${peripheral.address}`); 58 | if (peripheral.advertisement.localName == "M3") 59 | { 60 | try 61 | { 62 | var result = keiserParser.parseAdvertisement(peripheral); 63 | if (targetDeviceId == -1) { 64 | if (result.realTime) { 65 | console.log(`Attaching to bike id ${result.ordinalId}`); 66 | targetDeviceId = result.ordinalId; 67 | keiserBLE.setDeviceId(targetDeviceId); 68 | } else { 69 | return; 70 | } 71 | } 72 | 73 | if (result.ordinalId == targetDeviceId) { 74 | console.log(`Bike ${result.ordinalId}: ${result.realTime} ${result.cadence} ${result.power} ${result.gear} ${result.duration}`); 75 | if (result.realTime) { 76 | dataToSend = { 77 | rpm: result.cadence, 78 | power: result.power, 79 | hr: result.heartRate, 80 | speed: result.cadence * .73 // 30 cog 34 cassette for now 81 | }; 82 | if (fillInTimer) { 83 | clearTimeout(fillInTimer); 84 | fillInTimer = null; 85 | } 86 | 87 | if (connectedCount > 0) { 88 | keiserBLE.notifyFTMS(dataToSend); 89 | fillInTimer = setTimeout(sendFillInData, 1000); 90 | } 91 | } 92 | } 93 | } 94 | catch (err) { 95 | console.log(`\tError parsing: ${err}`); 96 | console.log(`\t ${err.stack}`); 97 | } 98 | } 99 | }); 100 | -------------------------------------------------------------------------------- /BLE/keiserBLE.js: -------------------------------------------------------------------------------- 1 | const bleno = require('@abandonware/bleno'); 2 | const EventEmitter = require('events'); 3 | const CyclingPowerService = require('./cycling-power-service'); 4 | const FitnessMachineService = require('./ftms-service'); 5 | 6 | var keiserDeviceId = -1; 7 | var isPoweredOn = false; 8 | 9 | class KeiserBLE extends EventEmitter { 10 | 11 | constructor() { 12 | super(); 13 | 14 | this.setName(); 15 | 16 | this.csp = new CyclingPowerService(); 17 | this.ftms = new FitnessMachineService(); 18 | 19 | let self = this; 20 | console.log(`[${this.name} starting]`); 21 | 22 | bleno.on('stateChange', (state) => { 23 | console.log(`[${this.name} stateChange] new state: ${state}`); 24 | 25 | self.emit('stateChange', state); 26 | 27 | if (state === 'poweredOn') { 28 | isPoweredOn = true; 29 | this.checkStartConditions(); 30 | } else { 31 | console.log('Stopping...'); 32 | isPoweredOn = false; 33 | bleno.stopAdvertising(); 34 | } 35 | }); 36 | 37 | bleno.on('advertisingStart', (error) => { 38 | console.log(`[${this.name} advertisingStart] ${(error ? 'error ' + error : 'success')}`); 39 | self.emit('advertisingStart', error); 40 | 41 | if (!error) { 42 | bleno.setServices([self.csp 43 | , self.ftms 44 | ], 45 | (error) => { 46 | console.log(`[${this.name} setServices] ${(error ? 'error ' + error : 'success')}`); 47 | }); 48 | } 49 | }); 50 | 51 | bleno.on('advertisingStartError', () => { 52 | console.log(`[${this.name} advertisingStartError] advertising stopped`); 53 | self.emit('advertisingStartError'); 54 | }); 55 | 56 | bleno.on('advertisingStop', error => { 57 | console.log(`[${this.name} advertisingStop] ${(error ? 'error ' + error : 'success')}`); 58 | self.emit('advertisingStop'); 59 | }); 60 | 61 | bleno.on('servicesSet', error => { 62 | console.log(`[${this.name} servicesSet] ${ (error) ? 'error ' + error : 'success'}`); 63 | }); 64 | 65 | bleno.on('accept', (clientAddress) => { 66 | console.log(`[${this.name} accept] Client: ${clientAddress}`); 67 | self.emit('accept', clientAddress); 68 | bleno.updateRssi(); 69 | }); 70 | 71 | bleno.on('disconnect', (clientAddress) => { 72 | console.log(`[${this.name} disconnect] Client: ${clientAddress}`); 73 | self.emit('disconnect', clientAddress); 74 | }); 75 | 76 | bleno.on('rssiUpdate', (rssi) => { 77 | console.log(`[${this.name} rssiUpdate]: ${rssi}`); 78 | }); 79 | 80 | } 81 | 82 | // notifiy BLE services 83 | notifyFTMS(event) { 84 | this.csp.notify(event); 85 | this.ftms.notify(event); 86 | }; 87 | 88 | setDeviceId(deviceId) { 89 | keiserDeviceId = deviceId; 90 | this.setName(); 91 | this.checkStartConditions(); 92 | } 93 | 94 | setName() { 95 | if (keiserDeviceId == -1) { 96 | this.name = "KeiserM3"; 97 | } else { 98 | this.name = "KeiserM3-" + keiserDeviceId; 99 | } 100 | 101 | process.env['BLENO_DEVICE_NAME'] = this.name; 102 | } 103 | 104 | checkStartConditions() { 105 | if (isPoweredOn && keiserDeviceId != -1) { 106 | bleno.startAdvertising(this.name, [this.csp.uuid 107 | , this.ftms.uuid 108 | ]); 109 | } 110 | } 111 | }; 112 | 113 | module.exports = KeiserBLE; -------------------------------------------------------------------------------- /keiserParser.js: -------------------------------------------------------------------------------- 1 | global.atob = require("atob"); 2 | 3 | const encodeStringToBytes = (rawString) => { 4 | let data = atob(rawString) 5 | let bytes = new Uint8Array(data.length) 6 | for (let i = 0; i < bytes.length; i++) { 7 | bytes[i] = data.charCodeAt(i) 8 | } 9 | return bytes 10 | } 11 | 12 | const getAdvertisingData = (response) => { 13 | let advertisingData; 14 | if (typeof response.advertisement !== 'string') { 15 | let advertisement = encodeStringToBytes(response.advertisement.manufacturerData) 16 | advertisingData = [].slice.call(advertisement, 2) 17 | } else { 18 | let advertisement = encodeStringToBytes(response.advertisement) 19 | if (advertisement.length > 17) { 20 | advertisingData = [].slice.call(advertisement, 11) 21 | } else { 22 | advertisingData = Array.from(advertisement) 23 | } 24 | } 25 | return advertisingData 26 | } 27 | 28 | const buildValueConvert = (value) => { 29 | return parseInt(value.toString(16), 10) 30 | } 31 | 32 | const twoByteConcat = (lower, higher) => { 33 | return (higher << 8) | lower 34 | } 35 | 36 | var parseAdvertisement = function(response) { 37 | let data = getAdvertisingData(response) 38 | let broadcast = { 39 | takenAt: (new Date()).getTime(), 40 | ordinalId: 0, 41 | buildMajor: 0, 42 | buildMinor: 0, 43 | interval: 0, 44 | realTime: false, 45 | cadence: 0, 46 | heartRate: 0, 47 | power: 0, 48 | caloricBurn: 0, 49 | duration: 0, 50 | gear: null, 51 | distance: 0 52 | } 53 | 54 | let index = 0 55 | 56 | broadcast.buildMajor = buildValueConvert(data[index++]) 57 | if (broadcast.buildMajor !== 6) { 58 | throw new Error('Invalid build major') 59 | } 60 | broadcast.buildMinor = buildValueConvert(data[index++]) 61 | 62 | if (broadcast.buildMajor === 6 && data.length > (index + 13)) { 63 | let dataType = data[index] 64 | if (dataType === 0 || dataType === 255) { 65 | broadcast.interval = 0 66 | } else if (dataType > 128 && dataType < 255) { 67 | broadcast.interval = dataType - 128 68 | } 69 | broadcast.realTime = dataType === 0 || (dataType > 128 && dataType < 255) 70 | 71 | broadcast.ordinalId = data[index + 1] 72 | if (broadcast.ordinalId < 0 || broadcast.ordinalId > 200) { 73 | throw new Error('Invalid machine id') 74 | } 75 | 76 | broadcast.cadence = Math.round(twoByteConcat(data[index + 2], data[index + 3]) / 10) 77 | broadcast.heartRate = Math.round(twoByteConcat(data[index + 4], data[index + 5]) / 10) || null 78 | broadcast.power = twoByteConcat(data[index + 6], data[index + 7]) 79 | broadcast.caloricBurn = twoByteConcat(data[index + 8], data[index + 9]) 80 | broadcast.duration = data[index + 10] * 60 + data[index + 11] 81 | 82 | broadcast.distance = twoByteConcat(data[index + 12], data[index + 13]) 83 | if ((broadcast.distance & 32768) !== 0) { 84 | // Metric 85 | broadcast.distance = broadcast.distance / 10 86 | } else { 87 | // Imperial (to Metric) 88 | broadcast.distance = ((broadcast.distance & 32767) / 10) * 1.60934 89 | } 90 | 91 | if (broadcast.buildMinor >= 21 && data.length > (index + 14)) { 92 | broadcast.gear = data[index + 14] 93 | } 94 | } 95 | 96 | return broadcast 97 | } 98 | 99 | module.exports.parseAdvertisement = parseAdvertisement -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Keiser2Zwift 2 | 3 | Use your Keiser M3 bike with apps like Zwift without buying a converter from Keiser which never really worked for me. This project was built to use make use of a Raspberry pi 4 | with 2 bluetooth adapters. Other systems may work but your on your own to get it setup. Two bluetooth adapters are required to make this work. I use the built in one on a Raspberry Pi 3/4 or the Pi Zero W 5 | and an additional one plugged into the usb port. The steps to install are below. 6 | 7 | # USB bluetooth adapters known to work 8 | Any one available from Amazon with linux support should work but I have tried these: 9 | - https://www.amazon.com/gp/product/B0775YF36R/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1 10 | - https://www.amazon.com/IOGEAR-Bluetooth-Micro-Adapter-GBU521/dp/B007GFX0PY/ref=sr_1_1?dchild=1&keywords=iogear+bluetooth&qid=1599502460&s=electronics&sr=1-1 11 | 12 | # Installation 13 | 1. Setup your Pi with Raspbian or Raspbian Lite. https://www.raspberrypi.org/downloads/ 14 | 2. Disable the default bluetooth service. Note that I actually move the file to a backup location to make sure it doesnt come back after a reboot. 15 | * ```sudo systemctl stop bluetooth``` 16 | * ```sudo systemctl disable bluetooth``` 17 | * ```sudo mv /usr/lib/bluetoothd bluetoothd.bak``` 18 | 3. Install the development requirements 19 | * ```sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev``` 20 | 4. Install NVVM to manager Node.js versions (Make sure to close and reopen your shell after this step) 21 | * ```curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash``` 22 | 5. Install the latest binary build of Node.js to support Pis (anything newer and your need to spend a lot time with building it) 23 | * ```nvm install 10.22.0``` 24 | 6. Download this repo or clone it locally. I put it in a directory off the home folder for pi called /home/pi/code/keiser 25 | 7. Go to that directory and run 26 | * ```npm install``` 27 | 8. Make sure both bluetooth adapters are connected and issues the following two commands 28 | * ```sudo hciconfig hci0 up``` 29 | * ```sudo hciconfig hci1 up``` 30 | 9. Verify that you see two devices when you run: 31 | * ``` hcitool dev``` 32 | 10. Start this project manually as root. You should see log messages that indicate its looking for an M3i. 33 | * ``` sudo npm start``` 34 | 11. Wake up your bike and do a few revolutions of the pedals. You should see log messages indicating that its connected to that bike 35 | 12. Launch Zwift and connect to the Power meter whose name starts with KeiserM3-. Then connect to the Cadence sensor. Enjoy 36 | 37 | ### Running without root/sudo 38 | 39 | Run the following command: 40 | 41 | ```sh 42 | sudo setcap cap_net_raw+eip $(eval readlink -f `which node`) 43 | ``` 44 | 45 | This grants the ```node``` binary ```cap_net_raw``` privileges, so it can start/stop BLE advertising. 46 | 47 | __Note:__ The above command requires ```setcap``` to be installed, it can be installed using the following: 48 | 49 | * apt: ```sudo apt-get install libcap2-bin``` 50 | * yum: ```su -c \'yum install libcap2-bin\'``` 51 | 52 | 53 | # Setting up to always run 54 | You can setup the program to run at Pi boot time by doing the following steps: 55 | 1. Edit the keiser.service file in the root of this project to change the path if you didnt take my suggestion. 56 | 2. Copy the service definition into the correct location 57 | * ```sudo cp keiser.service /etc/systemd/system``` 58 | 3. Enable the service 59 | * ```sudo systemctl enable keiser``` 60 | 4. Start the service (Make sure you aren't still manually running the project using npm) 61 | * ```sudo systemctl start keiser``` 62 | 5. Verify it started 63 | * ```systemctl status keiser``` 64 | 6. Reboot the system and verify that the service started automatically using step 5 65 | 66 | # Issues with USB adapters at system boot 67 | Several people have reported issues at system boot with both adapters being recognized. A known work around by @djwasser is described in issue: https://github.com/hypermoose/Keiser2Zwift/issues/2 68 | 69 | 70 | # Thanks 71 | I leveraged several other great projects to build this. They are: 72 | - Bleno: https://github.com/abandonware/bleno 73 | - Noble: https://github.com/abandonware/noble 74 | - KettlerUSB2BLE: https://github.com/360manu/kettlerUSB2BLE 75 | --------------------------------------------------------------------------------