diff --git a/src/bindings/direct-connect/mdns/binding.test.ts b/src/bindings/direct-connect/mdns/binding.test.ts new file mode 100644 index 00000000..ea473031 --- /dev/null +++ b/src/bindings/direct-connect/mdns/binding.test.ts @@ -0,0 +1,111 @@ +import { EventEmitter } from 'events' + +// react-native-zeroconf's Zeroconf is an EventEmitter driven by native events, with only one +// active scan. A plain EventEmitter stand-in lets the test fire 'resolved' events on demand. +class FakeZeroconf extends EventEmitter { + scan = jest.fn() + stop = jest.fn() +} + +let mockZeroconf: FakeZeroconf + +jest.mock('react-native-zeroconf', () => jest.fn().mockImplementation(() => mockZeroconf)) +jest.mock('gd-eventlog', () => ({ + EventLogger: jest.fn().mockImplementation(() => ({ logEvent: jest.fn() })), +})) + +import { ReactNativeMdnsBinding } from './binding' + +const resolved = (name: string, fullName: string, txt: Record = {}) => ({ + name, fullName, addresses: ['192.168.1.50'], port: 4711, txt, +}) + +describe('ReactNativeMdnsBinding', () => { + let binding: ReactNativeMdnsBinding + + beforeEach(() => { + jest.useFakeTimers() + jest.spyOn(console, 'log').mockImplementation(() => {}) + mockZeroconf = new FakeZeroconf() + binding = new ReactNativeMdnsBinding() + binding.connect() + }) + + afterEach(() => { + binding.disconnect() + jest.useRealTimers() + jest.restoreAllMocks() + }) + + it('scans a single type without rotating', () => { + binding.find({ type: 'wahoo-fitness-tnp' }, jest.fn()) + expect(mockZeroconf.scan).toHaveBeenCalledWith('wahoo-fitness-tnp', 'tcp', 'local.') + + jest.advanceTimersByTime(20000) + expect(mockZeroconf.scan).toHaveBeenCalledTimes(1) + }) + + it('starts a new type immediately and then rotates through all types', () => { + binding.find({ type: 'openbikecontrol' }, jest.fn()) + binding.find({ type: 'wahoo-fitness-tnp' }, jest.fn()) + binding.find({ type: 'wahoo-fitness-tnp' }, jest.fn()) // same type again: no new scan + + expect(mockZeroconf.scan.mock.calls.map(c => c[0])).toEqual(['openbikecontrol', 'wahoo-fitness-tnp']) + + jest.advanceTimersByTime(5000) + jest.advanceTimersByTime(5000) + expect(mockZeroconf.scan.mock.calls.map(c => c[0])).toEqual(['openbikecontrol', 'wahoo-fitness-tnp', 'openbikecontrol', 'wahoo-fitness-tnp']) + }) + + it('delivers a result only to the callbacks of the type it was found under', () => { + const onOBC = jest.fn() + const onWahoo = jest.fn() + binding.find({ type: 'openbikecontrol' }, onOBC) + binding.find({ type: 'wahoo-fitness-tnp' }, onWahoo) + + // iOS: host name + type, Android: host + type with leading dot + mockZeroconf.emit('resolved', resolved('BikeControl', 'iPhone.local._openbikecontrol._tcp.')) + mockZeroconf.emit('resolved', resolved('KICKR', '192.168.1.51._wahoo-fitness-tnp._tcp', { 'ble-service-uuids': '0x1826,0x1818' })) + + expect(onOBC).toHaveBeenCalledTimes(1) + expect(onOBC).toHaveBeenCalledWith(expect.objectContaining({ type: 'openbikecontrol', name: 'BikeControl', address: '192.168.1.50', port: 4711 })) + expect(onWahoo).toHaveBeenCalledTimes(1) + expect(onWahoo).toHaveBeenCalledWith(expect.objectContaining({ type: 'wahoo-fitness-tnp', name: 'KICKR', serviceUUIDs: ['0x1826', '0x1818'] })) + }) + + it('falls back to the active scan if the type cannot be taken from the result', () => { + const onOBC = jest.fn() + const onWahoo = jest.fn() + binding.find({ type: 'openbikecontrol' }, onOBC) + binding.find({ type: 'wahoo-fitness-tnp' }, onWahoo) + + mockZeroconf.emit('resolved', resolved('KICKR', 'KICKR')) + + expect(onWahoo).toHaveBeenCalledWith(expect.objectContaining({ type: 'wahoo-fitness-tnp', name: 'KICKR' })) + expect(onOBC).not.toHaveBeenCalled() + }) + + it('ignores results without address', () => { + const onOBC = jest.fn() + binding.find({ type: 'openbikecontrol' }, onOBC) + + mockZeroconf.emit('resolved', { name: 'BikeControl', fullName: 'iPhone.local._openbikecontrol._tcp.' }) + expect(onOBC).not.toHaveBeenCalled() + }) + + it('disconnect stops the rotation and forgets all browsers', () => { + binding.find({ type: 'openbikecontrol' }, jest.fn()) + binding.find({ type: 'wahoo-fitness-tnp' }, jest.fn()) + binding.disconnect() + expect(mockZeroconf.stop).toHaveBeenCalled() + + jest.advanceTimersByTime(20000) + expect(mockZeroconf.scan).toHaveBeenCalledTimes(2) + + mockZeroconf = new FakeZeroconf() + binding.connect() + binding.find({ type: 'wahoo-fitness-tnp' }, jest.fn()) + jest.advanceTimersByTime(20000) + expect(mockZeroconf.scan).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/bindings/direct-connect/mdns/binding.ts b/src/bindings/direct-connect/mdns/binding.ts index 385f5266..69ee2970 100644 --- a/src/bindings/direct-connect/mdns/binding.ts +++ b/src/bindings/direct-connect/mdns/binding.ts @@ -2,15 +2,28 @@ import { EventLogger } from 'gd-eventlog' import Zeroconf from 'react-native-zeroconf' import type { BrowserConfig, MulticastDnsAnnouncement, MulticastDnsBinding } from '../types' +// react-native-zeroconf only supports one active scan, so the browsers take turns +const BROWSER_ROTATION_INTERVAL = 5000 // ms + +type Browser = { + type: string + protocol: 'tcp' | 'udp' + callbacks: Array<(svc: MulticastDnsAnnouncement) => void> +} + export class ReactNativeMdnsBinding implements MulticastDnsBinding{ private bonjour:Zeroconf|undefined private _logger!: EventLogger + private browsers: Browser[] = [] + private activeBrowser: Browser|undefined + private rotationTimer: ReturnType|undefined connect():void { try { console.log('[DirectConnect].connect') if (!this.bonjour) { this.bonjour = new Zeroconf() + this.bonjour.on('resolved', this.onResolved.bind(this)) this.logger.logEvent( {message:'Connect to bonjour '}) } @@ -34,6 +47,13 @@ export class ReactNativeMdnsBinding implements MulticastDnsBinding{ disconnect():void { try { console.log('[DirectConnect].disconnect') + if (this.rotationTimer) { + clearInterval(this.rotationTimer) + this.rotationTimer = undefined + } + this.browsers = [] + this.activeBrowser = undefined + if (this.bonjour) { this.logger.logEvent( {message:'Disconnect from bonjour '}) this.bonjour.stop() @@ -63,40 +83,72 @@ export class ReactNativeMdnsBinding implements MulticastDnsBinding{ const type = opts?.type ?? 'directconnect' const protocol = opts?.protocol ?? 'tcp' - const domain = 'local.' - - - console.log('[DirectConnect].find', opts,{type,protocol,domain}) - - this.bonjour.on('resolved', (service:any) => { - if (!service.addresses?.length) return - console.log('[DirectConnect] got announcement', service) + console.log('[DirectConnect].find', opts,{type,protocol}) - const announcement: MulticastDnsAnnouncement = { - type, - protocol, - address: service.addresses[0], - port: service.port, - name: service.name, - serialNo: service.txt?.serialNo, - serviceUUIDs:service.txt?.['ble-service-uuids']?.split(','), - transport:'tcp' + let browser = this.browsers.find( b=> b.type===type && b.protocol===protocol) + if (!browser) { + browser = {type,protocol,callbacks:[]} + this.browsers.push(browser) - } + // a new browser is started immediately, then all browsers take turns + this.scan(browser) + if (!this.rotationTimer && this.browsers.length>1) + this.rotationTimer = setInterval( this.scanNext.bind(this), BROWSER_ROTATION_INTERVAL) + } + if (onup) + browser.callbacks.push(onup) - onup?.(announcement) - }) + } + catch(err:any) { + this.logError(err,'find') + } + } - this.bonjour.scan(type, protocol, domain) + protected scan(browser:Browser) { + this.activeBrowser = browser + this.bonjour?.scan(browser.type, browser.protocol, 'local.') + } + protected scanNext() { + try { + const idx = this.activeBrowser ? this.browsers.indexOf(this.activeBrowser) : -1 + this.scan(this.browsers[(idx+1) % this.browsers.length]) } catch(err:any) { - this.logError(err,'find') + this.logError(err,'scanNext') } + } + + protected onResolved(service:any) { + if (!service.addresses?.length) return + + console.log('[DirectConnect] got announcement', service) + + // a service might get resolved after the scan already switched to the next browser + const browser = this.getBrowser(service) ?? this.activeBrowser + if (!browser) return + + const announcement: MulticastDnsAnnouncement = { + type: browser.type, + protocol: browser.protocol, + address: service.addresses[0], + port: service.port, + name: service.name, + serialNo: service.txt?.serialNo, + serviceUUIDs:service.txt?.['ble-service-uuids']?.split(','), + transport:'tcp' + } + + browser.callbacks.forEach( cb => cb(announcement)) + } + // fullName is the host name followed by the service type, e.g. 'iPad.local._wahoo-fitness-tnp._tcp.' + protected getBrowser(service:any):Browser|undefined { + const match = /_([^.]+)\._(tcp|udp)\.?$/.exec(service.fullName ?? '') + if (!match) return + return this.browsers.find( b=> b.type===match[1] && b.protocol===match[2]) } - -} \ No newline at end of file +}