-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbluetooth-audio.service.ts
More file actions
2499 lines (2127 loc) · 81.4 KB
/
bluetooth-audio.service.ts
File metadata and controls
2499 lines (2127 loc) · 81.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Buffer } from 'buffer';
// @ts-ignore - callkeep service might not be resolvable in all contexts without barrel file updates
import { Alert, DeviceEventEmitter, NativeModules, PermissionsAndroid, Platform } from 'react-native';
import BleManager, { type BleManagerDidUpdateValueForCharacteristicEvent, BleScanCallbackType, BleScanMatchMode, BleScanMode, type BleState, type Peripheral, type PeripheralInfo } from 'react-native-ble-manager';
import { logger } from '@/lib/logging';
import { audioService } from '@/services/audio.service';
import { callKeepService } from '@/services/callkeep.service';
import { type AudioButtonEvent, type BluetoothAudioDevice, type Device, State, useBluetoothAudioStore } from '@/stores/app/bluetooth-audio-store';
// Lazy getters to avoid circular dependencies with livekit-store and useLiveKitCallStore
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getLiveKitCallStore = (): any => {
// Using import() for lazy loading to avoid circular dependencies
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('@/features/livekit-call/store/useLiveKitCallStore').useLiveKitCallStore;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getLiveKitStore = (): any => {
// Using import() for lazy loading to avoid circular dependencies
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('@/stores/app/livekit-store').useLiveKitStore;
};
// Standard Bluetooth UUIDs for audio services
const AUDIO_SERVICE_UUID = '0000110A-0000-1000-8000-00805F9B34FB'; // Advanced Audio Distribution Profile
const A2DP_SOURCE_UUID = '0000110A-0000-1000-8000-00805F9B34FB';
const HFP_SERVICE_UUID = '0000111E-0000-1000-8000-00805F9B34FB'; // Hands-Free Profile
const HSP_SERVICE_UUID = '00001108-0000-1000-8000-00805F9B34FB'; // Headset Profile
const AINA_HEADSET = 'D11C8116-A913-434D-A79D-97AE94A529B3';
const AINA_HEADSET_SERVICE = '127FACE1-CB21-11E5-93D0-0002A5D5C51B';
const AINA_HEADSET_SVC_PROP = '127FBEEF-CB21-11E5-93D0-0002A5D5C51B';
const B01INRICO_HEADSET = '2BD21C44-0198-4B92-9110-D622D53D8E37';
//const B01INRICO_HEADSET_SERVICE = '6666';
const B01INRICO_HEADSET_SERVICE = '00006666-0000-1000-8000-00805F9B34FB';
//const B01INRICO_HEADSET_SERVICE_CHAR = '8888';
const B01INRICO_HEADSET_SERVICE_CHAR = '00008888-0000-1000-8000-00805F9B34FB';
const HYS_HEADSET = '3CD31C55-A914-435E-B80E-98AF95B630C4';
const HYS_HEADSET_SERVICE = '0000FFE0-0000-1000-8000-00805F9B34FB';
//const HYS_HEADSET_SERVICE = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E';
//const HYS_HEADSET_SERVICE_CHAR = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E';
const HYS_HEADSET_SERVICE_CHAR = '00002902-0000-1000-8000-00805F9B34FB';
// Common button control characteristic UUIDs (varies by manufacturer)
const BUTTON_CONTROL_UUIDS = [
'0000FE59-0000-1000-8000-00805F9B34FB', // Common button control
'0000180F-0000-1000-8000-00805F9B34FB', // Battery Service (often includes button data)
'00001812-0000-1000-8000-00805F9B34FB', // Human Interface Device Service
];
class BluetoothAudioService {
private static instance: BluetoothAudioService;
private connectedDevice: Device | null = null;
private scanTimeout: ReturnType<typeof setTimeout> | null = null;
private connectionTimeout: NodeJS.Timeout | null = null;
private isInitialized: boolean = false;
private hasAttemptedPreferredDeviceConnection: boolean = false;
private eventListeners: { remove: () => void }[] = [];
private readonly isWeb = Platform.OS === 'web';
private monitoringStartedAt: number | null = null;
private monitoringWatchdogInterval: ReturnType<typeof setInterval> | null = null;
private readPollingInterval: ReturnType<typeof setInterval> | null = null;
private isReadPollingInFlight: boolean = false;
private monitoredReadCharacteristics: { serviceUuid: string; characteristicUuid: string; lastHexValue: string | null }[] = [];
private mediaButtonEventListener: { remove: () => void } | null = null;
private mediaButtonListeningActive: boolean = false;
private pttPressActive: boolean = false;
private pttReleaseFallbackTimeout: ReturnType<typeof setTimeout> | null = null;
private micApplyRetryTimeout: ReturnType<typeof setTimeout> | null = null;
private retryMicEnabled: boolean | null = null;
private pendingMicEnabled: boolean | null = null;
private isApplyingMicState: boolean = false;
static getInstance(): BluetoothAudioService {
if (!BluetoothAudioService.instance) {
BluetoothAudioService.instance = new BluetoothAudioService();
}
return BluetoothAudioService.instance;
}
/**
* Initialize the Bluetooth service and attempt to connect to the preferred device
*/
async initialize(): Promise<void> {
if (this.isInitialized) {
return;
}
// BLE is not available on web — skip initialization entirely
if (Platform.OS === 'web') {
logger.info({
message: 'Bluetooth Audio Service not available on web, skipping initialization',
});
this.isInitialized = true;
return;
}
try {
// Initialize BLE Manager
await BleManager.start({ showAlert: false });
this.setupEventListeners();
this.isInitialized = true;
// Check if we have permissions
const hasPermissions = await this.requestPermissions();
if (!hasPermissions) {
logger.warn({
message: 'Bluetooth permissions not granted, skipping initialization',
});
return;
}
// Check Bluetooth state
const state = await this.checkBluetoothState();
if (state !== State.PoweredOn) {
logger.info({
message: 'Bluetooth not powered on, skipping initialization',
context: { state },
});
return;
}
// Attempt to connect to preferred device
await this.attemptPreferredDeviceConnection();
} catch (error) {
logger.error({
message: 'Failed to initialize Bluetooth Audio Service',
context: { error },
});
}
}
/**
* Attempt to connect to a preferred device from storage.
* This method can only be called once per service instance.
*/
private async attemptPreferredDeviceConnection(): Promise<void> {
// Prevent multiple calls to this method
if (this.hasAttemptedPreferredDeviceConnection) {
logger.debug({
message: 'Preferred device connection already attempted, skipping',
});
return;
}
this.hasAttemptedPreferredDeviceConnection = true;
try {
// Load preferred device from storage
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { getItem } = require('@/lib/storage');
const preferredDevice: { id: string; name: string } | null = getItem('preferredBluetoothDevice');
if (preferredDevice) {
logger.info({
message: 'Found preferred Bluetooth device, attempting to connect',
context: { deviceId: preferredDevice.id, deviceName: preferredDevice.name },
});
// Set the preferred device in the store
useBluetoothAudioStore.getState().setPreferredDevice(preferredDevice);
if (preferredDevice.id === 'system-audio') {
logger.info({
message: 'Preferred device is System Audio, ensuring no specialized device is connected',
});
// We are already in system audio mode by default if no device is connected
return;
}
// Try to connect directly to the preferred device
try {
await this.connectToDevice(preferredDevice.id);
logger.info({
message: 'Successfully connected to preferred Bluetooth device',
context: { deviceId: preferredDevice.id },
});
} catch (error) {
logger.warn({
message: 'Failed to connect to preferred Bluetooth device, will scan for it',
context: { deviceId: preferredDevice.id, error },
});
// If direct connection fails, start scanning to find the device
this.startScanning(5000); // 5 second scan
}
} else {
logger.info({
message: 'No preferred Bluetooth device found',
});
}
} catch (error) {
logger.error({
message: 'Failed to attempt preferred device connection',
context: { error },
});
}
}
private addEventListener(listener: { remove: () => void }): void {
if (!this.eventListeners.includes(listener)) {
this.eventListeners.push(listener);
}
}
private removeEventListener(listener: { remove: () => void } | null): void {
if (!listener) {
return;
}
this.eventListeners = this.eventListeners.filter((registeredListener) => registeredListener !== listener);
}
private setupEventListeners(): void {
// Bluetooth state change listener
const stateListener = BleManager.onDidUpdateState(this.handleBluetoothStateChange.bind(this));
this.addEventListener(stateListener);
// Device disconnection listener
const disconnectListener = BleManager.onDisconnectPeripheral(this.handleDeviceDisconnected.bind(this));
this.addEventListener(disconnectListener);
// Device discovered listener
const discoverListener = BleManager.onDiscoverPeripheral(this.handleDeviceDiscovered.bind(this));
this.addEventListener(discoverListener);
// Characteristic value update listener
const valueUpdateListener = BleManager.onDidUpdateValueForCharacteristic(this.handleCharacteristicValueUpdate.bind(this));
this.addEventListener(valueUpdateListener);
// Stop scan listener
const stopScanListener = BleManager.onStopScan(this.handleScanStopped.bind(this));
this.addEventListener(stopScanListener);
}
private handleBluetoothStateChange(args: { state: BleState }): void {
const state = this.mapBleStateToState(args.state);
logger.info({
message: 'Bluetooth state changed',
context: { state },
});
useBluetoothAudioStore.getState().setBluetoothState(state);
if (state === State.PoweredOff || state === State.Unauthorized) {
this.handleBluetoothDisabled();
} else if (state === State.PoweredOn && this.isInitialized && !this.hasAttemptedPreferredDeviceConnection) {
// If Bluetooth is turned back on, try to reconnect to preferred device
this.attemptReconnectToPreferredDevice();
}
}
private mapBleStateToState(bleState: BleState): State {
switch (bleState) {
case 'on':
return State.PoweredOn;
case 'off':
return State.PoweredOff;
case 'turning_on':
return State.Resetting;
case 'turning_off':
return State.Resetting;
default:
return State.Unknown;
}
}
private handleDeviceDiscovered(device: Peripheral): void {
if (!device || !device.id || !device.advertising || !device.advertising.isConnectable) {
return;
}
// Define RSSI threshold for strong signals (typical range: -100 to -20 dBm)
const STRONG_RSSI_THRESHOLD = -95; // Relaxed threshold to improve discovery
// Check RSSI signal strength - only proceed with strong signals
if (!device.rssi || device.rssi < STRONG_RSSI_THRESHOLD) {
logger.debug({
message: 'Device ignored due to weak RSSI',
context: { deviceId: device.id, rssi: device.rssi, threshold: STRONG_RSSI_THRESHOLD },
});
return;
}
// Log discovered device for debugging
logger.debug({
message: 'Device discovered during scan with strong RSSI',
context: {
deviceId: device.id,
deviceName: device.name,
rssi: device.rssi,
advertising: device.advertising,
},
});
// Check if this is an audio device
if (this.isAudioDevice(device)) {
this.handleDeviceFound(device);
}
}
private handleCharacteristicValueUpdate(data: BleManagerDidUpdateValueForCharacteristicEvent): void {
// Convert the value array to a base64 string to match the old API
const value = Buffer.from(data.value).toString('base64');
if (this.connectedDevice && data.peripheral !== this.connectedDevice.id) {
return;
}
// Handle button events based on service and characteristic UUIDs
this.handleButtonEventFromCharacteristic(data.peripheral, data.service, data.characteristic, value);
}
private handleScanStopped(): void {
useBluetoothAudioStore.getState().setIsScanning(false);
logger.info({
message: 'Bluetooth scan stopped',
});
}
private handleButtonEventFromCharacteristic(peripheralId: string, serviceUuid: string, characteristicUuid: string, value: string): void {
// Route to appropriate handler based on service/characteristic
if (this.areUuidsEqual(serviceUuid, AINA_HEADSET_SERVICE) && this.areUuidsEqual(characteristicUuid, AINA_HEADSET_SVC_PROP)) {
this.handleAinaButtonEvent(value);
} else if (this.areUuidsEqual(serviceUuid, B01INRICO_HEADSET_SERVICE) && this.areUuidsEqual(characteristicUuid, B01INRICO_HEADSET_SERVICE_CHAR)) {
this.handleB01InricoButtonEvent(value);
} else if (this.areUuidsEqual(serviceUuid, HYS_HEADSET_SERVICE) && this.areUuidsEqual(characteristicUuid, HYS_HEADSET_SERVICE_CHAR)) {
this.handleHYSButtonEvent(value);
} else if (BUTTON_CONTROL_UUIDS.some((uuid) => this.areUuidsEqual(characteristicUuid, uuid))) {
this.handleGenericButtonEvent(value);
} else if (this.connectedDevice && this.connectedDevice.id === peripheralId && this.getDeviceType(this.connectedDevice) === 'specialized' && this.isLikelyButtonCharacteristic(serviceUuid, characteristicUuid)) {
this.handleGenericButtonEvent(value);
} else if (this.connectedDevice && this.connectedDevice.id === peripheralId && this.getDeviceType(this.connectedDevice) === 'specialized') {
logger.debug({
message: 'Ignoring characteristic update for specialized device (not identified as button control)',
context: {
peripheralId,
serviceUuid,
characteristicUuid,
},
});
}
}
private async attemptReconnectToPreferredDevice(): Promise<void> {
logger.info({
message: 'Bluetooth turned on, attempting preferred device connection',
});
// Reset the flag to allow reconnection attempt
this.hasAttemptedPreferredDeviceConnection = false;
// Attempt preferred device connection
await this.attemptPreferredDeviceConnection();
}
private handleBluetoothDisabled(): void {
this.stopScanning();
this.disconnectDevice();
useBluetoothAudioStore.getState().clearDevices();
}
async requestPermissions(): Promise<boolean> {
if (this.isWeb) return true;
if (Platform.OS === 'android') {
try {
const permissions = [PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN, PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT, PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION];
const results = await PermissionsAndroid.requestMultiple(permissions);
const allGranted = Object.values(results).every((result) => result === PermissionsAndroid.RESULTS.GRANTED);
logger.info({
message: 'Bluetooth permissions requested',
context: { results, allGranted },
});
return allGranted;
} catch (error) {
logger.error({
message: 'Failed to request Bluetooth permissions',
context: { error },
});
return false;
}
}
return true; // iOS permissions are handled via Info.plist
}
async checkBluetoothState(): Promise<State> {
if (this.isWeb) return State.PoweredOff;
try {
const bleState = await BleManager.checkState();
return this.mapBleStateToState(bleState);
} catch (error) {
logger.error({
message: 'Failed to check Bluetooth state',
context: { error },
});
return State.Unknown;
}
}
async startScanning(durationMs: number = 10000): Promise<void> {
if (this.isWeb) return;
const hasPermissions = await this.requestPermissions();
if (!hasPermissions) {
throw new Error('Bluetooth permissions not granted');
}
const state = await this.checkBluetoothState();
if (state !== State.PoweredOn) {
throw new Error(`Bluetooth is ${state}. Please enable Bluetooth.`);
}
if (useBluetoothAudioStore.getState().isScanning) {
logger.warn({ message: 'Scan already in progress, ignoring request', context: { durationMs } });
return;
}
useBluetoothAudioStore.getState().setIsScanning(true);
useBluetoothAudioStore.getState().clearDevices();
logger.info({
message: 'Starting Bluetooth audio device scan',
context: { durationMs },
});
try {
// Start scanning for all devices - filtering will be done in the discovery handler
await BleManager.scan([], durationMs / 1000, false, {
matchMode: BleScanMatchMode.Sticky,
scanMode: BleScanMode.LowLatency,
callbackType: BleScanCallbackType.AllMatches,
});
// Set timeout to update UI when scan completes
this.scanTimeout = setTimeout(() => {
this.handleScanStopped();
logger.info({
message: 'Bluetooth scan completed',
context: {
durationMs,
devicesFound: useBluetoothAudioStore.getState().availableDevices.length,
},
});
}, durationMs);
} catch (error) {
logger.error({
message: 'Failed to start Bluetooth scan',
context: { error },
});
useBluetoothAudioStore.getState().setIsScanning(false);
throw error;
}
}
/**
* Debug method to scan for ALL devices with detailed logging
* Use this for troubleshooting device discovery issues
*/
async startDebugScanning(durationMs: number = 15000): Promise<void> {
if (this.isWeb) return;
const hasPermissions = await this.requestPermissions();
if (!hasPermissions) {
throw new Error('Bluetooth permissions not granted');
}
const state = await this.checkBluetoothState();
if (state !== State.PoweredOn) {
throw new Error(`Bluetooth is ${state}. Please enable Bluetooth.`);
}
// Stop any existing scan first
await this.stopScanning();
useBluetoothAudioStore.getState().setIsScanning(true);
useBluetoothAudioStore.getState().clearDevices();
logger.info({
message: 'Starting DEBUG Bluetooth device scan (all devices)',
context: { durationMs },
});
try {
// Start scanning for all devices with detailed logging
await BleManager.scan([], durationMs / 1000, true); // Allow duplicates for debugging
// Set timeout to update UI when scan completes
this.scanTimeout = setTimeout(() => {
this.handleScanStopped();
logger.info({
message: 'DEBUG: Bluetooth scan completed',
context: {
durationMs,
totalDevicesFound: useBluetoothAudioStore.getState().availableDevices.length,
},
});
}, durationMs);
} catch (error) {
logger.error({
message: 'Failed to start DEBUG Bluetooth scan',
context: { error },
});
useBluetoothAudioStore.getState().setIsScanning(false);
throw error;
}
}
private isAudioDevice(device: Device): boolean {
const name = device.name?.toLowerCase() || '';
const audioKeywords = ['speaker', 'headset', 'earbuds', 'headphone', 'audio', 'mic', 'sound', 'wireless', 'bluetooth', 'bt', 'aina', 'inrico', 'hys', 'b01', 'ptt'];
// Check if device name contains audio-related keywords
const hasAudioKeyword = audioKeywords.some((keyword) => name.includes(keyword));
// Check if device has audio service UUIDs - use advertising data
const advertisingData = device.advertising;
const hasAudioService =
advertisingData?.serviceUUIDs?.some((uuid: string) => {
const upperUuid = uuid.toUpperCase();
return [AUDIO_SERVICE_UUID, HFP_SERVICE_UUID, HSP_SERVICE_UUID, AINA_HEADSET_SERVICE, B01INRICO_HEADSET_SERVICE, HYS_HEADSET_SERVICE].includes(upperUuid);
}) || false;
// Check manufacturer data for known audio device manufacturers
const hasAudioManufacturerData = advertisingData?.manufacturerData ? this.hasAudioManufacturerData(advertisingData.manufacturerData) : false;
// Check service data for audio device indicators
const hasAudioServiceData = advertisingData?.serviceData ? this.hasAudioServiceData(advertisingData.serviceData) : false;
// Log device details for debugging
logger.debug({
message: 'Evaluating device for audio capability',
context: {
deviceId: device.id,
deviceName: device.name,
hasAudioKeyword,
hasAudioService,
hasAudioManufacturerData,
hasAudioServiceData,
serviceUUIDs: advertisingData?.serviceUUIDs,
manufacturerData: advertisingData?.manufacturerData,
serviceData: advertisingData?.serviceData,
},
});
return hasAudioKeyword || hasAudioService || hasAudioManufacturerData || hasAudioServiceData;
}
private hasAudioManufacturerData(manufacturerData: string | { [key: string]: string } | Record<string, any>): boolean {
// Known audio device manufacturer IDs (check manufacturer data for audio device indicators)
// This is a simplified check - you'd need to implement device-specific logic
if (typeof manufacturerData === 'string') {
// Simple string check for audio-related manufacturer data
return manufacturerData.toLowerCase().includes('audio') || manufacturerData.toLowerCase().includes('headset') || manufacturerData.toLowerCase().includes('speaker');
}
const audioManufacturerIds = [
'0x004C', // Apple
'0x001D', // Qualcomm
'0x000F', // Broadcom
'0x0087', // Mediatek
'0x02E5', // Realtek
];
return Object.keys(manufacturerData).some((key) => audioManufacturerIds.includes(key) || audioManufacturerIds.includes(`0x${key}`));
}
private hasAudioServiceData(serviceData: string | { [key: string]: string } | Record<string, any>): boolean {
try {
// Service data contains information about the device's capabilities
// Audio devices often advertise their capabilities in service data
if (typeof serviceData === 'string') {
// Try to decode hex string service data
const decodedData = this.decodeServiceDataString(serviceData);
return this.analyzeServiceDataForAudio(decodedData);
}
if (typeof serviceData === 'object' && serviceData !== null) {
// Service data is an object with service UUIDs as keys and data as values
return Object.entries(serviceData).some(([serviceUuid, data]) => {
if (typeof data !== 'string') {
return false; // Skip non-string data
}
const upperServiceUuid = serviceUuid.toUpperCase();
// Check if the service UUID itself indicates audio capability
const isAudioServiceUuid = [
AUDIO_SERVICE_UUID,
HFP_SERVICE_UUID,
HSP_SERVICE_UUID,
AINA_HEADSET_SERVICE,
B01INRICO_HEADSET_SERVICE,
HYS_HEADSET_SERVICE,
'0000FE59-0000-1000-8000-00805F9B34FB', // Common audio service
'0000180F-0000-1000-8000-00805F9B34FB', // Battery service (often used by audio devices)
].some((uuid) => uuid.toUpperCase() === upperServiceUuid);
if (isAudioServiceUuid) {
logger.debug({
message: 'Found audio service UUID in service data',
context: {
serviceUuid: upperServiceUuid,
data: data,
},
});
return true;
}
// Analyze the service data content for audio indicators
if (typeof data === 'string') {
const decodedData = this.decodeServiceDataString(data);
return this.analyzeServiceDataForAudio(decodedData);
}
return false;
});
}
return false;
} catch (error) {
logger.debug({
message: 'Error analyzing service data for audio capability',
context: { error, serviceData },
});
return false;
}
}
private getDeviceType(device: Device): 'specialized' | 'system' {
const advertisingData = device.advertising;
const serviceUUIDs = advertisingData?.serviceUUIDs || [];
// Check for specialized PTT service UUIDs
const isSpecialized = serviceUUIDs.some((uuid: string) => {
return [AINA_HEADSET_SERVICE, B01INRICO_HEADSET_SERVICE, HYS_HEADSET_SERVICE].some((specialized) => this.areUuidsEqual(uuid, specialized));
});
if (isSpecialized) {
return 'specialized';
}
// Check by name for known specialized devices if UUID check fails
const name = device.name?.toLowerCase() || '';
if (name.includes('aina') || name.includes('inrico') || name.includes('hys')) {
return 'specialized';
}
return 'system';
}
private decodeServiceDataString(data: string): Buffer {
try {
// Service data can be in various formats: hex string, base64, etc.
// Try hex first (most common for BLE advertising data)
if (/^[0-9A-Fa-f]+$/.test(data)) {
return Buffer.from(data, 'hex');
}
// Try base64
try {
return Buffer.from(data, 'base64');
} catch {
// Fall back to treating as raw string
return Buffer.from(data, 'utf8');
}
} catch (error) {
logger.debug({
message: 'Failed to decode service data string',
context: { error, data },
});
return Buffer.alloc(0);
}
}
private analyzeServiceDataForAudio(data: Buffer): boolean {
if (!data || data.length === 0) {
return false;
}
try {
// Convert to hex string for pattern matching
const hexData = data.toString('hex').toLowerCase();
// Look for common audio device indicators in service data
const audioPatterns = [
// Common audio capability flags (these are example patterns)
'0001', // Audio sink capability
'0002', // Audio source capability
'0004', // Headset capability
'0008', // Hands-free capability
'1108', // HSP service class
'110a', // A2DP sink service class
'110b', // A2DP source service class
'111e', // HFP service class
'1203', // Audio/Video Remote Control Profile
// Known manufacturer-specific patterns
'aina', // AINA device identifier
'inrico', // Inrico device identifier
'hys', // HYS device identifier
];
const hasAudioPattern = audioPatterns.some((pattern) => hexData.includes(pattern));
// Check for specific byte patterns that indicate audio capabilities
const hasAudioCapabilityBytes = this.checkAudioCapabilityBytes(data);
// Check for device class indicators (if present in service data)
const hasAudioDeviceClass = this.checkAudioDeviceClass(data);
logger.debug({
message: 'Service data audio analysis',
context: {
hexData,
hasAudioPattern,
hasAudioCapabilityBytes,
hasAudioDeviceClass,
dataLength: data.length,
},
});
return hasAudioPattern || hasAudioCapabilityBytes || hasAudioDeviceClass;
} catch (error) {
logger.debug({
message: 'Error in service data audio analysis',
context: { error },
});
return false;
}
}
private checkAudioCapabilityBytes(data: Buffer): boolean {
// Check for common audio capability indicators in binary data
if (data.length < 2) return false;
try {
// Check for Bluetooth device class indicators (if embedded in service data)
// Major device class for Audio/Video devices is 0x04
// Minor device classes include: 0x01 (headset), 0x02 (hands-free), 0x04 (microphone), 0x05 (speaker), etc.
for (let i = 0; i < data.length - 1; i++) {
const byte1 = data[i];
const byte2 = data[i + 1];
// Check for audio device class patterns
if ((byte1 & 0x1f) === 0x04) {
// Major class: Audio/Video
const minorClass = (byte2 >> 2) & 0x3f;
if ([0x01, 0x02, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a].includes(minorClass)) {
logger.debug({
message: 'Found audio device class in service data',
context: {
majorClass: byte1 & 0x1f,
minorClass,
position: i,
},
});
return true;
}
}
// Check for HID service class (some audio devices also support HID)
if (byte1 === 0x05 && byte2 === 0x80) {
// HID pointing device
return true;
}
}
return false;
} catch (error) {
logger.debug({
message: 'Error checking audio capability bytes',
context: { error },
});
return false;
}
}
private checkAudioDeviceClass(data: Buffer): boolean {
// Look for Bluetooth Device Class (CoD) patterns that indicate audio devices
if (data.length < 3) return false;
try {
// Device class is typically 3 bytes: service classes (2 bytes) + device class (1 byte)
for (let i = 0; i <= data.length - 3; i++) {
const cod = (data[i + 2] << 16) | (data[i + 1] << 8) | data[i];
// Extract major and minor device class
const majorDeviceClass = (cod >> 8) & 0x1f;
const minorDeviceClass = (cod >> 2) & 0x3f;
// Major device class 0x04 = Audio/Video devices
if (majorDeviceClass === 0x04) {
logger.debug({
message: 'Found audio/video device class in service data',
context: {
cod: cod.toString(16),
majorClass: majorDeviceClass,
minorClass: minorDeviceClass,
position: i,
},
});
return true;
}
// Check service class bits for audio services
// Service class bits are in bits 13-23 of the 24-bit CoD
const serviceClasses = (cod >> 13) & 0x7ff;
const hasAudioService = (serviceClasses & 0x200) !== 0; // Audio bit (bit 21 -> bit 8 in service class)
const hasRenderingService = (serviceClasses & 0x40) !== 0; // Rendering bit (bit 18 -> bit 5 in service class)
if (hasAudioService || hasRenderingService) {
logger.debug({
message: 'Found audio service class bits in service data',
context: {
cod: cod.toString(16),
hasAudioService,
hasRenderingService,
position: i,
},
});
return true;
}
}
return false;
} catch (error) {
logger.debug({
message: 'Error checking audio device class',
context: { error },
});
return false;
}
}
private handleDeviceFound(device: Device): void {
const audioDevice: BluetoothAudioDevice = {
id: device.id,
name: device.name || null,
rssi: device.rssi || undefined,
isConnected: false,
hasAudioCapability: true,
supportsMicrophoneControl: this.supportsMicrophoneControl(device),
device,
type: this.getDeviceType(device),
};
logger.info({
message: 'Audio device found',
context: {
deviceId: device.id,
deviceName: device.name,
rssi: device.rssi,
supportsMicControl: audioDevice.supportsMicrophoneControl,
},
});
useBluetoothAudioStore.getState().addDevice(audioDevice);
// Check if this is the preferred device and auto-connect
this.checkAndAutoConnectPreferredDevice(audioDevice);
}
private async checkAndAutoConnectPreferredDevice(device: BluetoothAudioDevice): Promise<void> {
const { preferredDevice, connectedDevice } = useBluetoothAudioStore.getState();
// Only auto-connect if:
// 1. This is the preferred device
// 2. No device is currently connected
// 3. We're not already in the process of connecting
if (preferredDevice?.id === device.id && !connectedDevice && !this.connectionTimeout) {
try {
logger.info({
message: 'Auto-connecting to preferred Bluetooth device',
context: { deviceId: device.id, deviceName: device.name },
});
await this.connectToDevice(device.id);
} catch (error) {
logger.warn({
message: 'Failed to auto-connect to preferred Bluetooth device',
context: { deviceId: device.id, error },
});
}
}
}
private supportsMicrophoneControl(device: Device): boolean {
// Check if device likely supports microphone control based on service UUIDs
const advertisingData = device.advertising;
const serviceUUIDs = advertisingData?.serviceUUIDs || [];
return serviceUUIDs.some((uuid: string) => [HFP_SERVICE_UUID, HSP_SERVICE_UUID].includes(uuid.toUpperCase()));
}
async stopScanning(): Promise<void> {
if (this.isWeb) return;
try {
await BleManager.stopScan();
} catch (error) {
logger.debug({
message: 'Error stopping scan',
context: { error },
});
}
if (this.scanTimeout) {
clearTimeout(this.scanTimeout);
this.scanTimeout = null;
}
useBluetoothAudioStore.getState().setIsScanning(false);
logger.info({
message: 'Bluetooth scan stopped',
});
}
async connectToDevice(deviceId: string): Promise<void> {
if (this.isWeb) return;
try {
useBluetoothAudioStore.getState().clearConnectionError();
useBluetoothAudioStore.getState().setIsConnecting(true);
// Ensure scanning is stopped before connecting
// Connecting while scanning often fails on Android
await this.stopScanning();
// Small delay to allow radio to switch modes
await new Promise((resolve) => setTimeout(resolve, 500));
// Connect to the device
logger.info({
message: 'Attempting to connect to device via BleManager',
context: { deviceId },
});
await BleManager.connect(deviceId);
logger.info({
message: 'Connected to Bluetooth audio device',
context: { deviceId },
});
// Get the connected peripheral info
const connectedPeripherals = await BleManager.getConnectedPeripherals();
const device = connectedPeripherals.find((p) => p.id === deviceId);
if (!device) {
throw new Error('Device not found after connection');
}
// Discover services and characteristics
logger.info({
message: 'Retrieving services which triggers discovery',
context: { deviceId },
});
const peripheralInfo = await BleManager.retrieveServices(deviceId);
logger.info({
message: 'Services retrieved successfully',
context: {
deviceId,
serviceCount: peripheralInfo.services?.length,
services: peripheralInfo.services?.map((s: any) => s.uuid),
},
});
this.connectedDevice = device;
useBluetoothAudioStore.getState().setConnectedDevice({
id: device.id,
name: device.name || null,
rssi: device.rssi || undefined,
isConnected: true,
hasAudioCapability: true,
supportsMicrophoneControl: this.supportsMicrophoneControl(device),
device,
type: this.getDeviceType(device),
});
// Special handling for specialized PTT devices to prevent mute loops
if (this.getDeviceType(device) === 'specialized') {
callKeepService.removeMuteListener();
logger.info({
message: 'Specialized PTT device connected - CallKeep mute listener removed',
context: { deviceId },
});
} else {
// Ensure listener is active for system devices
callKeepService.restoreMuteListener();
}
// Set up button event monitoring with peripheral info
await this.setupButtonEventMonitoring(device, peripheralInfo);