From bd2d08e84b8e411324fb3b0cca6f4c949ce1252d Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Fri, 6 Nov 2026 10:14:30 +0100 Subject: [PATCH 1/7] Add OpenBikeControl controller support (BLE) Adds a BLE adapter/sensor for OpenBikeControl controllers (https://openbikecontrol.org), next to the existing Zwift Play/Click support. Button state notifications are mapped onto the existing 'key-pressed' keys, so no changes are needed in the services: - Shift Up/Down -> r-shift-up / r-shift-down (gear change) - Increase/Decrease Difficulty -> y / b (power / workout adjustment) - Skip / Previous Interval -> a / z (workout forward / backward) - Shift + Difficulty on the same button -> up / down (as Zwift Click) After subscribing, the app information message is sent so controllers know which buttons Incyclist supports. Co-Authored-By: Claude Opus 5.5 --- src/ble/index.ts | 2 + src/ble/openbikecontrol/adapter.ts | 82 +++++++++++ src/ble/openbikecontrol/index.ts | 2 + src/ble/openbikecontrol/sensor.ts | 142 ++++++++++++++++++++ src/ble/openbikecontrol/sensor.unit.test.ts | 116 ++++++++++++++++ src/ble/types.ts | 2 +- src/direct-connect/base/interface.ts | 2 + 7 files changed, 347 insertions(+), 1 deletion(-) create mode 100644 src/ble/openbikecontrol/adapter.ts create mode 100644 src/ble/openbikecontrol/index.ts create mode 100644 src/ble/openbikecontrol/sensor.ts create mode 100644 src/ble/openbikecontrol/sensor.unit.test.ts diff --git a/src/ble/index.ts b/src/ble/index.ts index 759d487..6f77087 100644 --- a/src/ble/index.ts +++ b/src/ble/index.ts @@ -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' @@ -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) diff --git a/src/ble/openbikecontrol/adapter.ts b/src/ble/openbikecontrol/adapter.ts new file mode 100644 index 0000000..7bd726e --- /dev/null +++ b/src/ble/openbikecontrol/adapter.ts @@ -0,0 +1,82 @@ +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{ + 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 { + return ; + } + + + async startSensor():Promise { + 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) + } + + 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 + } + + getDisplayName() { + return this.getName() + } + + mapData(deviceData:BleDeviceData): IncyclistAdapterData{ + return {} // nothing requires mapping + } + + +} diff --git a/src/ble/openbikecontrol/index.ts b/src/ble/openbikecontrol/index.ts new file mode 100644 index 0000000..2d207cc --- /dev/null +++ b/src/ble/openbikecontrol/index.ts @@ -0,0 +1,2 @@ +export * from './sensor.js' +export * from './adapter.js' diff --git a/src/ble/openbikecontrol/sensor.ts b/src/ble/openbikecontrol/sensor.ts new file mode 100644 index 0000000..cbf25d9 --- /dev/null +++ b/src/ble/openbikecontrol/sensor.ts @@ -0,0 +1,142 @@ +import { LegacyProfile } from "../../antv2/types.js"; +import { TBleSensor } from "../base/sensor.js"; +import { BleProtocol } from "../types.js"; +import { matches } from "../utils.js"; + +// OpenBikeControl (https://openbikecontrol.org) - open protocol for handlebar controllers +const OBC_SERVICE = 'd273f680-d548-419d-b9d1-fa0472345229' +const OBC_BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229' +const OBC_APP_INFO = 'd273f683-d548-419d-b9d1-fa0472345229' + +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([ + [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'], +]) + +type ButtonState = { + pressed: boolean + 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 = new Map() + + protected onDisconnect() { + super.onDisconnect() + this.reset() + } + + async subscribe():Promise { + const subscribed = await super.subscribe() + if (subscribed) + await this.sendAppInfo() + return subscribed + } + + protected getRequiredCharacteristics():Array { + 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 + + // keys are reported on release, same as for the Zwift controllers + const released = new Map() + for (let i=1; i+1 { + 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 getReleasedKeys(released:Map):Array<{key:string, duration:number}> { + const keys:Array<{key:string, duration:number}> = [] + + // controllers may send shift and difficulty for the same physical button (e.g. BikeControl) + // in that case use the generic 'up'/'down' keys (as Zwift Click), to avoid a double adjustment + const combine = (shift:number, difficulty:number, key:string) => { + if (released.has(shift) && released.has(difficulty)) { + keys.push({key, duration:released.get(shift)}) + released.delete(shift) + released.delete(difficulty) + } + } + combine(BUTTON_SHIFT_UP, BUTTON_INCREASE_DIFFICULTY, 'up') + combine(BUTTON_SHIFT_DOWN, BUTTON_DECREASE_DIFFICULTY, 'down') + + released.forEach( (duration,buttonId) => { + keys.push({key:BUTTON_KEYS.get(buttonId), duration}) + }) + return keys + } + + protected async sendAppInfo():Promise { + 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() + } + +} diff --git a/src/ble/openbikecontrol/sensor.unit.test.ts b/src/ble/openbikecontrol/sensor.unit.test.ts new file mode 100644 index 0000000..5048246 --- /dev/null +++ b/src/ble/openbikecontrol/sensor.unit.test.ts @@ -0,0 +1,116 @@ +import { BleOpenBikeControlSensor } from './sensor' +import { BleAdapterFactory } from '../index' +import { MockLogger } from '../../../test/logger' + +const BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229' +const APP_INFO = 'd273f683-d548-419d-b9d1-fa0472345229' + +describe('BleOpenBikeControlSensor', () => { + + describe('onData - button state', () => { + let sensor: any + let onKey: any + + const send = (...bytes:number[]) => sensor.onData(BUTTON_STATE, Buffer.from(bytes)) + + beforeEach(() => { + sensor = new BleOpenBikeControlSensor({ getInfo: () => ({}) } as any, { logger: MockLogger }) + sensor.logEvent = jest.fn() + onKey = jest.fn() + sensor.on('key-pressed', onKey) + }) + + test.each([ + [0x01, 'r-shift-up'], + [0x02, 'r-shift-down'], + [0x30, 'y'], + [0x31, 'b'], + [0x32, 'a'], + [0x36, 'z'], + ])('button %i emits key %s on release', (buttonId, key) => { + send(0x01, buttonId, 0x01) + expect(onKey).not.toHaveBeenCalled() + + send(0x01, buttonId, 0x00) + expect(onKey).toHaveBeenCalledTimes(1) + expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key, duration: expect.any(Number) })) + }) + + test('long press reports the duration', () => { + jest.useFakeTimers() + send(0x01, 0x01, 0x01) + jest.advanceTimersByTime(1500) + send(0x01, 0x01, 0x00) + jest.useRealTimers() + + expect(onKey).toHaveBeenCalledWith({ key: 'r-shift-up', duration: 1500 }) + }) + + test('shift and difficulty sent for the same button are combined into one key', () => { + send(0x01, 0x01, 0x01, 0x30, 0x01, 0x14, 0x01) + send(0x01, 0x01, 0x00, 0x30, 0x00, 0x14, 0x00) + + expect(onKey).toHaveBeenCalledTimes(1) + expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key: 'up' })) + }) + + test('release without press, unsupported buttons and other messages are ignored', () => { + send(0x01, 0x01, 0x00) + send(0x01, 0x14, 0x01) + send(0x01, 0x14, 0x00) + send(0x02, 0x55, 0x01) + sensor.onData('d273f682-d548-419d-b9d1-fa0472345229', Buffer.from([0x01, 0x01, 0x01])) + + expect(onKey).not.toHaveBeenCalled() + }) + + test('a disconnect clears pressed buttons', () => { + send(0x01, 0x01, 0x01) + sensor.onDisconnect() + send(0x01, 0x01, 0x00) + + expect(onKey).not.toHaveBeenCalled() + }) + }) + + describe('subscribe - app information', () => { + test('sends app id and supported buttons after subscribing', async () => { + const peripheral = { + isConnected: jest.fn(() => true), + subscribeSelected: jest.fn(async () => true), + write: jest.fn(async () => Buffer.from([])), + } + const sensor = new BleOpenBikeControlSensor(peripheral as any, { logger: MockLogger }) + + const subscribed = await sensor.subscribe() + + expect(subscribed).toBe(true) + expect(peripheral.subscribeSelected).toHaveBeenCalledWith([BUTTON_STATE], expect.any(Function)) + const expected = Buffer.from([0x04, 0x01, 0x09, ...Buffer.from('incyclist'), 0x00, 0x06, 0x01, 0x02, 0x30, 0x31, 0x32, 0x36]) + expect(peripheral.write).toHaveBeenCalledWith(APP_INFO, expected, { withoutResponse: true }) + }) + + test('a failing app information write does not fail the subscription', async () => { + const peripheral = { + isConnected: jest.fn(() => true), + subscribeSelected: jest.fn(async () => true), + write: jest.fn(async () => { throw new Error('not supported') }), + } + const sensor = new BleOpenBikeControlSensor(peripheral as any, { logger: MockLogger }) + + expect(await sensor.subscribe()).toBe(true) + }) + }) + + describe('detection', () => { + const factory = BleAdapterFactory.getInstance('ble') + + test('OpenBikeControl service', () => { + expect(factory.getProtocol(['d273f680d548419db9d1fa0472345229'])).toBe('openbikecontrol') + }) + + test('a trainer that also offers OpenBikeControl is detected as trainer', () => { + expect(factory.getProtocol(['1826', 'd273f680-d548-419d-b9d1-fa0472345229'])).toBe('fm') + }) + }) +}) diff --git a/src/ble/types.ts b/src/ble/types.ts index c92e82a..856abea 100644 --- a/src/ble/types.ts +++ b/src/ble/types.ts @@ -3,7 +3,7 @@ import { EventLogger } from "gd-eventlog"; import { DeviceProperties, DeviceSettings, DeviceStartProperties, IncyclistInterface, IncyclistScanProps,InterfaceProps } from "../types/index.js"; -export type BleProtocol = 'hr' | 'fm' | 'cp' | 'tacx' | 'wahoo' | 'bkool' | 'elite' | 'csc' | 'zwift-play' +export type BleProtocol = 'hr' | 'fm' | 'cp' | 'tacx' | 'wahoo' | 'bkool' | 'elite' | 'csc' | 'zwift-play' | 'openbikecontrol' export type BleInterfaceState = 'unknown' | 'resetting' | 'unsupported' | 'unauthorized' | 'poweredOff'| 'poweredOn' diff --git a/src/direct-connect/base/interface.ts b/src/direct-connect/base/interface.ts index bcbdd80..644d9a4 100644 --- a/src/direct-connect/base/interface.ts +++ b/src/direct-connect/base/interface.ts @@ -863,6 +863,8 @@ export default class DirectConnectInterface extends EventEmitter implements IB return [CSC] case 'zwift-play': return ['0000000119ca465186e5fa29dcdd09d1'] + case 'openbikecontrol': + return ['d273f680d548419db9d1fa0472345229'] default: return [] } From a259171992ce1947591fce08c32744a521bdae0f Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Fri, 6 Nov 2026 11:15:15 +0100 Subject: [PATCH 2/7] Add OpenBikeControl support over mDNS/TCP OpenBikeControl devices that announce _openbikecontrol._tcp are now discovered by the Direct Connect (wifi) interface. The TCP connection carries the same messages as the BLE characteristics, so the new OpenBikeControlPeripheral provides button state messages as notifications of the Button State characteristic and sends writes unchanged. This way the existing OpenBikeControl sensor/adapter (button mapping, app information) is shared between BLE and WiFi. - the OpenBikeControl service UUID is added to the announcement, as the device lists it in a different TXT record than Direct Connect - an announcement without services (unfiltered browser) no longer replaces one with services, and the device is announced once its services are known - no known-device placeholder for OpenBikeControl, as the port is only known from the announcement Co-Authored-By: Claude Opus 5.5 --- src/ble/openbikecontrol/consts.ts | 4 + src/ble/openbikecontrol/sensor.ts | 6 +- src/direct-connect/base/interface.ts | 34 +++++- .../base/interface.unit.test.ts | 62 ++++++++++- src/direct-connect/base/peripheral.ts | 100 +++++++++++++++++- .../base/peripheral.unit.test.ts | 59 ++++++++++- 6 files changed, 251 insertions(+), 14 deletions(-) create mode 100644 src/ble/openbikecontrol/consts.ts diff --git a/src/ble/openbikecontrol/consts.ts b/src/ble/openbikecontrol/consts.ts new file mode 100644 index 0000000..eb5a628 --- /dev/null +++ b/src/ble/openbikecontrol/consts.ts @@ -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' diff --git a/src/ble/openbikecontrol/sensor.ts b/src/ble/openbikecontrol/sensor.ts index cbf25d9..fc452b5 100644 --- a/src/ble/openbikecontrol/sensor.ts +++ b/src/ble/openbikecontrol/sensor.ts @@ -2,11 +2,7 @@ import { LegacyProfile } from "../../antv2/types.js"; import { TBleSensor } from "../base/sensor.js"; import { BleProtocol } from "../types.js"; import { matches } from "../utils.js"; - -// OpenBikeControl (https://openbikecontrol.org) - open protocol for handlebar controllers -const OBC_SERVICE = 'd273f680-d548-419d-b9d1-fa0472345229' -const OBC_BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229' -const OBC_APP_INFO = 'd273f683-d548-419d-b9d1-fa0472345229' +import { OBC_APP_INFO, OBC_BUTTON_STATE, OBC_SERVICE } from "./consts.js"; const MSG_BUTTON_STATE = 0x01 const MSG_APP_INFO = 0x04 diff --git a/src/direct-connect/base/interface.ts b/src/direct-connect/base/interface.ts index 644d9a4..c8d9cfc 100644 --- a/src/direct-connect/base/interface.ts +++ b/src/direct-connect/base/interface.ts @@ -5,12 +5,13 @@ import { DirectConnectBinding, MulticastDnsAnnouncement } from "../bindings/inde import { DirectConnectScanProps } from "../types.js"; import { BleDeviceSettings, BleProtocol, IBleInterface, IBlePeripheral } from '../../ble/types.js'; import { InteruptableTask, TaskState } from "../../utils/task.js"; -import { DirectConnectPeripheral } from "./peripheral.js"; +import { DirectConnectPeripheral, OpenBikeControlPeripheral } from "./peripheral.js"; import { beautifyUUID, BleAdapterFactory } from "../../ble/index.js"; import { TBleSensor } from "../../ble/base/sensor.js"; import { InterfaceFactory } from "../../ble/base/types.js"; import { CSC, CSP } from "../../ble/consts.js"; import { WAHOO_ADVANCED_FTMS } from "../../ble/wahoo/consts.js"; +import { OBC_SERVICE } from "../../ble/openbikecontrol/consts.js"; const DC_TYPE = 'wahoo-fitness-tnp' const DC_PORT = 36866 @@ -18,6 +19,7 @@ const DC_EXPIRATION_TIMEOUT = 10*1000*60 // 10min const DC_PROBE_TIMEOUT = 2000 // max time to wait for a TCP probe const DC_REPROBE_INTERVAL = 5000 // pause between probes while waiting for a device const DC_WAIT_LIFETIME = 5*60*1000 // stop re-probing a device after 5min +const OBC_TYPE = 'openbikecontrol' interface Announcement { @@ -118,6 +120,8 @@ export default class DirectConnectInterface extends EventEmitter implements IB createPeripheral(announcement: MulticastDnsAnnouncement): IBlePeripheral { + if (announcement.type===OBC_TYPE) + return OpenBikeControlPeripheral.create(announcement) return DirectConnectPeripheral.create(announcement) } @@ -292,6 +296,13 @@ export default class DirectConnectInterface extends EventEmitter implements IB this.addService( service, DC_TYPE ) } ) + + this.getBinding().mdns.find( {type:OBC_TYPE},( service:MulticastDnsAnnouncement )=>{ + // some bindings don't provide the type and deliver announcements to all callbacks + if (service.type && service.type!==OBC_TYPE) + return + this.addService( {...service, type:OBC_TYPE}, OBC_TYPE ) + } ) } async pauseBackgroundActivity():Promise { @@ -660,6 +671,10 @@ export default class DirectConnectInterface extends EventEmitter implements IB try { service.transport = this.getName(); + // OpenBikeControl announces its service UUIDs in a different TXT record than Direct Connect + if (service.type===OBC_TYPE && !service.serviceUUIDs?.length) + service.serviceUUIDs = [OBC_SERVICE] + // exact match (same name AND same address): a refresh/heartbeat of an entry we already // track, not a new device const sameAddress = this.findByNameAndAddress(service.name, service.address) @@ -710,12 +725,22 @@ export default class DirectConnectInterface extends EventEmitter implements IB const idx = this.services.indexOf(sameAddress) const wasKnownDevicePlaceholder = sameAddress.source==='known-device' const nextSource = (wasKnownDevicePlaceholder && src!=='known-device') ? src : sameAddress.source - this.services[idx] = {ts:Date.now(),service,source:nextSource} + + // an announcement without services (e.g. from the unfiltered browser) must not replace one with services + const hadServices = sameAddress.service.serviceUUIDs?.length>0 + const hasServices = service.serviceUUIDs?.length>0 + this.services[idx] = {ts:Date.now(),service: (hadServices && !hasServices) ? sameAddress.service : service,source:nextSource} if (src!=='known-device' && wasKnownDevicePlaceholder) { this.logEvent({message:'device re-announced',device:service.name, announcement:service, source}) this.emitDevice(service) } + else if (!hadServices && hasServices) { + // first announcement with services (e.g. an OpenBikeControl device that was already seen by the unfiltered browser) + this.logEvent({message:'device announced',device:service.name, announcement:service, source}) + this.emitDevice(service) + this.matching?.push(service.name) + } } // Records a brand new cache entry (first sighting of this name this session, or a 2nd distinct @@ -826,7 +851,8 @@ export default class DirectConnectInterface extends EventEmitter implements IB return details[0].class } protected createAnnouncementFromSettings(settings: BleDeviceSettings): MulticastDnsAnnouncement { - if (settings.protocol && settings.address) { + // OpenBikeControl devices don't use a fixed port, they can only be connected once announced + if (settings.protocol && settings.address && settings.protocol!=='openbikecontrol') { const announcement:MulticastDnsAnnouncement = { name: settings.name, address: settings.address, @@ -863,8 +889,6 @@ export default class DirectConnectInterface extends EventEmitter implements IB return [CSC] case 'zwift-play': return ['0000000119ca465186e5fa29dcdd09d1'] - case 'openbikecontrol': - return ['d273f680d548419db9d1fa0472345229'] default: return [] } diff --git a/src/direct-connect/base/interface.unit.test.ts b/src/direct-connect/base/interface.unit.test.ts index a079a03..cc73834 100644 --- a/src/direct-connect/base/interface.unit.test.ts +++ b/src/direct-connect/base/interface.unit.test.ts @@ -1,6 +1,7 @@ import { resolveNextTick } from "../../utils/utils" import { DirectConnectBinding, MulticastDnsAnnouncement, MulticastDnsBinding } from "../bindings" import DirectConnectInterface from "./interface" +import { OpenBikeControlPeripheral } from "./peripheral" import net from 'net' const mdns:MulticastDnsBinding = { @@ -432,4 +433,63 @@ describe('DirectConnectInterface', () => { }) }) -}) \ No newline at end of file + describe('OpenBikeControl', () => { + + let dc: any + + const OBC = (extra: Partial = {}): MulticastDnsAnnouncement => + ({ name: 'BikeControl', address: '10.0.0.7', port: 4711, protocol: 'tcp', ...extra } as MulticastDnsAnnouncement) + + beforeEach(() => { + DirectConnectInterface.prototype.autoConnect = jest.fn() + iface = new DirectConnectInterface({ binding: mock }) + iface.on('device',deviceSpy) + dc = iface as any + }) + + afterEach(() => { + jest.resetAllMocks() + iface?.removeAllListeners() + }) + + test('browses for _openbikecontrol._tcp and announces the device', async () => { + const callbacks: Record void> = {} + mdns.find = jest.fn((filter, cb) => { callbacks[filter?.type ?? 'unfiltered'] = cb }) + + await iface.connect() + expect(mdns.find).toHaveBeenCalledWith({type:'openbikecontrol'},expect.anything()) + + callbacks['openbikecontrol'](OBC()) + + expect(deviceSpy).toHaveBeenCalledWith(O({ interface: 'wifi', name: 'BikeControl', protocol: 'openbikecontrol', address: '10.0.0.7' }), expect.anything()) + expect(dc.createPeripheralFromSettings({ interface: 'wifi', name: 'BikeControl', address: '10.0.0.7' })).toBeInstanceOf(OpenBikeControlPeripheral) + }) + + test('ignores announcements of other types', async () => { + const callbacks: Record void> = {} + mdns.find = jest.fn((filter, cb) => { callbacks[filter?.type ?? 'unfiltered'] = cb }) + + await iface.connect() + callbacks['openbikecontrol'](OBC({ type: 'wahoo-fitness-tnp' })) + + expect(deviceSpy).not.toHaveBeenCalled() + }) + + test('device that was first seen by the unfiltered browser is announced once its type is known', () => { + dc.addService(OBC(), 'unfiltered') + expect(deviceSpy).not.toHaveBeenCalled() + + dc.addService(OBC({ type: 'openbikecontrol' }), 'openbikecontrol') + expect(deviceSpy).toHaveBeenCalledTimes(1) + + // a later unfiltered announcement does not replace the OpenBikeControl announcement + dc.addService(OBC(), 'unfiltered') + expect(dc.createPeripheralFromSettings({ interface: 'wifi', name: 'BikeControl', address: '10.0.0.7' })).toBeInstanceOf(OpenBikeControlPeripheral) + }) + + test('known devices are not added, as the port is only known from the announcement', () => { + iface.addKnownDevice({ interface: 'wifi', name: 'BikeControl', protocol: 'openbikecontrol', address: '10.0.0.7' }) + expect(dc.getAll()).toHaveLength(0) + }) + }) +}) diff --git a/src/direct-connect/base/peripheral.ts b/src/direct-connect/base/peripheral.ts index 2273635..0cbffa9 100644 --- a/src/direct-connect/base/peripheral.ts +++ b/src/direct-connect/base/peripheral.ts @@ -6,6 +6,7 @@ import { CharacteristicNotificationMessage, DiscoverCharacteristicsMessage, Disc import { EventEmitter } from "node:events"; import { DC_MESSAGE_CHARACTERISTIC_NOTIFICATION, DC_RC_REQUEST_COMPLETED_SUCCESSFULLY } from "../consts.js"; import { beautifyUUID, parseUUID } from "../../ble/utils.js"; +import { OBC_BUTTON_STATE, OBC_SERVICE } from "../../ble/openbikecontrol/consts.js"; let IDS = 0; const DC_CONNECT_TIMEOUT = 2000 // max time to establish the TCP connection @@ -707,4 +708,101 @@ export class DirectConnectPeripheral implements IBlePeripheral { -} \ No newline at end of file +} + +const OBC_MSG_BUTTON_STATE = 0x01 +const OBC_MSG_DEVICE_STATUS = 0x02 +const OBC_DEVICE_STATUS_LENGTH = 3 + +/** + * OpenBikeControl device, discovered via mDNS (_openbikecontrol._tcp) + * + * Other than Direct Connect, the TCP connection carries the plain OpenBikeControl messages, which use + * the same format as the BLE characteristics. Button state messages are therefore provided as notifications + * of the Button State characteristic and writes (e.g. App Information) are sent as they are. + * This allows to use the same sensor for BLE and WiFi + */ +export class OpenBikeControlPeripheral extends DirectConnectPeripheral { + + static readonly instances: Record ={} + + static create(announcement:MulticastDnsAnnouncement) { + const {address,port} = announcement + const key = `${address}:${port}` + if (!this.instances[key]) + this.instances[key] = new OpenBikeControlPeripheral(announcement) + return this.instances[key] + } + + async discoverServices(): Promise { + this.discoveredServiceUUIds = [beautifyUUID(OBC_SERVICE)] + return [OBC_SERVICE] + } + + async discoverCharacteristics(_serviceUUID: string): Promise { + return [{uuid:OBC_BUTTON_STATE, properties:['read','notify']}] + } + + async subscribe(characteristicUUID: string, callback?: (characteristicUuid: string, data: Buffer) => void): Promise { + // the device sends button state messages without request + const uuid = parseUUID(characteristicUUID) + if (!this.subscribed.includes(uuid)) + this.subscribed.push(uuid) + if (callback) { + this.eventEmitter.on(uuid, (data)=>{ + callback(characteristicUUID,data) + }) + } + return true + } + + async unsubscribe(characteristicUUID: string): Promise { + const uuid = parseUUID(characteristicUUID) + if (this.subscribed.includes(uuid)) + this.subscribed.splice(this.subscribed.indexOf(uuid),1) + this.eventEmitter.removeAllListeners(uuid) + return true + } + + async read(_characteristicUUID: string): Promise { + return Buffer.from([]) + } + + async write(characteristicUUID: string, data: Buffer, _options?: BleWriteProps): Promise { + await this.connect() + + this.logEvent({message:'write', path:this.getPath(), characteristic:beautifyUUID(characteristicUUID), raw:data.toString('hex') }) + this.socket.write(data) + return Buffer.from([]) + } + + protected async onData(data:Buffer) { + try { + let offset = 0 + while (offset{ @@ -148,4 +148,59 @@ describe('DirectConnect Peripheral',()=>{ } }) }) -}) \ No newline at end of file + + describe('OpenBikeControlPeripheral',()=>{ + + const announcement:MulticastDnsAnnouncement = { + type:'openbikecontrol', + name:'BikeControl', + address:'192.168.1.2', + protocol:'tcp', + port:4711, + serviceUUIDs:['d273f680-d548-419d-b9d1-fa0472345229'], + transport:'wifi'} + + const BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229' + + let p:any + beforeEach( ()=>{ + p = new OpenBikeControlPeripheral(announcement) + p.logEvent = jest.fn() + }) + + test('button state messages are notified on the Button State characteristic',async ()=>{ + const callback = jest.fn() + const success = await p.subscribeSelected([BUTTON_STATE],callback) + expect(success).toBe(true) + + await p.onData(M('010101')) + expect(callback).toHaveBeenCalledWith(BUTTON_STATE, M('010101')) + }) + + test('device status is skipped, also if followed by a button state message in the same packet',async ()=>{ + const callback = jest.fn() + await p.subscribe(BUTTON_STATE,callback) + + await p.onData(M('025501')) + expect(callback).not.toHaveBeenCalled() + + await p.onData(M('0255010102010300')) + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(BUTTON_STATE, M('0102010300')) + }) + + test('writes are sent unchanged',async ()=>{ + const write = jest.fn() + p.connect = jest.fn(async ()=>true) + p.socket = { write } + + await p.write('d273f683-d548-419d-b9d1-fa0472345229', M('0401'), {withoutResponse:true}) + expect(write).toHaveBeenCalledWith(M('0401')) + }) + + test('create returns one instance per address and port',()=>{ + expect(OpenBikeControlPeripheral.create(announcement)).toBe(OpenBikeControlPeripheral.create({...announcement})) + expect(OpenBikeControlPeripheral.create(announcement)).not.toBe(OpenBikeControlPeripheral.create({...announcement, port:4712})) + }) + }) +}) From aa999d012adec31e21d6eb0bdb108953b753c5d8 Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Fri, 6 Nov 2026 11:17:04 +0100 Subject: [PATCH 3/7] Keep Direct Connect discovery unaffected by the OpenBikeControl browser Start the OpenBikeControl browser before the Direct Connect browser, as the mobile binding only keeps the last started browser active, and ignore announcements that list services other than OpenBikeControl, as the mobile binding labels all announcements with the requested type. Co-Authored-By: Claude Opus 5.5 --- src/direct-connect/base/interface.ts | 17 ++++++++++------- src/direct-connect/base/interface.unit.test.ts | 2 ++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/direct-connect/base/interface.ts b/src/direct-connect/base/interface.ts index c8d9cfc..b1e366e 100644 --- a/src/direct-connect/base/interface.ts +++ b/src/direct-connect/base/interface.ts @@ -6,7 +6,7 @@ import { DirectConnectScanProps } from "../types.js"; import { BleDeviceSettings, BleProtocol, IBleInterface, IBlePeripheral } from '../../ble/types.js'; import { InteruptableTask, TaskState } from "../../utils/task.js"; import { DirectConnectPeripheral, OpenBikeControlPeripheral } from "./peripheral.js"; -import { beautifyUUID, BleAdapterFactory } from "../../ble/index.js"; +import { beautifyUUID, BleAdapterFactory, matches } from "../../ble/index.js"; import { TBleSensor } from "../../ble/base/sensor.js"; import { InterfaceFactory } from "../../ble/base/types.js"; import { CSC, CSP } from "../../ble/consts.js"; @@ -292,17 +292,20 @@ export default class DirectConnectInterface extends EventEmitter implements IB } ) - this.getBinding().mdns.find( {type:DC_TYPE},( service:MulticastDnsAnnouncement )=>{ - this.addService( service, DC_TYPE ) - - } ) - + // started before the Direct Connect browser, as some bindings only support one active browser this.getBinding().mdns.find( {type:OBC_TYPE},( service:MulticastDnsAnnouncement )=>{ - // some bindings don't provide the type and deliver announcements to all callbacks + // some bindings deliver all announcements to all callbacks if (service.type && service.type!==OBC_TYPE) return + if (service.serviceUUIDs?.length && !service.serviceUUIDs.some( uuid=>matches(uuid,OBC_SERVICE))) + return this.addService( {...service, type:OBC_TYPE}, OBC_TYPE ) } ) + + this.getBinding().mdns.find( {type:DC_TYPE},( service:MulticastDnsAnnouncement )=>{ + this.addService( service, DC_TYPE ) + + } ) } async pauseBackgroundActivity():Promise { diff --git a/src/direct-connect/base/interface.unit.test.ts b/src/direct-connect/base/interface.unit.test.ts index cc73834..766cd39 100644 --- a/src/direct-connect/base/interface.unit.test.ts +++ b/src/direct-connect/base/interface.unit.test.ts @@ -471,6 +471,8 @@ describe('DirectConnectInterface', () => { await iface.connect() callbacks['openbikecontrol'](OBC({ type: 'wahoo-fitness-tnp' })) + // bindings that set the requested type on all announcements + callbacks['openbikecontrol'](OBC({ name: 'KICKR', type: 'openbikecontrol', serviceUUIDs: ['1826'] })) expect(deviceSpy).not.toHaveBeenCalled() }) From 5248b096d76838748389b73234dda4b1d5abaa42 Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Fri, 6 Nov 2026 12:02:08 +0100 Subject: [PATCH 4/7] Report one key per OpenBikeControl button press A controller may send several actions for one physical button (e.g. Shift Up + Increase Difficulty + Select). All supported buttons that are pressed with the same message are now treated as one press, which results in exactly one key once all of them are released: 'up'/'down' for shift together with difficulty, otherwise the first supported action (shift, difficulty, interval). Co-Authored-By: Claude Opus 5.5 --- src/ble/openbikecontrol/sensor.ts | 61 +++++++++++---------- src/ble/openbikecontrol/sensor.unit.test.ts | 34 +++++++++++- 2 files changed, 63 insertions(+), 32 deletions(-) diff --git a/src/ble/openbikecontrol/sensor.ts b/src/ble/openbikecontrol/sensor.ts index fc452b5..30ab635 100644 --- a/src/ble/openbikecontrol/sensor.ts +++ b/src/ble/openbikecontrol/sensor.ts @@ -24,8 +24,10 @@ const BUTTON_KEYS = new Map([ [BUTTON_PREVIOUS_INTERVAL, 'z'], ]) -type ButtonState = { - pressed: boolean +// buttons that were pressed with the same message, i.e. one physical button +type ButtonPress = { + buttons: number[] + pressed: number[] timestamp: number } @@ -36,7 +38,7 @@ export class BleOpenBikeControlSensor extends TBleSensor { static readonly characteristics = []; static readonly detectionPriority = 0; // trainers that also offer OpenBikeControl should be detected as trainer - protected buttonStates: Map = new Map() + protected buttonStates: Map = new Map() protected onDisconnect() { super.onDisconnect() @@ -66,8 +68,11 @@ export class BleOpenBikeControlSensor extends TBleSensor { 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 released = new Map() + const press:ButtonPress = {buttons:[], pressed:[], timestamp:Date.now()} + const released:ButtonPress[] = [] for (let i=1; i+1 id!==buttonId) + if (prev.pressed.length===0) + released.push(prev) } } - this.getReleasedKeys(released).forEach( ({key,duration}) => { + 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}) @@ -95,25 +106,17 @@ export class BleOpenBikeControlSensor extends TBleSensor { } } - protected getReleasedKeys(released:Map):Array<{key:string, duration:number}> { - const keys:Array<{key:string, duration:number}> = [] - - // controllers may send shift and difficulty for the same physical button (e.g. BikeControl) - // in that case use the generic 'up'/'down' keys (as Zwift Click), to avoid a double adjustment - const combine = (shift:number, difficulty:number, key:string) => { - if (released.has(shift) && released.has(difficulty)) { - keys.push({key, duration:released.get(shift)}) - released.delete(shift) - released.delete(difficulty) - } - } - combine(BUTTON_SHIFT_UP, BUTTON_INCREASE_DIFFICULTY, 'up') - combine(BUTTON_SHIFT_DOWN, BUTTON_DECREASE_DIFFICULTY, 'down') - - released.forEach( (duration,buttonId) => { - keys.push({key:BUTTON_KEYS.get(buttonId), duration}) - }) - return keys + 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 { diff --git a/src/ble/openbikecontrol/sensor.unit.test.ts b/src/ble/openbikecontrol/sensor.unit.test.ts index 5048246..968a40a 100644 --- a/src/ble/openbikecontrol/sensor.unit.test.ts +++ b/src/ble/openbikecontrol/sensor.unit.test.ts @@ -46,14 +46,42 @@ describe('BleOpenBikeControlSensor', () => { expect(onKey).toHaveBeenCalledWith({ key: 'r-shift-up', duration: 1500 }) }) - test('shift and difficulty sent for the same button are combined into one key', () => { - send(0x01, 0x01, 0x01, 0x30, 0x01, 0x14, 0x01) - send(0x01, 0x01, 0x00, 0x30, 0x00, 0x14, 0x00) + test.each([ + ['Shift Up + Increase Difficulty + Select', [0x01, 0x30, 0x14], 'up'], + ['Shift Down + Decrease Difficulty + Back', [0x02, 0x31, 0x15], 'down'], + ['Shift Up + Increase Difficulty + Skip Interval', [0x01, 0x30, 0x32], 'up'], + ['Shift Up + Decrease Difficulty', [0x01, 0x31], 'r-shift-up'], + ['Increase Difficulty + Skip Interval', [0x30, 0x32], 'y'], + ['Skip Interval + Previous Interval + Select', [0x32, 0x36, 0x14], 'a'], + ['Shift Up + Shift Down', [0x01, 0x02], 'r-shift-up'], + ])('several actions for one button (%s) result in exactly one key', (_name, ids: number[], key) => { + send(0x01, ...ids.flatMap(id => [id, 0x01])) + send(0x01, ...ids.flatMap(id => [id, 0x00])) + expect(onKey).toHaveBeenCalledTimes(1) + expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key })) + }) + + test('a press is reported once all of its actions are released, also if released with separate messages', () => { + send(0x01, 0x01, 0x01, 0x30, 0x01) + send(0x01, 0x01, 0x00) + expect(onKey).not.toHaveBeenCalled() + + send(0x01, 0x30, 0x00) expect(onKey).toHaveBeenCalledTimes(1) expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key: 'up' })) }) + test('buttons pressed with separate messages are separate presses', () => { + send(0x01, 0x01, 0x01) + send(0x01, 0x32, 0x01) + send(0x01, 0x01, 0x00, 0x32, 0x00) + + expect(onKey).toHaveBeenCalledTimes(2) + expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key: 'r-shift-up' })) + expect(onKey).toHaveBeenCalledWith(expect.objectContaining({ key: 'a' })) + }) + test('release without press, unsupported buttons and other messages are ignored', () => { send(0x01, 0x01, 0x00) send(0x01, 0x14, 0x01) From b3225bc13a611eb9d4ef64996b90db061ba4ac6a Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Mon, 9 Nov 2026 09:45:04 +0100 Subject: [PATCH 5/7] Browse for smart trainers before OpenBikeControl devices Review feedback: start the Direct Connect browser first, so that smart trainers are found first. The mobile binding now supports several concurrent browsers (incyclist/mobile#481), so the order no longer decides which browser stays active. Co-Authored-By: Claude Opus 5.5 --- src/direct-connect/base/interface.ts | 12 ++++++------ src/direct-connect/base/interface.unit.test.ts | 9 +++++++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/direct-connect/base/interface.ts b/src/direct-connect/base/interface.ts index b1e366e..25cc8ce 100644 --- a/src/direct-connect/base/interface.ts +++ b/src/direct-connect/base/interface.ts @@ -292,7 +292,12 @@ export default class DirectConnectInterface extends EventEmitter implements IB } ) - // started before the Direct Connect browser, as some bindings only support one active browser + this.getBinding().mdns.find( {type:DC_TYPE},( service:MulticastDnsAnnouncement )=>{ + this.addService( service, DC_TYPE ) + + } ) + + // started after the Direct Connect browser, so that smart trainers are found first this.getBinding().mdns.find( {type:OBC_TYPE},( service:MulticastDnsAnnouncement )=>{ // some bindings deliver all announcements to all callbacks if (service.type && service.type!==OBC_TYPE) @@ -301,11 +306,6 @@ export default class DirectConnectInterface extends EventEmitter implements IB return this.addService( {...service, type:OBC_TYPE}, OBC_TYPE ) } ) - - this.getBinding().mdns.find( {type:DC_TYPE},( service:MulticastDnsAnnouncement )=>{ - this.addService( service, DC_TYPE ) - - } ) } async pauseBackgroundActivity():Promise { diff --git a/src/direct-connect/base/interface.unit.test.ts b/src/direct-connect/base/interface.unit.test.ts index 766cd39..d71353d 100644 --- a/src/direct-connect/base/interface.unit.test.ts +++ b/src/direct-connect/base/interface.unit.test.ts @@ -465,6 +465,15 @@ describe('DirectConnectInterface', () => { expect(dc.createPeripheralFromSettings({ interface: 'wifi', name: 'BikeControl', address: '10.0.0.7' })).toBeInstanceOf(OpenBikeControlPeripheral) }) + test('browses for smart trainers before OpenBikeControl devices', async () => { + mdns.find = jest.fn() + + await iface.connect() + const types = mdns.find.mock.calls.map(([filter]) => filter?.type).filter(Boolean) + expect(types.indexOf('wahoo-fitness-tnp')).toBeGreaterThanOrEqual(0) + expect(types.indexOf('wahoo-fitness-tnp')).toBeLessThan(types.indexOf('openbikecontrol')) + }) + test('ignores announcements of other types', async () => { const callbacks: Record void> = {} mdns.find = jest.fn((filter, cb) => { callbacks[filter?.type ?? 'unfiltered'] = cb }) From 66ed2d0ff666a6104f08da1a583ee91a34d0cd2a Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Mon, 9 Nov 2026 09:45:04 +0100 Subject: [PATCH 6/7] OpenBikeControl over Wi-Fi: split messages that arrive together, buffer split ones Button state messages have no length field, so a press and its release that arrived in one TCP read were treated as one message and the release was lost. A pair that repeats a button of the current message, or a 0x01/0x02 byte followed by a value that is not a valid Shift Up/Down state, now starts the next message. Incomplete messages are kept until the next read. Subscribing twice no longer registers a second callback, which reported every button press twice. Co-Authored-By: Claude Opus 5.5 --- src/direct-connect/base/peripheral.ts | 76 ++++++++++++++++--- .../base/peripheral.unit.test.ts | 58 ++++++++++++++ 2 files changed, 124 insertions(+), 10 deletions(-) diff --git a/src/direct-connect/base/peripheral.ts b/src/direct-connect/base/peripheral.ts index 0cbffa9..752dced 100644 --- a/src/direct-connect/base/peripheral.ts +++ b/src/direct-connect/base/peripheral.ts @@ -746,8 +746,11 @@ export class OpenBikeControlPeripheral extends DirectConnectPeripheral { async subscribe(characteristicUUID: string, callback?: (characteristicUuid: string, data: Buffer) => void): Promise { // the device sends button state messages without request const uuid = parseUUID(characteristicUUID) - if (!this.subscribed.includes(uuid)) - this.subscribed.push(uuid) + // already subscribed? A second callback would report every button press twice + if (this.subscribed.includes(uuid)) + return true + + this.subscribed.push(uuid) if (callback) { this.eventEmitter.on(uuid, (data)=>{ callback(characteristicUUID,data) @@ -776,33 +779,86 @@ export class OpenBikeControlPeripheral extends DirectConnectPeripheral { return Buffer.from([]) } + protected pending?:Buffer + + async disconnect(connectionLost?:boolean): Promise { + delete this.pending + return super.disconnect(connectionLost) + } + protected async onData(data:Buffer) { + const buffer = this.pending ? Buffer.concat([this.pending,data]) : data + delete this.pending + try { let offset = 0 - while (offsetbuffer.length) { + // incomplete, the rest will arrive with the next read + this.pending = Buffer.from(buffer.subarray(offset)) + return + } + const status = buffer.subarray(offset, offset+OBC_DEVICE_STATUS_LENGTH) this.logEvent({message:'device status', path:this.getPath(), battery:status[1], connected:status[2]===1, raw:status.toString('hex') }) offset += OBC_DEVICE_STATUS_LENGTH } else if (msgType===OBC_MSG_BUTTON_STATE) { - // button state messages don't contain a length, so the remaining data is treated as one message - const message = Buffer.from(data.subarray(offset)) + const end = this.getButtonStateEnd(buffer, offset) + if (end<0) { + // incomplete (odd number of bytes), the rest will arrive with the next read + this.pending = Buffer.from(buffer.subarray(offset)) + return + } + const message = Buffer.from(buffer.subarray(offset,end)) this.logEvent({message:'button state', path:this.getPath(), raw:message.toString('hex') }) this.eventEmitter.emit(parseUUID(OBC_BUTTON_STATE), message) - return + offset = end } else { - this.logEvent({message:'unknown message', path:this.getPath(), raw:data.subarray(offset).toString('hex') }) + this.logEvent({message:'unknown message', path:this.getPath(), raw:buffer.subarray(offset).toString('hex') }) return } } } catch(err) { - this.logEvent({message:'error', fn:'onData', error:err.message, stack:err.stack, path:this.getPath(), raw:data?.toString('hex')}) + this.logEvent({message:'error', fn:'onData', error:err.message, stack:err.stack, path:this.getPath(), raw:buffer?.toString('hex')}) } } + /** + * Returns the end of the button state message that starts at `offset`, or -1 if it is incomplete + * + * Button state messages don't contain a length, and the message types 0x01/0x02 are also button IDs + * (Shift Up/Down), so a message boundary can't be read from the stream directly. The next message starts + * where the next pair would + * - repeat a button of the current message (a message lists every button only once), e.g. press and release, or + * - start with 0x01/0x02 followed by a byte that is not a valid Shift Up/Down state (these buttons are digital) + */ + protected getButtonStateEnd(buffer:Buffer, offset:number):number { + const buttons = new Set() + let pos = offset+1 + while (pos=buffer.length) + return buttons.size>0 && this.isMessageType(id) ? pos : -1 + + const next = buffer[pos+1] + if (buttons.size>0 && this.isMessageType(id) && next>0x01) + return pos + + buttons.add(id) + pos += 2 + } + return buttons.size>0 ? pos : -1 + } + + protected isMessageType(byte:number):boolean { + return byte===OBC_MSG_BUTTON_STATE || byte===OBC_MSG_DEVICE_STATUS + } + } diff --git a/src/direct-connect/base/peripheral.unit.test.ts b/src/direct-connect/base/peripheral.unit.test.ts index 4f06e92..4287323 100644 --- a/src/direct-connect/base/peripheral.unit.test.ts +++ b/src/direct-connect/base/peripheral.unit.test.ts @@ -189,6 +189,64 @@ describe('DirectConnect Peripheral',()=>{ expect(callback).toHaveBeenCalledWith(BUTTON_STATE, M('0102010300')) }) + describe('messages that arrive together or split',()=>{ + let callback:any + beforeEach( async ()=>{ + callback = jest.fn() + await p.subscribe(BUTTON_STATE,callback) + }) + const received = ()=>callback.mock.calls.map( ([,data])=>data.toString('hex')) + + test('press and release of the same button in one read',async ()=>{ + await p.onData(M('010101010100')) + expect(received()).toEqual(['010101','010100']) + }) + + test('press and release of several buttons in one read',async ()=>{ + await p.onData(M('01100120010110002000')) + expect(received()).toEqual(['0110012001','0110002000']) + }) + + test('press of one button followed by a press of another button',async ()=>{ + await p.onData(M('011001012001')) + expect(received()).toEqual(['011001','012001']) + }) + + test('Shift Up and Shift Down pressed and released together in one read',async ()=>{ + await p.onData(M('01010102010101000200')) + expect(received()).toEqual(['0101010201','0101000200']) + }) + + test('button state followed by device status in one read',async ()=>{ + await p.onData(M('011001025501')) + expect(received()).toEqual(['011001']) + expect(p.logEvent).toHaveBeenCalledWith(expect.objectContaining({message:'device status', battery:0x55})) + }) + + test('a message split across two reads',async ()=>{ + await p.onData(M('0110')) + expect(callback).not.toHaveBeenCalled() + await p.onData(M('01')) + expect(received()).toEqual(['011001']) + }) + + test('a device status split across two reads',async ()=>{ + await p.onData(M('0255')) + await p.onData(M('01010101')) + expect(p.logEvent).toHaveBeenCalledWith(expect.objectContaining({message:'device status', battery:0x55})) + expect(received()).toEqual(['010101']) + }) + }) + + test('subscribing twice does not report a button press twice',async ()=>{ + const callback = jest.fn() + await p.subscribe(BUTTON_STATE,callback) + await p.subscribe(BUTTON_STATE,callback) + + await p.onData(M('010101')) + expect(callback).toHaveBeenCalledTimes(1) + }) + test('writes are sent unchanged',async ()=>{ const write = jest.fn() p.connect = jest.fn(async ()=>true) From 60dc8efb672a75add72f827c94b74b776e501f48 Mon Sep 17 00:00:00 2001 From: Jonas Acker Date: Mon, 9 Nov 2026 09:45:05 +0100 Subject: [PATCH 7/7] OpenBikeControl adapter: don't wait for data on start, tell same-named controllers apart Controllers only send data when a button is pressed, so the adapter overrides shouldWaitForData() (incyclist/devices#144). Two controllers with the same name (e.g. BikeControl on two devices) are now told apart by address, and the name shows the end of the address, as for Zwift Play. Co-Authored-By: Claude Opus 5.5 --- src/ble/openbikecontrol/adapter.ts | 17 +++++++++++++++ src/ble/openbikecontrol/adapter.unit.test.ts | 23 ++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 src/ble/openbikecontrol/adapter.unit.test.ts diff --git a/src/ble/openbikecontrol/adapter.ts b/src/ble/openbikecontrol/adapter.ts index 7bd726e..53dcf7a 100644 --- a/src/ble/openbikecontrol/adapter.ts +++ b/src/ble/openbikecontrol/adapter.ts @@ -54,6 +54,11 @@ export class OpenBikeControlAdapter extends BleAdapter 4 ? id.slice(-4).toUpperCase() : id.toUpperCase() + return addressHash ? `${settings.name} ${addressHash}` : settings.name + } + getDisplayName() { return this.getName() } @@ -78,5 +90,10 @@ export class OpenBikeControlAdapter extends BleAdapter { + + 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') + }) +})