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..53dcf7a --- /dev/null +++ b/src/ble/openbikecontrol/adapter.ts @@ -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{ + 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) + } + + 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 + } + + +} diff --git a/src/ble/openbikecontrol/adapter.unit.test.ts b/src/ble/openbikecontrol/adapter.unit.test.ts new file mode 100644 index 0000000..aefca6c --- /dev/null +++ b/src/ble/openbikecontrol/adapter.unit.test.ts @@ -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') + }) +}) 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/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..30ab635 --- /dev/null +++ b/src/ble/openbikecontrol/sensor.ts @@ -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([ + [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 = 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 + + // 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 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 { + 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..968a40a --- /dev/null +++ b/src/ble/openbikecontrol/sensor.unit.test.ts @@ -0,0 +1,144 @@ +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.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) + 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..25cc8ce 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 { beautifyUUID, BleAdapterFactory } from "../../ble/index.js"; +import { DirectConnectPeripheral, OpenBikeControlPeripheral } from "./peripheral.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"; 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,16 @@ export default class DirectConnectInterface extends EventEmitter implements IB 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) + return + if (service.serviceUUIDs?.length && !service.serviceUUIDs.some( uuid=>matches(uuid,OBC_SERVICE))) + return + this.addService( {...service, type:OBC_TYPE}, OBC_TYPE ) + } ) } async pauseBackgroundActivity():Promise { @@ -660,6 +674,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 +728,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 +854,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, diff --git a/src/direct-connect/base/interface.unit.test.ts b/src/direct-connect/base/interface.unit.test.ts index a079a03..d71353d 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,74 @@ 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('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 }) + + 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() + }) + + 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..752dced 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,157 @@ 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) + // 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) + }) + } + 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 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) { + 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) + offset = end + } + else { + 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: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 9d8d9ea..4287323 100644 --- a/src/direct-connect/base/peripheral.unit.test.ts +++ b/src/direct-connect/base/peripheral.unit.test.ts @@ -1,6 +1,6 @@ import { write } from "fs" import { MulticastDnsAnnouncement } from "../bindings" -import { DirectConnectPeripheral } from "./peripheral" +import { DirectConnectPeripheral, OpenBikeControlPeripheral } from "./peripheral" describe('DirectConnect Peripheral',()=>{ @@ -148,4 +148,117 @@ 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')) + }) + + 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) + 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})) + }) + }) +})