Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/ble/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { BleInterface, BleInterfaceFactory } from '../ble/base/interface.js'
import { BleMultiTransportInterfaceFactory,BleAdapterFactory } from './factories/index.js'
import { BleCSCAdapter, BleCyclingSpeedCadenceDevice } from './csc/index.js'
import { BleZwiftPlaySensor, ZwiftPlayAdapter } from './zwift/play/index.js'
import { BleOpenBikeControlSensor, OpenBikeControlAdapter } from './openbikecontrol/index.js'



Expand All @@ -24,6 +25,7 @@ import { BleZwiftPlaySensor, ZwiftPlayAdapter } from './zwift/play/index.js'
af.register('bkool',BleBkoolAdapter,BleBkoolComms)
af.register('csc',BleCSCAdapter,BleCyclingSpeedCadenceDevice)
af.register('zwift-play',ZwiftPlayAdapter,BleZwiftPlaySensor)
af.register('openbikecontrol',OpenBikeControlAdapter,BleOpenBikeControlSensor)
})

BleMultiTransportInterfaceFactory.register('ble',BleInterfaceFactory)
Expand Down
99 changes: 99 additions & 0 deletions src/ble/openbikecontrol/adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import {EventLogger} from 'gd-eventlog';
import { BleDeviceData } from '../base/types.js';
import { LegacyProfile } from '../../antv2/types.js';
import BleAdapter from '../base/adapter.js';
import { BleOpenBikeControlSensor } from './sensor.js';
import { DeviceProperties, IAdapter, IncyclistAdapterData, IncyclistCapability } from '../../types/index.js';
import { BleDeviceSettings, IBlePeripheral } from '../types.js';


export class OpenBikeControlAdapter extends BleAdapter<BleDeviceData,BleOpenBikeControlSensor>{
protected static INCYCLIST_PROFILE_NAME:LegacyProfile = 'Controller'
protected static CAPABILITIES:IncyclistCapability[] = [ IncyclistCapability.AppControl ]
protected keyPressedHandler?: (event:any)=>void

constructor( settings:BleDeviceSettings, props?:DeviceProperties) {
super(settings,props);

this.logger = new EventLogger('OpenBikeControl')

this.device = new BleOpenBikeControlSensor( this.getPeripheral() , {logger: this.logger})
this.capabilities = OpenBikeControlAdapter.CAPABILITIES
}

protected async checkCapabilities():Promise<void> {
return ;
}


async startSensor():Promise<boolean> {
try {
let connected = await super.startSensor()

if (connected) {
const sensor = this.getSensor()

// forward key-pressed events
if (this.keyPressedHandler) {
sensor.off('key-pressed', this.keyPressedHandler)
}
else {
this.keyPressedHandler = this.onKeyPressed.bind(this)
}
sensor.on('key-pressed', this.keyPressedHandler)
}
return connected
}
catch ( err:any) {
this.logEvent({message:'error', fn:'startSensor', error:err.message, stack:err.stack})
return false
}
}

protected onKeyPressed(event:any) {
this.emit('key-pressed',this.getSettings(), event)
}

isEqual(settings: BleDeviceSettings): boolean {
// several controllers may use the same name (e.g. BikeControl on two devices)
return super.isEqual(settings) && settings.address == (this.settings as BleDeviceSettings).address
}

isSame(adapter:IAdapter):boolean {
if (!(adapter instanceof OpenBikeControlAdapter))
return false;

return this.isEqual(adapter.settings as BleDeviceSettings)
}

updateSensor(peripheral:IBlePeripheral) {
this.device = new BleOpenBikeControlSensor( peripheral, {logger:this.logger})
}


getProfile():LegacyProfile {
return OpenBikeControlAdapter.INCYCLIST_PROFILE_NAME
}

getName(): string {
const settings:BleDeviceSettings = this.settings as BleDeviceSettings
const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '')
const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase()
return addressHash ? `${settings.name} ${addressHash}` : settings.name
}

getDisplayName() {
return this.getName()
}

mapData(deviceData:BleDeviceData): IncyclistAdapterData{
return {} // nothing requires mapping
}

// controllers only send data when a button is pressed, so the start must not wait for it
protected shouldWaitForData(): boolean {
return false
}


}
23 changes: 23 additions & 0 deletions src/ble/openbikecontrol/adapter.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { OpenBikeControlAdapter } from './adapter'

describe('OpenBikeControlAdapter', () => {

const settings = (extra = {}) => ({ interface: 'wifi', name: 'BikeControl', protocol: 'openbikecontrol', address: '10.0.0.7', ...extra }) as any

test('start does not wait for data, as controllers only send data when a button is pressed', () => {
const adapter: any = new OpenBikeControlAdapter(settings())
expect(adapter.shouldWaitForData()).toBe(false)
})

test('controllers with the same name but different addresses are different devices', () => {
const adapter = new OpenBikeControlAdapter(settings())
expect(adapter.isEqual(settings())).toBe(true)
expect(adapter.isEqual(settings({ address: '10.0.0.8' }))).toBe(false)
expect(adapter.isSame(new OpenBikeControlAdapter(settings({ address: '10.0.0.8' })))).toBe(false)
})

test('the name contains the end of the address', () => {
expect(new OpenBikeControlAdapter(settings()).getName()).toBe('BikeControl 0007')
expect(new OpenBikeControlAdapter(settings({ interface: 'ble', address: 'aa:bb:cc:dd:ee:ff' })).getName()).toBe('BikeControl EEFF')
})
})
4 changes: 4 additions & 0 deletions src/ble/openbikecontrol/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// OpenBikeControl (https://openbikecontrol.org) - open protocol for handlebar controllers
export const OBC_SERVICE = 'd273f680-d548-419d-b9d1-fa0472345229'
export const OBC_BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229'
export const OBC_APP_INFO = 'd273f683-d548-419d-b9d1-fa0472345229'
2 changes: 2 additions & 0 deletions src/ble/openbikecontrol/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './sensor.js'
export * from './adapter.js'
141 changes: 141 additions & 0 deletions src/ble/openbikecontrol/sensor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { LegacyProfile } from "../../antv2/types.js";
import { TBleSensor } from "../base/sensor.js";
import { BleProtocol } from "../types.js";
import { matches } from "../utils.js";
import { OBC_APP_INFO, OBC_BUTTON_STATE, OBC_SERVICE } from "./consts.js";

const MSG_BUTTON_STATE = 0x01
const MSG_APP_INFO = 0x04

const BUTTON_SHIFT_UP = 0x01
const BUTTON_SHIFT_DOWN = 0x02
const BUTTON_INCREASE_DIFFICULTY = 0x30
const BUTTON_DECREASE_DIFFICULTY = 0x31
const BUTTON_SKIP_INTERVAL = 0x32
const BUTTON_PREVIOUS_INTERVAL = 0x36

// OpenBikeControl button IDs mapped to the keys that are already used for the Zwift controllers
const BUTTON_KEYS = new Map<number,string>([
[BUTTON_SHIFT_UP, 'r-shift-up'],
[BUTTON_SHIFT_DOWN, 'r-shift-down'],
[BUTTON_INCREASE_DIFFICULTY, 'y'],
[BUTTON_DECREASE_DIFFICULTY, 'b'],
[BUTTON_SKIP_INTERVAL, 'a'],
[BUTTON_PREVIOUS_INTERVAL, 'z'],
])

// buttons that were pressed with the same message, i.e. one physical button
type ButtonPress = {
buttons: number[]
pressed: number[]
timestamp: number
}

export class BleOpenBikeControlSensor extends TBleSensor {
static readonly profile:LegacyProfile = 'Controller'
static readonly protocol:BleProtocol = 'openbikecontrol'
static readonly services = [OBC_SERVICE];
static readonly characteristics = [];
static readonly detectionPriority = 0; // trainers that also offer OpenBikeControl should be detected as trainer

protected buttonStates: Map<number, ButtonPress> = new Map()

protected onDisconnect() {
super.onDisconnect()
this.reset()
}

async subscribe():Promise<boolean> {
const subscribed = await super.subscribe()
if (subscribed)
await this.sendAppInfo()
return subscribed
}

protected getRequiredCharacteristics():Array<string> {
return [OBC_BUTTON_STATE]
}

onData(characteristic: string, data: Buffer): boolean {
if (matches(characteristic,OBC_BUTTON_STATE)) {
this.onButtonState(Buffer.from(data))
}
return true
}

protected onButtonState(data:Buffer) {
try {
if (data.length<3 || data[0]!==MSG_BUTTON_STATE)
return

// a controller may send several actions for one physical button (e.g. BikeControl),
// so all buttons pressed with the same message are treated as one press, which results in one key.
// keys are reported on release, same as for the Zwift controllers
const press:ButtonPress = {buttons:[], pressed:[], timestamp:Date.now()}
const released:ButtonPress[] = []
for (let i=1; i+1<data.length; i+=2) {
const buttonId = data[i]
if (!BUTTON_KEYS.has(buttonId))
continue

const pressed = data[i+1]!==0x00
const prev = this.buttonStates.get(buttonId)
if (pressed && !prev) {
press.buttons.push(buttonId)
press.pressed.push(buttonId)
this.buttonStates.set(buttonId, press)
}
else if (!pressed && prev) {
this.buttonStates.delete(buttonId)
prev.pressed = prev.pressed.filter( id=> id!==buttonId)
if (prev.pressed.length===0)
released.push(prev)
}
}

released.forEach( p => {
const key = this.getKey(p.buttons)
const duration = Date.now()-p.timestamp
const {name,address} = this.peripheral?.getInfo() ?? {}
this.logEvent({message:'key pressed', key, name,address, duration})
this.emit('key-pressed', {key, duration})
})
}
catch(err) {
this.logEvent({message:'error', fn:'onButtonState', error:err.message, stack:err.stack})
}
}

protected getKey(buttons:number[]):string {
// shift and difficulty for the same button: use the generic 'up'/'down' keys (as Zwift Click),
// which adjust gear or power depending on the mode, to avoid a double adjustment
if (buttons.includes(BUTTON_SHIFT_UP) && buttons.includes(BUTTON_INCREASE_DIFFICULTY))
return 'up'
if (buttons.includes(BUTTON_SHIFT_DOWN) && buttons.includes(BUTTON_DECREASE_DIFFICULTY))
return 'down'

// otherwise the first supported action in the order of BUTTON_KEYS
const buttonId = Array.from(BUTTON_KEYS.keys()).find( id=> buttons.includes(id))
return BUTTON_KEYS.get(buttonId)
}

protected async sendAppInfo():Promise<void> {
try {
const appId = Buffer.from('incyclist')
const buttons = Array.from(BUTTON_KEYS.keys())

// [type] [version] [app id length] [app id] [app version length (not sent)] [button count] [button ids]
const message = Buffer.from([MSG_APP_INFO, 0x01, appId.length, ...appId, 0x00, buttons.length, ...buttons])
await this.write(OBC_APP_INFO, message, {withoutResponse:true})
}
catch(err) {
// app information is optional, the controller will still send all buttons
this.logEvent({message:'warning', fn:'sendAppInfo', error:err.message})
}
}

reset(): void {
this.buttonStates = new Map()
}

}
Loading
Loading