@capgo/capacitor-bluetooth-low-energy 8.0.1 → 8.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -1,6 +1,738 @@
1
1
  var capacitorBluetoothLowEnergy = (function (exports, core) {
2
2
  'use strict';
3
3
 
4
+ const PLUGIN_NAME = 'BluetoothLowEnergy';
5
+ const DEFAULT_SCAN_TIMEOUT = 15000;
6
+ const BLUETOOTH_BASE_UUID_SUFFIX = '-0000-1000-8000-00805f9b34fb';
7
+ const BLUETOOTH_SERVICE_UUID_ALIASES = {
8
+ alert_notification: 0x1811,
9
+ automation_io: 0x1815,
10
+ battery_service: 0x180f,
11
+ binary_sensor: 0x183b,
12
+ blood_pressure: 0x1810,
13
+ body_composition: 0x181b,
14
+ bond_management: 0x181e,
15
+ continuous_glucose_monitoring: 0x181f,
16
+ coordinated_set_identification_service: 0x1846,
17
+ current_time: 0x1805,
18
+ cycling_power: 0x1818,
19
+ cycling_speed_and_cadence: 0x1816,
20
+ device_information: 0x180a,
21
+ device_time: 0x1847,
22
+ emergency_configuration: 0x183c,
23
+ environmental_sensing: 0x181a,
24
+ fitness_machine: 0x1826,
25
+ generic_access: 0x1800,
26
+ generic_attribute: 0x1801,
27
+ generic_media_control_service: 0x1849,
28
+ generic_telephone_bearer_service: 0x184c,
29
+ glucose: 0x1808,
30
+ health_thermometer: 0x1809,
31
+ heart_rate: 0x180d,
32
+ http_proxy: 0x1823,
33
+ human_interface_device: 0x1812,
34
+ immediate_alert: 0x1802,
35
+ indoor_positioning: 0x1821,
36
+ insulin_delivery: 0x183a,
37
+ internet_protocol_support: 0x1820,
38
+ link_loss: 0x1803,
39
+ location_and_navigation: 0x1819,
40
+ media_control_service: 0x1848,
41
+ mesh_provisioning: 0x1827,
42
+ mesh_proxy: 0x1828,
43
+ microphone_control: 0x184d,
44
+ next_dst_change: 0x1807,
45
+ object_transfer: 0x1825,
46
+ phone_alert_status: 0x180e,
47
+ physical_activity_monitor: 0x183e,
48
+ pulse_oximeter: 0x1822,
49
+ reconnection_configuration: 0x1829,
50
+ reference_time_update: 0x1806,
51
+ running_speed_and_cadence: 0x1814,
52
+ scan_parameters: 0x1813,
53
+ transport_discovery: 0x1824,
54
+ tx_power: 0x1804,
55
+ user_data: 0x181c,
56
+ volume_control: 0x1844,
57
+ volume_offset_control: 0x1845,
58
+ weight_scale: 0x181d,
59
+ };
60
+ class ShimEventEmitter {
61
+ constructor() {
62
+ this.listeners = new Map();
63
+ }
64
+ addEventListener(type, listener) {
65
+ var _a;
66
+ if (!type) {
67
+ return;
68
+ }
69
+ const typeListeners = (_a = this.listeners.get(type)) !== null && _a !== void 0 ? _a : new Set();
70
+ typeListeners.add(listener);
71
+ this.listeners.set(type, typeListeners);
72
+ }
73
+ removeEventListener(type, listener) {
74
+ const typeListeners = this.listeners.get(type);
75
+ if (!typeListeners) {
76
+ return;
77
+ }
78
+ typeListeners.delete(listener);
79
+ if (typeListeners.size === 0) {
80
+ this.listeners.delete(type);
81
+ }
82
+ }
83
+ dispatchShimEvent(type, target) {
84
+ const event = { type, target };
85
+ const typeListeners = this.listeners.get(type);
86
+ typeListeners === null || typeListeners === void 0 ? void 0 : typeListeners.forEach((listener) => {
87
+ listener(event);
88
+ });
89
+ const handler = target[`on${type}`];
90
+ if (typeof handler === 'function') {
91
+ handler(event);
92
+ }
93
+ }
94
+ }
95
+ class NativeWebBluetoothShim {
96
+ constructor(root, plugin) {
97
+ this.root = root;
98
+ this.plugin = plugin;
99
+ this.initializedPromise = null;
100
+ this.listenersPromise = null;
101
+ this.pendingRequest = null;
102
+ this.deviceCache = new Map();
103
+ this.characteristicCache = new Map();
104
+ this.exposedDeviceIds = new Set();
105
+ this.listenerHandles = [];
106
+ }
107
+ install() {
108
+ var _a;
109
+ var _b;
110
+ if (this.root.__capgoBluetoothLowEnergyShimInstalled || !this.root.navigator || this.root.navigator.bluetooth) {
111
+ return;
112
+ }
113
+ const bluetooth = new BluetoothShimFacade(this);
114
+ Object.defineProperty(this.root.navigator, 'bluetooth', {
115
+ configurable: true,
116
+ enumerable: true,
117
+ value: bluetooth,
118
+ writable: false,
119
+ });
120
+ this.root.BluetoothDevice = BluetoothDeviceShim;
121
+ this.root.BluetoothRemoteGATTServer = BluetoothRemoteGATTServerShim;
122
+ this.root.BluetoothRemoteGATTService = BluetoothRemoteGATTServiceShim;
123
+ this.root.BluetoothRemoteGATTCharacteristic = BluetoothRemoteGATTCharacteristicShim;
124
+ this.root.BluetoothRemoteGATTDescriptor = BluetoothRemoteGATTDescriptorShim;
125
+ (_a = (_b = this.root).BluetoothUUID) !== null && _a !== void 0 ? _a : (_b.BluetoothUUID = {
126
+ canonicalUUID,
127
+ getService: canonicalUUID,
128
+ getCharacteristic: canonicalUUID,
129
+ getDescriptor: canonicalUUID,
130
+ });
131
+ this.root.__capgoBluetoothLowEnergyShimInstalled = true;
132
+ }
133
+ async getAvailability() {
134
+ await this.ensureInitialized();
135
+ const { available } = await this.plugin.isAvailable();
136
+ return available === true;
137
+ }
138
+ async getDevices() {
139
+ await this.ensureInitialized();
140
+ await this.ensureListeners();
141
+ const { devices } = await this.plugin.getConnectedDevices();
142
+ devices.forEach((deviceData) => {
143
+ const device = this.getOrCreateDevice(deviceData);
144
+ device.gatt.setConnected(true);
145
+ this.exposedDeviceIds.add(device.id);
146
+ });
147
+ return Array.from(this.exposedDeviceIds)
148
+ .map((deviceId) => this.deviceCache.get(deviceId))
149
+ .filter((device) => typeof device !== 'undefined');
150
+ }
151
+ async requestDevice(options) {
152
+ var _a;
153
+ if (!options || (options.acceptAllDevices !== true && (!options.filters || options.filters.length === 0))) {
154
+ throw new TypeError('requestDevice requires filters or acceptAllDevices: true.');
155
+ }
156
+ if (options.acceptAllDevices !== true &&
157
+ ((_a = options.filters) === null || _a === void 0 ? void 0 : _a.some((filter) => (!filter.services || filter.services.length === 0) &&
158
+ typeof filter.name !== 'string' &&
159
+ typeof filter.namePrefix !== 'string'))) {
160
+ throw new TypeError('requestDevice filters must specify a name, namePrefix, or at least one service.');
161
+ }
162
+ if (this.pendingRequest) {
163
+ throw createBluetoothError('InvalidStateError', 'A Bluetooth request is already in progress.');
164
+ }
165
+ await this.ensureListeners();
166
+ await this.ensureScanPrerequisites();
167
+ await this.stopScanSilently();
168
+ return new Promise((resolve, reject) => {
169
+ const timeoutId = setTimeout(() => {
170
+ if (!this.pendingRequest) {
171
+ return;
172
+ }
173
+ this.pendingRequest = null;
174
+ void this.stopScanSilently();
175
+ reject(createBluetoothError('NotFoundError', 'No matching Bluetooth device was found.'));
176
+ }, DEFAULT_SCAN_TIMEOUT);
177
+ this.pendingRequest = {
178
+ options,
179
+ reject,
180
+ resolve: (device) => {
181
+ device.gatt.setConnected(false);
182
+ resolve(device);
183
+ },
184
+ timeoutId,
185
+ };
186
+ void this.plugin
187
+ .startScan({
188
+ allowDuplicates: true,
189
+ services: mergeRequestedServices(options.filters),
190
+ timeout: DEFAULT_SCAN_TIMEOUT,
191
+ })
192
+ .catch((error) => {
193
+ if (!this.pendingRequest) {
194
+ return;
195
+ }
196
+ clearTimeout(timeoutId);
197
+ this.pendingRequest = null;
198
+ reject(normalizeError(error));
199
+ });
200
+ });
201
+ }
202
+ async connectDevice(device) {
203
+ await this.ensureInitialized();
204
+ await this.ensureListeners();
205
+ await this.plugin.connect({ deviceId: device.id });
206
+ device.gatt.setConnected(true);
207
+ device.setServices(null);
208
+ return device.gatt;
209
+ }
210
+ disconnectDevice(device) {
211
+ if (!device.gatt.connected) {
212
+ return;
213
+ }
214
+ device.gatt.setConnected(false);
215
+ device.setServices(null);
216
+ void this.plugin.disconnect({ deviceId: device.id }).catch(() => undefined);
217
+ }
218
+ async getPrimaryServices(device, serviceUuid) {
219
+ const services = await this.ensureServices(device);
220
+ const mapped = services.map((serviceData) => new BluetoothRemoteGATTServiceShim(this, device, serviceData));
221
+ if (typeof serviceUuid === 'undefined') {
222
+ return mapped;
223
+ }
224
+ const normalized = normalizeUuid(serviceUuid);
225
+ return mapped.filter((service) => normalizeUuid(service.uuid) === normalized);
226
+ }
227
+ async getPrimaryService(device, serviceUuid) {
228
+ const services = await this.getPrimaryServices(device, serviceUuid);
229
+ const service = services[0];
230
+ if (!service) {
231
+ throw createBluetoothError('NotFoundError', 'Requested Bluetooth service was not found.');
232
+ }
233
+ return service;
234
+ }
235
+ async getCharacteristics(device, serviceUuid, characteristicUuid) {
236
+ const service = await this.findService(device, serviceUuid);
237
+ const characteristics = service.characteristics.map((characteristicData) => {
238
+ const characteristic = this.getOrCreateCharacteristic(device, service.uuid, characteristicData);
239
+ characteristic.service = new BluetoothRemoteGATTServiceShim(this, device, service);
240
+ return characteristic;
241
+ });
242
+ if (typeof characteristicUuid === 'undefined') {
243
+ return characteristics;
244
+ }
245
+ const normalizedCharacteristicUuid = normalizeUuid(characteristicUuid);
246
+ return characteristics.filter((characteristic) => normalizeUuid(characteristic.uuid) === normalizedCharacteristicUuid);
247
+ }
248
+ async getCharacteristic(device, serviceUuid, characteristicUuid) {
249
+ const { characteristic, service } = await this.findCharacteristic(device, serviceUuid, characteristicUuid);
250
+ const shim = this.getOrCreateCharacteristic(device, service.uuid, characteristic);
251
+ shim.service = new BluetoothRemoteGATTServiceShim(this, device, service);
252
+ return shim;
253
+ }
254
+ async getDescriptors(device, serviceUuid, characteristicUuid, descriptorUuid) {
255
+ const { characteristic } = await this.findCharacteristic(device, serviceUuid, characteristicUuid);
256
+ const normalizedDescriptorUuid = descriptorUuid ? normalizeUuid(descriptorUuid) : null;
257
+ return characteristic.descriptors
258
+ .filter((descriptorData) => {
259
+ if (!normalizedDescriptorUuid) {
260
+ return true;
261
+ }
262
+ return normalizeUuid(descriptorData.uuid) === normalizedDescriptorUuid;
263
+ })
264
+ .map((descriptorData) => {
265
+ const descriptor = new BluetoothRemoteGATTDescriptorShim(this, device, normalizeUuid(serviceUuid), normalizeUuid(characteristicUuid), descriptorData);
266
+ return descriptor;
267
+ });
268
+ }
269
+ async getDescriptor(device, serviceUuid, characteristicUuid, descriptorUuid) {
270
+ const descriptor = (await this.getDescriptors(device, serviceUuid, characteristicUuid, descriptorUuid))[0];
271
+ if (!descriptor) {
272
+ throw createBluetoothError('NotFoundError', 'Requested Bluetooth descriptor was not found.');
273
+ }
274
+ return descriptor;
275
+ }
276
+ async readCharacteristic(device, serviceUuid, characteristicUuid) {
277
+ const { value } = await this.plugin.readCharacteristic({
278
+ characteristic: normalizeUuid(characteristicUuid),
279
+ deviceId: device.id,
280
+ service: normalizeUuid(serviceUuid),
281
+ });
282
+ return toDataView(value);
283
+ }
284
+ async writeCharacteristic(device, serviceUuid, characteristicUuid, value, type) {
285
+ await this.plugin.writeCharacteristic({
286
+ characteristic: normalizeUuid(characteristicUuid),
287
+ deviceId: device.id,
288
+ service: normalizeUuid(serviceUuid),
289
+ type,
290
+ value: Array.from(toUint8Array(value)),
291
+ });
292
+ }
293
+ async startNotifications(device, serviceUuid, characteristicUuid) {
294
+ await this.ensureListeners();
295
+ await this.plugin.startCharacteristicNotifications({
296
+ characteristic: normalizeUuid(characteristicUuid),
297
+ deviceId: device.id,
298
+ service: normalizeUuid(serviceUuid),
299
+ });
300
+ }
301
+ async stopNotifications(device, serviceUuid, characteristicUuid) {
302
+ await this.plugin.stopCharacteristicNotifications({
303
+ characteristic: normalizeUuid(characteristicUuid),
304
+ deviceId: device.id,
305
+ service: normalizeUuid(serviceUuid),
306
+ });
307
+ }
308
+ async readDescriptor(device, serviceUuid, characteristicUuid, descriptorUuid) {
309
+ const { value } = await this.plugin.readDescriptor({
310
+ characteristic: normalizeUuid(characteristicUuid),
311
+ descriptor: normalizeUuid(descriptorUuid),
312
+ deviceId: device.id,
313
+ service: normalizeUuid(serviceUuid),
314
+ });
315
+ return toDataView(value);
316
+ }
317
+ async writeDescriptor(device, serviceUuid, characteristicUuid, descriptorUuid, value) {
318
+ await this.plugin.writeDescriptor({
319
+ characteristic: normalizeUuid(characteristicUuid),
320
+ descriptor: normalizeUuid(descriptorUuid),
321
+ deviceId: device.id,
322
+ service: normalizeUuid(serviceUuid),
323
+ value: Array.from(toUint8Array(value)),
324
+ });
325
+ }
326
+ async ensureInitialized() {
327
+ if (!this.initializedPromise) {
328
+ this.initializedPromise = this.plugin.initialize({ mode: 'central' }).catch((error) => {
329
+ this.initializedPromise = null;
330
+ throw normalizeError(error);
331
+ });
332
+ }
333
+ await this.initializedPromise;
334
+ }
335
+ async ensureListeners() {
336
+ if (!this.listenersPromise) {
337
+ this.listenersPromise = Promise.all([
338
+ this.plugin.addListener('deviceScanned', (event) => this.handleDeviceScanned(event)),
339
+ this.plugin.addListener('deviceDisconnected', (event) => this.handleDeviceDisconnected(event)),
340
+ this.plugin.addListener('characteristicChanged', (event) => this.handleCharacteristicChanged(event)),
341
+ ]).then((handles) => {
342
+ this.listenerHandles.push(...handles);
343
+ });
344
+ }
345
+ await this.listenersPromise;
346
+ }
347
+ handleDeviceScanned(event) {
348
+ if (!this.pendingRequest || !event.device) {
349
+ return;
350
+ }
351
+ if (!matchesRequestOptions(event.device, this.pendingRequest.options)) {
352
+ return;
353
+ }
354
+ const device = this.getOrCreateDevice(event.device);
355
+ this.exposedDeviceIds.add(device.id);
356
+ const request = this.pendingRequest;
357
+ this.pendingRequest = null;
358
+ clearTimeout(request.timeoutId);
359
+ void this.stopScanSilently();
360
+ request.resolve(device);
361
+ }
362
+ handleDeviceDisconnected(event) {
363
+ const device = this.deviceCache.get(event.deviceId);
364
+ device === null || device === void 0 ? void 0 : device.notifyDisconnected();
365
+ }
366
+ handleCharacteristicChanged(event) {
367
+ const key = createCharacteristicKey(event.deviceId, event.service, event.characteristic);
368
+ const characteristic = this.characteristicCache.get(key);
369
+ characteristic === null || characteristic === void 0 ? void 0 : characteristic.handleValueChange(event.value);
370
+ }
371
+ async ensureScanPrerequisites() {
372
+ if (!(await this.getAvailability())) {
373
+ throw createBluetoothError('NotSupportedError', 'Bluetooth Low Energy is not available on this device.');
374
+ }
375
+ const { enabled } = await this.plugin.isEnabled();
376
+ if (!enabled) {
377
+ throw createBluetoothError('NotFoundError', 'Bluetooth is disabled on this device.');
378
+ }
379
+ const permissions = await this.plugin.requestPermissions();
380
+ if (permissions.bluetooth === 'denied' || permissions.location === 'denied') {
381
+ throw createBluetoothError('NotAllowedError', 'Bluetooth permissions were denied.');
382
+ }
383
+ const location = await this.plugin.isLocationEnabled();
384
+ if (location.enabled === false) {
385
+ throw createBluetoothError('NotFoundError', 'Location services must be enabled for Bluetooth scanning.');
386
+ }
387
+ }
388
+ async ensureServices(device) {
389
+ const cachedServices = device.getServices();
390
+ if (cachedServices) {
391
+ return cachedServices;
392
+ }
393
+ if (!device.gatt.connected) {
394
+ throw createBluetoothError('NetworkError', 'Device is not connected.');
395
+ }
396
+ await this.plugin.discoverServices({ deviceId: device.id });
397
+ const { services } = await this.plugin.getServices({ deviceId: device.id });
398
+ device.setServices(services);
399
+ return services;
400
+ }
401
+ async findService(device, serviceUuid) {
402
+ const services = await this.ensureServices(device);
403
+ const normalized = normalizeUuid(serviceUuid);
404
+ const service = services.find((entry) => normalizeUuid(entry.uuid) === normalized);
405
+ if (!service) {
406
+ throw createBluetoothError('NotFoundError', 'Requested Bluetooth service was not found.');
407
+ }
408
+ return service;
409
+ }
410
+ async findCharacteristic(device, serviceUuid, characteristicUuid) {
411
+ const service = await this.findService(device, serviceUuid);
412
+ const normalized = normalizeUuid(characteristicUuid);
413
+ const characteristic = service.characteristics.find((entry) => normalizeUuid(entry.uuid) === normalized);
414
+ if (!characteristic) {
415
+ throw createBluetoothError('NotFoundError', 'Requested Bluetooth characteristic was not found.');
416
+ }
417
+ return { characteristic, service };
418
+ }
419
+ getOrCreateDevice(deviceData) {
420
+ const existingDevice = this.deviceCache.get(deviceData.deviceId);
421
+ if (existingDevice) {
422
+ existingDevice.updateMetadata(deviceData);
423
+ return existingDevice;
424
+ }
425
+ const device = new BluetoothDeviceShim(this, deviceData);
426
+ this.deviceCache.set(deviceData.deviceId, device);
427
+ return device;
428
+ }
429
+ getOrCreateCharacteristic(device, serviceUuid, characteristicData) {
430
+ const key = createCharacteristicKey(device.id, serviceUuid, characteristicData.uuid);
431
+ const existingCharacteristic = this.characteristicCache.get(key);
432
+ if (existingCharacteristic) {
433
+ existingCharacteristic.update(characteristicData);
434
+ return existingCharacteristic;
435
+ }
436
+ const characteristic = new BluetoothRemoteGATTCharacteristicShim(this, device, serviceUuid, characteristicData);
437
+ this.characteristicCache.set(key, characteristic);
438
+ return characteristic;
439
+ }
440
+ async stopScanSilently() {
441
+ try {
442
+ await this.plugin.stopScan();
443
+ }
444
+ catch (_a) {
445
+ // Ignore stale scan errors.
446
+ }
447
+ }
448
+ }
449
+ class BluetoothDeviceShim extends ShimEventEmitter {
450
+ constructor(shim, deviceData) {
451
+ super();
452
+ this.services = null;
453
+ this.id = deviceData.deviceId;
454
+ this.name = deviceData.name;
455
+ this.gatt = new BluetoothRemoteGATTServerShim(shim, this);
456
+ this.updateMetadata(deviceData);
457
+ }
458
+ updateMetadata(deviceData) {
459
+ this.name = deviceData.name;
460
+ this.rssi = deviceData.rssi;
461
+ this.manufacturerData = deviceData.manufacturerData;
462
+ this.serviceUuids = deviceData.serviceUuids;
463
+ }
464
+ getServices() {
465
+ return this.services;
466
+ }
467
+ setServices(services) {
468
+ this.services = services;
469
+ }
470
+ notifyDisconnected() {
471
+ this.gatt.setConnected(false);
472
+ this.services = null;
473
+ this.dispatchShimEvent('gattserverdisconnected', this);
474
+ }
475
+ async watchAdvertisements() {
476
+ throw createBluetoothError('NotSupportedError', 'watchAdvertisements is not implemented by the Capacitor shim.');
477
+ }
478
+ }
479
+ class BluetoothRemoteGATTServerShim {
480
+ constructor(shim, device) {
481
+ this.shim = shim;
482
+ this.device = device;
483
+ this.connected = false;
484
+ }
485
+ setConnected(connected) {
486
+ this.connected = connected;
487
+ }
488
+ async connect() {
489
+ return this.shim.connectDevice(this.device);
490
+ }
491
+ disconnect() {
492
+ this.shim.disconnectDevice(this.device);
493
+ }
494
+ async getPrimaryServices(serviceUuid) {
495
+ return this.shim.getPrimaryServices(this.device, serviceUuid);
496
+ }
497
+ async getPrimaryService(serviceUuid) {
498
+ return this.shim.getPrimaryService(this.device, serviceUuid);
499
+ }
500
+ }
501
+ class BluetoothRemoteGATTServiceShim {
502
+ constructor(shim, device, serviceData) {
503
+ this.shim = shim;
504
+ this.device = device;
505
+ this.serviceData = serviceData;
506
+ this.isPrimary = true;
507
+ }
508
+ get uuid() {
509
+ return this.serviceData.uuid;
510
+ }
511
+ async getCharacteristics(characteristicUuid) {
512
+ return this.shim.getCharacteristics(this.device, this.uuid, characteristicUuid);
513
+ }
514
+ async getCharacteristic(characteristicUuid) {
515
+ return this.shim.getCharacteristic(this.device, this.uuid, characteristicUuid);
516
+ }
517
+ }
518
+ class BluetoothRemoteGATTCharacteristicShim extends ShimEventEmitter {
519
+ constructor(shim, device, serviceUuid, characteristicData) {
520
+ super();
521
+ this.shim = shim;
522
+ this.device = device;
523
+ this.serviceUuid = serviceUuid;
524
+ this.characteristicData = characteristicData;
525
+ this.service = null;
526
+ this.value = null;
527
+ }
528
+ get uuid() {
529
+ return this.characteristicData.uuid;
530
+ }
531
+ get properties() {
532
+ return this.characteristicData.properties;
533
+ }
534
+ update(characteristicData) {
535
+ this.characteristicData = characteristicData;
536
+ }
537
+ async getDescriptors(descriptorUuid) {
538
+ const descriptors = await this.shim.getDescriptors(this.device, this.serviceUuid, this.uuid, descriptorUuid);
539
+ descriptors.forEach((descriptor) => {
540
+ descriptor.characteristic = this;
541
+ });
542
+ return descriptors;
543
+ }
544
+ async getDescriptor(descriptorUuid) {
545
+ const descriptor = await this.shim.getDescriptor(this.device, this.serviceUuid, this.uuid, descriptorUuid);
546
+ descriptor.characteristic = this;
547
+ return descriptor;
548
+ }
549
+ async readValue() {
550
+ this.value = await this.shim.readCharacteristic(this.device, this.serviceUuid, this.uuid);
551
+ return this.value;
552
+ }
553
+ async writeValue(value) {
554
+ await this.writeValueWithResponse(value);
555
+ }
556
+ async writeValueWithResponse(value) {
557
+ await this.shim.writeCharacteristic(this.device, this.serviceUuid, this.uuid, value, 'withResponse');
558
+ }
559
+ async writeValueWithoutResponse(value) {
560
+ await this.shim.writeCharacteristic(this.device, this.serviceUuid, this.uuid, value, 'withoutResponse');
561
+ }
562
+ async startNotifications() {
563
+ await this.shim.startNotifications(this.device, this.serviceUuid, this.uuid);
564
+ return this;
565
+ }
566
+ async stopNotifications() {
567
+ await this.shim.stopNotifications(this.device, this.serviceUuid, this.uuid);
568
+ return this;
569
+ }
570
+ handleValueChange(value) {
571
+ this.value = toDataView(value);
572
+ this.dispatchShimEvent('characteristicvaluechanged', this);
573
+ }
574
+ }
575
+ class BluetoothRemoteGATTDescriptorShim {
576
+ constructor(shim, device, serviceUuid, characteristicUuid, descriptorData) {
577
+ this.shim = shim;
578
+ this.device = device;
579
+ this.serviceUuid = serviceUuid;
580
+ this.characteristicUuid = characteristicUuid;
581
+ this.descriptorData = descriptorData;
582
+ this.characteristic = null;
583
+ this.value = null;
584
+ }
585
+ get uuid() {
586
+ return this.descriptorData.uuid;
587
+ }
588
+ async readValue() {
589
+ this.value = await this.shim.readDescriptor(this.device, this.serviceUuid, this.characteristicUuid, this.uuid);
590
+ return this.value;
591
+ }
592
+ async writeValue(value) {
593
+ await this.shim.writeDescriptor(this.device, this.serviceUuid, this.characteristicUuid, this.uuid, value);
594
+ }
595
+ }
596
+ class BluetoothShimFacade extends ShimEventEmitter {
597
+ constructor(shim) {
598
+ super();
599
+ this.shim = shim;
600
+ }
601
+ async getAvailability() {
602
+ return this.shim.getAvailability();
603
+ }
604
+ async getDevices() {
605
+ return this.shim.getDevices();
606
+ }
607
+ async requestDevice(options) {
608
+ return this.shim.requestDevice(options);
609
+ }
610
+ }
611
+ function mergeRequestedServices(filters) {
612
+ if (!filters || filters.some((filter) => !filter.services || filter.services.length === 0)) {
613
+ return [];
614
+ }
615
+ const services = new Set();
616
+ filters.forEach((filter) => {
617
+ var _a;
618
+ (_a = filter.services) === null || _a === void 0 ? void 0 : _a.forEach((service) => {
619
+ services.add(normalizeUuid(service));
620
+ });
621
+ });
622
+ return Array.from(services);
623
+ }
624
+ function matchesRequestOptions(device, options) {
625
+ var _a;
626
+ if (options.acceptAllDevices) {
627
+ return true;
628
+ }
629
+ if (!options.filters || options.filters.length === 0) {
630
+ return false;
631
+ }
632
+ const advertisedServices = new Set(((_a = device.serviceUuids) !== null && _a !== void 0 ? _a : []).map((serviceUuid) => normalizeUuid(serviceUuid)));
633
+ return options.filters.some((filter) => {
634
+ var _a, _b;
635
+ const hasServiceConstraint = Boolean(filter.services && filter.services.length > 0);
636
+ const hasNameConstraint = typeof filter.name === 'string';
637
+ const hasNamePrefixConstraint = typeof filter.namePrefix === 'string';
638
+ if (!hasServiceConstraint && !hasNameConstraint && !hasNamePrefixConstraint) {
639
+ return false;
640
+ }
641
+ if (filter.name && device.name !== filter.name) {
642
+ return false;
643
+ }
644
+ if (filter.namePrefix) {
645
+ if (!((_a = device.name) === null || _a === void 0 ? void 0 : _a.startsWith(filter.namePrefix))) {
646
+ return false;
647
+ }
648
+ }
649
+ if (!hasServiceConstraint) {
650
+ return true;
651
+ }
652
+ const services = (_b = filter.services) !== null && _b !== void 0 ? _b : [];
653
+ return services.every((service) => advertisedServices.has(normalizeUuid(service)));
654
+ });
655
+ }
656
+ function createCharacteristicKey(deviceId, serviceUuid, characteristicUuid) {
657
+ return `${deviceId}::${normalizeUuid(serviceUuid)}::${normalizeUuid(characteristicUuid)}`;
658
+ }
659
+ function normalizeUuid(value) {
660
+ return canonicalUUID(value);
661
+ }
662
+ function canonicalUUID(value) {
663
+ if (typeof value === 'number' && Number.isFinite(value)) {
664
+ return `${value.toString(16).padStart(8, '0')}${BLUETOOTH_BASE_UUID_SUFFIX}`;
665
+ }
666
+ const trimmed = String(value).trim().toLowerCase();
667
+ if (trimmed in BLUETOOTH_SERVICE_UUID_ALIASES) {
668
+ return `${BLUETOOTH_SERVICE_UUID_ALIASES[trimmed].toString(16).padStart(8, '0')}${BLUETOOTH_BASE_UUID_SUFFIX}`;
669
+ }
670
+ if (/^0x[0-9a-f]+$/iu.test(trimmed)) {
671
+ return `${trimmed.slice(2).padStart(8, '0')}${BLUETOOTH_BASE_UUID_SUFFIX}`;
672
+ }
673
+ if (/^[0-9a-f]{4}$/iu.test(trimmed) || /^[0-9a-f]{8}$/iu.test(trimmed)) {
674
+ return `${trimmed.padStart(8, '0')}${BLUETOOTH_BASE_UUID_SUFFIX}`;
675
+ }
676
+ if (/^[0-9a-f]{32}$/iu.test(trimmed)) {
677
+ return trimmed.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/u, '$1-$2-$3-$4-$5');
678
+ }
679
+ return trimmed;
680
+ }
681
+ function toDataView(value) {
682
+ const bytes = value instanceof Uint8Array
683
+ ? value
684
+ : value instanceof DataView
685
+ ? new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength))
686
+ : ArrayBuffer.isView(value)
687
+ ? new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength))
688
+ : value instanceof ArrayBuffer
689
+ ? new Uint8Array(value.slice(0))
690
+ : Uint8Array.from(value !== null && value !== void 0 ? value : []);
691
+ return new DataView(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
692
+ }
693
+ function toUint8Array(value) {
694
+ if (value instanceof Uint8Array) {
695
+ return new Uint8Array(value);
696
+ }
697
+ if (value instanceof DataView) {
698
+ return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
699
+ }
700
+ if (ArrayBuffer.isView(value)) {
701
+ return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
702
+ }
703
+ if (value instanceof ArrayBuffer) {
704
+ return new Uint8Array(value.slice(0));
705
+ }
706
+ return Uint8Array.from(value);
707
+ }
708
+ function createBluetoothError(name, message) {
709
+ try {
710
+ return new DOMException(message, name);
711
+ }
712
+ catch (_a) {
713
+ const error = new Error(message);
714
+ error.name = name;
715
+ return error;
716
+ }
717
+ }
718
+ function normalizeError(error) {
719
+ if (error instanceof Error) {
720
+ return error;
721
+ }
722
+ return new Error(String(error));
723
+ }
724
+ function installBluetoothLowEnergyShim(plugin, options = {}) {
725
+ var _a, _b, _c;
726
+ const root = ((_a = options.root) !== null && _a !== void 0 ? _a : globalThis);
727
+ const isNativePlatform = (_b = options.isNativePlatform) !== null && _b !== void 0 ? _b : core.Capacitor.isNativePlatform();
728
+ const isPluginAvailable = (_c = options.isPluginAvailable) !== null && _c !== void 0 ? _c : core.Capacitor.isPluginAvailable(PLUGIN_NAME);
729
+ if (!isNativePlatform || !isPluginAvailable || !root.navigator || root.navigator.bluetooth) {
730
+ return;
731
+ }
732
+ const shim = new NativeWebBluetoothShim(root, plugin);
733
+ shim.install();
734
+ }
735
+
4
736
  /**
5
737
  * Utility class for BLE operations.
6
738
  *
@@ -74,8 +806,11 @@ var capacitorBluetoothLowEnergy = (function (exports, core) {
74
806
  }
75
807
 
76
808
  const BluetoothLowEnergy = core.registerPlugin('BluetoothLowEnergy', {
77
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BluetoothLowEnergyWeb()),
809
+ web: () => Promise.resolve().then(function () { return web; }).then((module) => new module.BluetoothLowEnergyWeb()),
78
810
  });
811
+ BluetoothLowEnergy.shimWebBluetooth = () => {
812
+ installBluetoothLowEnergyShim(BluetoothLowEnergy);
813
+ };
79
814
 
80
815
  class BluetoothLowEnergyWeb extends core.WebPlugin {
81
816
  constructor() {
@@ -90,6 +825,9 @@ var capacitorBluetoothLowEnergy = (function (exports, core) {
90
825
  throw new Error('Web Bluetooth API is not available');
91
826
  }
92
827
  }
828
+ shimWebBluetooth() {
829
+ // The browser already provides navigator.bluetooth when available.
830
+ }
93
831
  async isAvailable() {
94
832
  if (!navigator.bluetooth) {
95
833
  return { available: false };