@capacitor-community/bluetooth-le 8.0.0-0 → 8.0.1

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.
Files changed (54) hide show
  1. package/CapacitorCommunityBluetoothLe.podspec +17 -17
  2. package/LICENSE +21 -21
  3. package/Package.swift +27 -27
  4. package/README.md +5 -3
  5. package/android/build.gradle +73 -71
  6. package/android/src/main/AndroidManifest.xml +22 -22
  7. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/BluetoothLe.kt +1094 -1094
  8. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/Conversion.kt +51 -51
  9. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/Device.kt +771 -771
  10. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/DeviceList.kt +28 -28
  11. package/android/src/main/java/com/capacitorjs/community/plugins/bluetoothle/DeviceScanner.kt +189 -189
  12. package/dist/docs.json +43 -43
  13. package/dist/esm/bleClient.d.ts +278 -278
  14. package/dist/esm/bleClient.js +361 -361
  15. package/dist/esm/bleClient.js.map +1 -1
  16. package/dist/esm/config.d.ts +53 -53
  17. package/dist/esm/config.js +2 -2
  18. package/dist/esm/conversion.d.ts +56 -56
  19. package/dist/esm/conversion.js +134 -134
  20. package/dist/esm/conversion.js.map +1 -1
  21. package/dist/esm/definitions.d.ts +352 -352
  22. package/dist/esm/definitions.js +42 -42
  23. package/dist/esm/definitions.js.map +1 -1
  24. package/dist/esm/index.d.ts +5 -5
  25. package/dist/esm/index.js +5 -5
  26. package/dist/esm/plugin.d.ts +2 -2
  27. package/dist/esm/plugin.js +4 -4
  28. package/dist/esm/queue.d.ts +3 -3
  29. package/dist/esm/queue.js +17 -17
  30. package/dist/esm/queue.js.map +1 -1
  31. package/dist/esm/timeout.d.ts +1 -1
  32. package/dist/esm/timeout.js +9 -9
  33. package/dist/esm/validators.d.ts +1 -1
  34. package/dist/esm/validators.js +11 -11
  35. package/dist/esm/validators.js.map +1 -1
  36. package/dist/esm/web.d.ts +57 -57
  37. package/dist/esm/web.js +403 -403
  38. package/dist/esm/web.js.map +1 -1
  39. package/dist/plugin.cjs.js +964 -964
  40. package/dist/plugin.cjs.js.map +1 -1
  41. package/dist/plugin.js +964 -964
  42. package/dist/plugin.js.map +1 -1
  43. package/ios/Sources/BluetoothLe/Conversion.swift +83 -83
  44. package/ios/Sources/BluetoothLe/Device.swift +423 -423
  45. package/ios/Sources/BluetoothLe/DeviceListView.swift +121 -121
  46. package/ios/Sources/BluetoothLe/DeviceManager.swift +415 -503
  47. package/ios/Sources/BluetoothLe/Logging.swift +8 -8
  48. package/ios/Sources/BluetoothLe/Plugin.swift +763 -775
  49. package/ios/Sources/BluetoothLe/ScanFilters.swift +114 -0
  50. package/ios/Sources/BluetoothLe/ThreadSafeDictionary.swift +15 -15
  51. package/ios/Tests/BluetoothLeTests/ConversionTests.swift +55 -55
  52. package/ios/Tests/BluetoothLeTests/PluginTests.swift +27 -27
  53. package/ios/Tests/BluetoothLeTests/ScanFiltersTests.swift +153 -0
  54. package/package.json +114 -115
@@ -2,984 +2,984 @@
2
2
 
3
3
  var core = require('@capacitor/core');
4
4
 
5
- /**
6
- * Android scan mode
7
- */
8
- exports.ScanMode = void 0;
9
- (function (ScanMode) {
10
- /**
11
- * Perform Bluetooth LE scan in low power mode. This mode is enforced if the scanning application is not in foreground.
12
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_POWER
13
- */
14
- ScanMode[ScanMode["SCAN_MODE_LOW_POWER"] = 0] = "SCAN_MODE_LOW_POWER";
15
- /**
16
- * Perform Bluetooth LE scan in balanced power mode. (default) Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption.
17
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_BALANCED
18
- */
19
- ScanMode[ScanMode["SCAN_MODE_BALANCED"] = 1] = "SCAN_MODE_BALANCED";
20
- /**
21
- * Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground.
22
- * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_LATENCY
23
- */
24
- ScanMode[ScanMode["SCAN_MODE_LOW_LATENCY"] = 2] = "SCAN_MODE_LOW_LATENCY";
25
- })(exports.ScanMode || (exports.ScanMode = {}));
26
- /**
27
- * Android connection priority used in `requestConnectionPriority`
28
- */
29
- exports.ConnectionPriority = void 0;
30
- (function (ConnectionPriority) {
31
- /**
32
- * Use the connection parameters recommended by the Bluetooth SIG. This is the default value if no connection parameter update is requested.
33
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_BALANCED
34
- */
35
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_BALANCED"] = 0] = "CONNECTION_PRIORITY_BALANCED";
36
- /**
37
- * Request a high priority, low latency connection. An application should only request high priority connection parameters to transfer large amounts of data over LE quickly. Once the transfer is complete, the application should request CONNECTION_PRIORITY_BALANCED connection parameters to reduce energy use.
38
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_HIGH
39
- */
40
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_HIGH"] = 1] = "CONNECTION_PRIORITY_HIGH";
41
- /**
42
- * Request low power, reduced data rate connection parameters.
43
- * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER
44
- */
45
- ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_LOW_POWER"] = 2] = "CONNECTION_PRIORITY_LOW_POWER";
5
+ /**
6
+ * Android scan mode
7
+ */
8
+ exports.ScanMode = void 0;
9
+ (function (ScanMode) {
10
+ /**
11
+ * Perform Bluetooth LE scan in low power mode. This mode is enforced if the scanning application is not in foreground.
12
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_POWER
13
+ */
14
+ ScanMode[ScanMode["SCAN_MODE_LOW_POWER"] = 0] = "SCAN_MODE_LOW_POWER";
15
+ /**
16
+ * Perform Bluetooth LE scan in balanced power mode. (default) Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption.
17
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_BALANCED
18
+ */
19
+ ScanMode[ScanMode["SCAN_MODE_BALANCED"] = 1] = "SCAN_MODE_BALANCED";
20
+ /**
21
+ * Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground.
22
+ * https://developer.android.com/reference/android/bluetooth/le/ScanSettings#SCAN_MODE_LOW_LATENCY
23
+ */
24
+ ScanMode[ScanMode["SCAN_MODE_LOW_LATENCY"] = 2] = "SCAN_MODE_LOW_LATENCY";
25
+ })(exports.ScanMode || (exports.ScanMode = {}));
26
+ /**
27
+ * Android connection priority used in `requestConnectionPriority`
28
+ */
29
+ exports.ConnectionPriority = void 0;
30
+ (function (ConnectionPriority) {
31
+ /**
32
+ * Use the connection parameters recommended by the Bluetooth SIG. This is the default value if no connection parameter update is requested.
33
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_BALANCED
34
+ */
35
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_BALANCED"] = 0] = "CONNECTION_PRIORITY_BALANCED";
36
+ /**
37
+ * Request a high priority, low latency connection. An application should only request high priority connection parameters to transfer large amounts of data over LE quickly. Once the transfer is complete, the application should request CONNECTION_PRIORITY_BALANCED connection parameters to reduce energy use.
38
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_HIGH
39
+ */
40
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_HIGH"] = 1] = "CONNECTION_PRIORITY_HIGH";
41
+ /**
42
+ * Request low power, reduced data rate connection parameters.
43
+ * https://developer.android.com/reference/android/bluetooth/BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER
44
+ */
45
+ ConnectionPriority[ConnectionPriority["CONNECTION_PRIORITY_LOW_POWER"] = 2] = "CONNECTION_PRIORITY_LOW_POWER";
46
46
  })(exports.ConnectionPriority || (exports.ConnectionPriority = {}));
47
47
 
48
- /**
49
- * Convert an array of numbers into a DataView.
50
- */
51
- function numbersToDataView(value) {
52
- return new DataView(Uint8Array.from(value).buffer);
53
- }
54
- /**
55
- * Convert a DataView into an array of numbers.
56
- */
57
- function dataViewToNumbers(value) {
58
- return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
59
- }
60
- /**
61
- * Convert a string into a DataView.
62
- */
63
- function textToDataView(value) {
64
- return numbersToDataView(value.split('').map((s) => s.charCodeAt(0)));
65
- }
66
- /**
67
- * Convert a DataView into a string.
68
- */
69
- function dataViewToText(value) {
70
- return String.fromCharCode(...dataViewToNumbers(value));
71
- }
72
- /**
73
- * Convert a 16 bit UUID into a 128 bit UUID string
74
- * @param value number, e.g. 0x180d
75
- * @return string, e.g. '0000180d-0000-1000-8000-00805f9b34fb'
76
- */
77
- function numberToUUID(value) {
78
- return `0000${value.toString(16).padStart(4, '0')}-0000-1000-8000-00805f9b34fb`;
79
- }
80
- /**
81
- * Convert a string of hex into a DataView of raw bytes.
82
- * Note: characters other than [0-9a-fA-F] are ignored
83
- * @param hex string of values, e.g. "00 01 02" or "000102"
84
- * @return DataView of raw bytes
85
- */
86
- function hexStringToDataView(hex) {
87
- const bin = [];
88
- let i, c, isEmpty = 1, buffer = 0;
89
- for (i = 0; i < hex.length; i++) {
90
- c = hex.charCodeAt(i);
91
- if ((c > 47 && c < 58) || (c > 64 && c < 71) || (c > 96 && c < 103)) {
92
- buffer = (buffer << 4) ^ ((c > 64 ? c + 9 : c) & 15);
93
- if ((isEmpty ^= 1)) {
94
- bin.push(buffer & 0xff);
95
- }
96
- }
97
- }
98
- return numbersToDataView(bin);
99
- }
100
- function dataViewToHexString(value) {
101
- return dataViewToNumbers(value)
102
- .map((n) => {
103
- let s = n.toString(16);
104
- if (s.length == 1) {
105
- s = '0' + s;
106
- }
107
- return s;
108
- })
109
- .join('');
110
- }
111
- function webUUIDToString(uuid) {
112
- if (typeof uuid === 'string') {
113
- return uuid;
114
- }
115
- else if (typeof uuid === 'number') {
116
- return numberToUUID(uuid);
117
- }
118
- else {
119
- throw new Error('Invalid UUID');
120
- }
121
- }
122
- function mapToObject(map) {
123
- const obj = {};
124
- if (!map) {
125
- return undefined;
126
- }
127
- map.forEach((value, key) => {
128
- obj[key.toString()] = value;
129
- });
130
- return obj;
131
- }
132
- /**
133
- * Convert Data or Uint8Array to Uint8Array.
134
- * @param value DataView, Uint8Array, or undefined
135
- * @return Uint8Array or undefined
136
- */
137
- function toUint8Array(value) {
138
- if (value === undefined) {
139
- return undefined;
140
- }
141
- if (typeof value === 'string') {
142
- const dataView = hexStringToDataView(value);
143
- return new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength);
144
- }
145
- if (value instanceof DataView) {
146
- return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
147
- }
148
- return value; // Already Uint8Array
149
- }
150
- /**
151
- * Convert Data, Uint8Array, or string to hex string.
152
- * @param value DataView, Uint8Array, or undefined
153
- * @return hex string or undefined
154
- */
155
- function toHexString(value) {
156
- if (value === undefined) {
157
- return undefined;
158
- }
159
- if (value instanceof DataView) {
160
- return dataViewToHexString(value);
161
- }
162
- // Uint8Array
163
- return dataViewToHexString(new DataView(value.buffer, value.byteOffset, value.byteLength));
164
- }
165
- /**
166
- * Convert a DataView to a DataView backed by an ArrayBuffer.
167
- * If the DataView is backed by a SharedArrayBuffer, this creates a copy.
168
- * Otherwise, returns the original DataView.
169
- * @param value DataView to convert
170
- * @return DataView backed by ArrayBuffer
171
- */
172
- function toArrayBufferDataView(value) {
173
- if (value.buffer instanceof SharedArrayBuffer) {
174
- // Need to copy to a regular ArrayBuffer
175
- const uint8Array = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
176
- const buffer = uint8Array.slice().buffer;
177
- return new DataView(buffer);
178
- }
179
- // Already an ArrayBuffer, use directly
180
- return value;
48
+ /**
49
+ * Convert an array of numbers into a DataView.
50
+ */
51
+ function numbersToDataView(value) {
52
+ return new DataView(Uint8Array.from(value).buffer);
53
+ }
54
+ /**
55
+ * Convert a DataView into an array of numbers.
56
+ */
57
+ function dataViewToNumbers(value) {
58
+ return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
59
+ }
60
+ /**
61
+ * Convert a string into a DataView.
62
+ */
63
+ function textToDataView(value) {
64
+ return numbersToDataView(value.split('').map((s) => s.charCodeAt(0)));
65
+ }
66
+ /**
67
+ * Convert a DataView into a string.
68
+ */
69
+ function dataViewToText(value) {
70
+ return String.fromCharCode(...dataViewToNumbers(value));
71
+ }
72
+ /**
73
+ * Convert a 16 bit UUID into a 128 bit UUID string
74
+ * @param value number, e.g. 0x180d
75
+ * @return string, e.g. '0000180d-0000-1000-8000-00805f9b34fb'
76
+ */
77
+ function numberToUUID(value) {
78
+ return `0000${value.toString(16).padStart(4, '0')}-0000-1000-8000-00805f9b34fb`;
79
+ }
80
+ /**
81
+ * Convert a string of hex into a DataView of raw bytes.
82
+ * Note: characters other than [0-9a-fA-F] are ignored
83
+ * @param hex string of values, e.g. "00 01 02" or "000102"
84
+ * @return DataView of raw bytes
85
+ */
86
+ function hexStringToDataView(hex) {
87
+ const bin = [];
88
+ let i, c, isEmpty = 1, buffer = 0;
89
+ for (i = 0; i < hex.length; i++) {
90
+ c = hex.charCodeAt(i);
91
+ if ((c > 47 && c < 58) || (c > 64 && c < 71) || (c > 96 && c < 103)) {
92
+ buffer = (buffer << 4) ^ ((c > 64 ? c + 9 : c) & 15);
93
+ if ((isEmpty ^= 1)) {
94
+ bin.push(buffer & 0xff);
95
+ }
96
+ }
97
+ }
98
+ return numbersToDataView(bin);
99
+ }
100
+ function dataViewToHexString(value) {
101
+ return dataViewToNumbers(value)
102
+ .map((n) => {
103
+ let s = n.toString(16);
104
+ if (s.length == 1) {
105
+ s = '0' + s;
106
+ }
107
+ return s;
108
+ })
109
+ .join('');
110
+ }
111
+ function webUUIDToString(uuid) {
112
+ if (typeof uuid === 'string') {
113
+ return uuid;
114
+ }
115
+ else if (typeof uuid === 'number') {
116
+ return numberToUUID(uuid);
117
+ }
118
+ else {
119
+ throw new Error('Invalid UUID');
120
+ }
121
+ }
122
+ function mapToObject(map) {
123
+ const obj = {};
124
+ if (!map) {
125
+ return undefined;
126
+ }
127
+ map.forEach((value, key) => {
128
+ obj[key.toString()] = value;
129
+ });
130
+ return obj;
131
+ }
132
+ /**
133
+ * Convert Data or Uint8Array to Uint8Array.
134
+ * @param value DataView, Uint8Array, or undefined
135
+ * @return Uint8Array or undefined
136
+ */
137
+ function toUint8Array(value) {
138
+ if (value === undefined) {
139
+ return undefined;
140
+ }
141
+ if (typeof value === 'string') {
142
+ const dataView = hexStringToDataView(value);
143
+ return new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength);
144
+ }
145
+ if (value instanceof DataView) {
146
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
147
+ }
148
+ return value; // Already Uint8Array
149
+ }
150
+ /**
151
+ * Convert Data, Uint8Array, or string to hex string.
152
+ * @param value DataView, Uint8Array, or undefined
153
+ * @return hex string or undefined
154
+ */
155
+ function toHexString(value) {
156
+ if (value === undefined) {
157
+ return undefined;
158
+ }
159
+ if (value instanceof DataView) {
160
+ return dataViewToHexString(value);
161
+ }
162
+ // Uint8Array
163
+ return dataViewToHexString(new DataView(value.buffer, value.byteOffset, value.byteLength));
164
+ }
165
+ /**
166
+ * Convert a DataView to a DataView backed by an ArrayBuffer.
167
+ * If the DataView is backed by a SharedArrayBuffer, this creates a copy.
168
+ * Otherwise, returns the original DataView.
169
+ * @param value DataView to convert
170
+ * @return DataView backed by ArrayBuffer
171
+ */
172
+ function toArrayBufferDataView(value) {
173
+ if (value.buffer instanceof SharedArrayBuffer) {
174
+ // Need to copy to a regular ArrayBuffer
175
+ const uint8Array = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
176
+ const buffer = uint8Array.slice().buffer;
177
+ return new DataView(buffer);
178
+ }
179
+ // Already an ArrayBuffer, use directly
180
+ return value;
181
181
  }
182
182
 
183
- const BluetoothLe = core.registerPlugin('BluetoothLe', {
184
- web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BluetoothLeWeb()),
183
+ const BluetoothLe = core.registerPlugin('BluetoothLe', {
184
+ web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.BluetoothLeWeb()),
185
185
  });
186
186
 
187
- const makeQueue = () => {
188
- let currentTask = Promise.resolve();
189
- // create a new promise so that errors can be bubbled
190
- // up to the caller without being caught by the queue
191
- return (fn) => new Promise((resolve, reject) => {
192
- currentTask = currentTask
193
- .then(() => fn())
194
- .then(resolve)
195
- .catch(reject);
196
- });
197
- };
198
- function getQueue(enabled) {
199
- if (enabled) {
200
- return makeQueue();
201
- }
202
- return (fn) => fn();
187
+ const makeQueue = () => {
188
+ let currentTask = Promise.resolve();
189
+ // create a new promise so that errors can be bubbled
190
+ // up to the caller without being caught by the queue
191
+ return (fn) => new Promise((resolve, reject) => {
192
+ currentTask = currentTask
193
+ .then(() => fn())
194
+ .then(resolve)
195
+ .catch(reject);
196
+ });
197
+ };
198
+ function getQueue(enabled) {
199
+ if (enabled) {
200
+ return makeQueue();
201
+ }
202
+ return (fn) => fn();
203
203
  }
204
204
 
205
- function parseUUID(uuid) {
206
- if (typeof uuid !== 'string') {
207
- throw new Error(`Invalid UUID type ${typeof uuid}. Expected string.`);
208
- }
209
- uuid = uuid.toLowerCase();
210
- const is128BitUuid = uuid.search(/^[0-9a-f]{8}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{12}$/) >= 0;
211
- if (!is128BitUuid) {
212
- throw new Error(`Invalid UUID format ${uuid}. Expected 128 bit string (e.g. "0000180d-0000-1000-8000-00805f9b34fb").`);
213
- }
214
- return uuid;
205
+ function parseUUID(uuid) {
206
+ if (typeof uuid !== 'string') {
207
+ throw new Error(`Invalid UUID type ${typeof uuid}. Expected string.`);
208
+ }
209
+ uuid = uuid.toLowerCase();
210
+ const is128BitUuid = uuid.search(/^[0-9a-f]{8}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{4}\b-[0-9a-f]{12}$/) >= 0;
211
+ if (!is128BitUuid) {
212
+ throw new Error(`Invalid UUID format ${uuid}. Expected 128 bit string (e.g. "0000180d-0000-1000-8000-00805f9b34fb").`);
213
+ }
214
+ return uuid;
215
215
  }
216
216
 
217
- class BleClientClass {
218
- constructor() {
219
- this.scanListener = null;
220
- this.eventListeners = new Map();
221
- this.queue = getQueue(true);
222
- }
223
- enableQueue() {
224
- this.queue = getQueue(true);
225
- }
226
- disableQueue() {
227
- this.queue = getQueue(false);
228
- }
229
- async initialize(options) {
230
- await this.queue(async () => {
231
- await BluetoothLe.initialize(options);
232
- });
233
- }
234
- async isEnabled() {
235
- const enabled = await this.queue(async () => {
236
- const result = await BluetoothLe.isEnabled();
237
- return result.value;
238
- });
239
- return enabled;
240
- }
241
- async requestEnable() {
242
- await this.queue(async () => {
243
- await BluetoothLe.requestEnable();
244
- });
245
- }
246
- async enable() {
247
- await this.queue(async () => {
248
- await BluetoothLe.enable();
249
- });
250
- }
251
- async disable() {
252
- await this.queue(async () => {
253
- await BluetoothLe.disable();
254
- });
255
- }
256
- async startEnabledNotifications(callback) {
257
- await this.queue(async () => {
258
- var _a;
259
- const key = `onEnabledChanged`;
260
- await ((_a = this.eventListeners.get(key)) === null || _a === void 0 ? void 0 : _a.remove());
261
- const listener = await BluetoothLe.addListener(key, (result) => {
262
- callback(result.value);
263
- });
264
- this.eventListeners.set(key, listener);
265
- await BluetoothLe.startEnabledNotifications();
266
- });
267
- }
268
- async stopEnabledNotifications() {
269
- await this.queue(async () => {
270
- var _a;
271
- const key = `onEnabledChanged`;
272
- await ((_a = this.eventListeners.get(key)) === null || _a === void 0 ? void 0 : _a.remove());
273
- this.eventListeners.delete(key);
274
- await BluetoothLe.stopEnabledNotifications();
275
- });
276
- }
277
- async isLocationEnabled() {
278
- const enabled = await this.queue(async () => {
279
- const result = await BluetoothLe.isLocationEnabled();
280
- return result.value;
281
- });
282
- return enabled;
283
- }
284
- async openLocationSettings() {
285
- await this.queue(async () => {
286
- await BluetoothLe.openLocationSettings();
287
- });
288
- }
289
- async openBluetoothSettings() {
290
- await this.queue(async () => {
291
- await BluetoothLe.openBluetoothSettings();
292
- });
293
- }
294
- async openAppSettings() {
295
- await this.queue(async () => {
296
- await BluetoothLe.openAppSettings();
297
- });
298
- }
299
- async setDisplayStrings(displayStrings) {
300
- await this.queue(async () => {
301
- await BluetoothLe.setDisplayStrings(displayStrings);
302
- });
303
- }
304
- async requestDevice(options) {
305
- options = options ? this.validateRequestBleDeviceOptions(options) : undefined;
306
- const result = await this.queue(async () => {
307
- const device = await BluetoothLe.requestDevice(options);
308
- return device;
309
- });
310
- return result;
311
- }
312
- async requestLEScan(options, callback) {
313
- options = this.validateRequestBleDeviceOptions(options);
314
- await this.queue(async () => {
315
- var _a;
316
- await ((_a = this.scanListener) === null || _a === void 0 ? void 0 : _a.remove());
317
- this.scanListener = await BluetoothLe.addListener('onScanResult', (resultInternal) => {
318
- const result = Object.assign(Object.assign({}, resultInternal), { manufacturerData: this.convertObject(resultInternal.manufacturerData), serviceData: this.convertObject(resultInternal.serviceData), rawAdvertisement: resultInternal.rawAdvertisement
319
- ? this.convertValue(resultInternal.rawAdvertisement)
320
- : undefined });
321
- callback(result);
322
- });
323
- await BluetoothLe.requestLEScan(options);
324
- });
325
- }
326
- async stopLEScan() {
327
- await this.queue(async () => {
328
- var _a;
329
- await ((_a = this.scanListener) === null || _a === void 0 ? void 0 : _a.remove());
330
- this.scanListener = null;
331
- await BluetoothLe.stopLEScan();
332
- });
333
- }
334
- async getDevices(deviceIds) {
335
- if (!Array.isArray(deviceIds)) {
336
- throw new Error('deviceIds must be an array');
337
- }
338
- return this.queue(async () => {
339
- const result = await BluetoothLe.getDevices({ deviceIds });
340
- return result.devices;
341
- });
342
- }
343
- async getConnectedDevices(services) {
344
- if (!Array.isArray(services)) {
345
- throw new Error('services must be an array');
346
- }
347
- services = services.map(parseUUID);
348
- return this.queue(async () => {
349
- const result = await BluetoothLe.getConnectedDevices({ services });
350
- return result.devices;
351
- });
352
- }
353
- async getBondedDevices() {
354
- return this.queue(async () => {
355
- const result = await BluetoothLe.getBondedDevices();
356
- return result.devices;
357
- });
358
- }
359
- async connect(deviceId, onDisconnect, options) {
360
- await this.queue(async () => {
361
- var _a;
362
- if (onDisconnect) {
363
- const key = `disconnected|${deviceId}`;
364
- await ((_a = this.eventListeners.get(key)) === null || _a === void 0 ? void 0 : _a.remove());
365
- const listener = await BluetoothLe.addListener(key, () => {
366
- onDisconnect(deviceId);
367
- });
368
- this.eventListeners.set(key, listener);
369
- }
370
- await BluetoothLe.connect(Object.assign({ deviceId }, options));
371
- });
372
- }
373
- async createBond(deviceId, options) {
374
- await this.queue(async () => {
375
- await BluetoothLe.createBond(Object.assign({ deviceId }, options));
376
- });
377
- }
378
- async isBonded(deviceId) {
379
- const isBonded = await this.queue(async () => {
380
- const result = await BluetoothLe.isBonded({ deviceId });
381
- return result.value;
382
- });
383
- return isBonded;
384
- }
385
- async disconnect(deviceId) {
386
- await this.queue(async () => {
387
- await BluetoothLe.disconnect({ deviceId });
388
- });
389
- }
390
- async getServices(deviceId) {
391
- const services = await this.queue(async () => {
392
- const result = await BluetoothLe.getServices({ deviceId });
393
- return result.services;
394
- });
395
- return services;
396
- }
397
- async discoverServices(deviceId) {
398
- await this.queue(async () => {
399
- await BluetoothLe.discoverServices({ deviceId });
400
- });
401
- }
402
- async getMtu(deviceId) {
403
- const value = await this.queue(async () => {
404
- const result = await BluetoothLe.getMtu({ deviceId });
405
- return result.value;
406
- });
407
- return value;
408
- }
409
- async requestConnectionPriority(deviceId, connectionPriority) {
410
- await this.queue(async () => {
411
- await BluetoothLe.requestConnectionPriority({ deviceId, connectionPriority });
412
- });
413
- }
414
- async readRssi(deviceId) {
415
- const value = await this.queue(async () => {
416
- const result = await BluetoothLe.readRssi({ deviceId });
417
- return parseFloat(result.value);
418
- });
419
- return value;
420
- }
421
- async read(deviceId, service, characteristic, options) {
422
- service = parseUUID(service);
423
- characteristic = parseUUID(characteristic);
424
- const value = await this.queue(async () => {
425
- const result = await BluetoothLe.read(Object.assign({ deviceId,
426
- service,
427
- characteristic }, options));
428
- return this.convertValue(result.value);
429
- });
430
- return value;
431
- }
432
- async write(deviceId, service, characteristic, value, options) {
433
- service = parseUUID(service);
434
- characteristic = parseUUID(characteristic);
435
- return this.queue(async () => {
436
- if (!(value === null || value === void 0 ? void 0 : value.buffer)) {
437
- throw new Error('Invalid data.');
438
- }
439
- let writeValue = value;
440
- if (core.Capacitor.getPlatform() !== 'web') {
441
- // on native we can only write strings
442
- writeValue = dataViewToHexString(value);
443
- }
444
- await BluetoothLe.write(Object.assign({ deviceId,
445
- service,
446
- characteristic, value: writeValue }, options));
447
- });
448
- }
449
- async writeWithoutResponse(deviceId, service, characteristic, value, options) {
450
- service = parseUUID(service);
451
- characteristic = parseUUID(characteristic);
452
- await this.queue(async () => {
453
- if (!(value === null || value === void 0 ? void 0 : value.buffer)) {
454
- throw new Error('Invalid data.');
455
- }
456
- let writeValue = value;
457
- if (core.Capacitor.getPlatform() !== 'web') {
458
- // on native we can only write strings
459
- writeValue = dataViewToHexString(value);
460
- }
461
- await BluetoothLe.writeWithoutResponse(Object.assign({ deviceId,
462
- service,
463
- characteristic, value: writeValue }, options));
464
- });
465
- }
466
- async readDescriptor(deviceId, service, characteristic, descriptor, options) {
467
- service = parseUUID(service);
468
- characteristic = parseUUID(characteristic);
469
- descriptor = parseUUID(descriptor);
470
- const value = await this.queue(async () => {
471
- const result = await BluetoothLe.readDescriptor(Object.assign({ deviceId,
472
- service,
473
- characteristic,
474
- descriptor }, options));
475
- return this.convertValue(result.value);
476
- });
477
- return value;
478
- }
479
- async writeDescriptor(deviceId, service, characteristic, descriptor, value, options) {
480
- service = parseUUID(service);
481
- characteristic = parseUUID(characteristic);
482
- descriptor = parseUUID(descriptor);
483
- return this.queue(async () => {
484
- if (!(value === null || value === void 0 ? void 0 : value.buffer)) {
485
- throw new Error('Invalid data.');
486
- }
487
- let writeValue = value;
488
- if (core.Capacitor.getPlatform() !== 'web') {
489
- // on native we can only write strings
490
- writeValue = dataViewToHexString(value);
491
- }
492
- await BluetoothLe.writeDescriptor(Object.assign({ deviceId,
493
- service,
494
- characteristic,
495
- descriptor, value: writeValue }, options));
496
- });
497
- }
498
- async startNotifications(deviceId, service, characteristic, callback, options) {
499
- service = parseUUID(service);
500
- characteristic = parseUUID(characteristic);
501
- await this.queue(async () => {
502
- var _a;
503
- const key = `notification|${deviceId}|${service}|${characteristic}`;
504
- await ((_a = this.eventListeners.get(key)) === null || _a === void 0 ? void 0 : _a.remove());
505
- const listener = await BluetoothLe.addListener(key, (event) => {
506
- callback(this.convertValue(event === null || event === void 0 ? void 0 : event.value));
507
- });
508
- this.eventListeners.set(key, listener);
509
- await BluetoothLe.startNotifications(Object.assign({ deviceId,
510
- service,
511
- characteristic }, options));
512
- });
513
- }
514
- async stopNotifications(deviceId, service, characteristic) {
515
- service = parseUUID(service);
516
- characteristic = parseUUID(characteristic);
517
- await this.queue(async () => {
518
- var _a;
519
- const key = `notification|${deviceId}|${service}|${characteristic}`;
520
- await ((_a = this.eventListeners.get(key)) === null || _a === void 0 ? void 0 : _a.remove());
521
- this.eventListeners.delete(key);
522
- await BluetoothLe.stopNotifications({
523
- deviceId,
524
- service,
525
- characteristic,
526
- });
527
- });
528
- }
529
- validateRequestBleDeviceOptions(options) {
530
- if (options.services) {
531
- options.services = options.services.map(parseUUID);
532
- }
533
- if (options.optionalServices) {
534
- options.optionalServices = options.optionalServices.map(parseUUID);
535
- }
536
- if (options.serviceData && core.Capacitor.getPlatform() !== 'web') {
537
- // Native platforms: convert to hex strings
538
- options.serviceData = options.serviceData.map((filter) => (Object.assign(Object.assign({}, filter), { serviceUuid: parseUUID(filter.serviceUuid), dataPrefix: toHexString(filter.dataPrefix), mask: toHexString(filter.mask) })));
539
- }
540
- if (options.manufacturerData) {
541
- if (core.Capacitor.getPlatform() !== 'web') {
542
- // Native platforms: convert to hex strings
543
- options.manufacturerData = options.manufacturerData.map((filter) => (Object.assign(Object.assign({}, filter), { dataPrefix: toHexString(filter.dataPrefix), mask: toHexString(filter.mask) })));
544
- }
545
- else {
546
- // Web platform: convert to Uint8Array for Web Bluetooth API
547
- options.manufacturerData = options.manufacturerData.map((filter) => (Object.assign(Object.assign({}, filter), { dataPrefix: toUint8Array(filter.dataPrefix), mask: toUint8Array(filter.mask) })));
548
- }
549
- }
550
- return options;
551
- }
552
- convertValue(value) {
553
- if (typeof value === 'string') {
554
- return hexStringToDataView(value);
555
- }
556
- else if (value === undefined) {
557
- return new DataView(new ArrayBuffer(0));
558
- }
559
- return value;
560
- }
561
- convertObject(obj) {
562
- if (obj === undefined) {
563
- return undefined;
564
- }
565
- const result = {};
566
- for (const key of Object.keys(obj)) {
567
- result[key] = this.convertValue(obj[key]);
568
- }
569
- return result;
570
- }
571
- }
217
+ class BleClientClass {
218
+ constructor() {
219
+ this.scanListener = null;
220
+ this.eventListeners = new Map();
221
+ this.queue = getQueue(true);
222
+ }
223
+ enableQueue() {
224
+ this.queue = getQueue(true);
225
+ }
226
+ disableQueue() {
227
+ this.queue = getQueue(false);
228
+ }
229
+ async initialize(options) {
230
+ await this.queue(async () => {
231
+ await BluetoothLe.initialize(options);
232
+ });
233
+ }
234
+ async isEnabled() {
235
+ const enabled = await this.queue(async () => {
236
+ const result = await BluetoothLe.isEnabled();
237
+ return result.value;
238
+ });
239
+ return enabled;
240
+ }
241
+ async requestEnable() {
242
+ await this.queue(async () => {
243
+ await BluetoothLe.requestEnable();
244
+ });
245
+ }
246
+ async enable() {
247
+ await this.queue(async () => {
248
+ await BluetoothLe.enable();
249
+ });
250
+ }
251
+ async disable() {
252
+ await this.queue(async () => {
253
+ await BluetoothLe.disable();
254
+ });
255
+ }
256
+ async startEnabledNotifications(callback) {
257
+ await this.queue(async () => {
258
+ var _a;
259
+ const key = `onEnabledChanged`;
260
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
261
+ const listener = await BluetoothLe.addListener(key, (result) => {
262
+ callback(result.value);
263
+ });
264
+ this.eventListeners.set(key, listener);
265
+ await BluetoothLe.startEnabledNotifications();
266
+ });
267
+ }
268
+ async stopEnabledNotifications() {
269
+ await this.queue(async () => {
270
+ var _a;
271
+ const key = `onEnabledChanged`;
272
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
273
+ this.eventListeners.delete(key);
274
+ await BluetoothLe.stopEnabledNotifications();
275
+ });
276
+ }
277
+ async isLocationEnabled() {
278
+ const enabled = await this.queue(async () => {
279
+ const result = await BluetoothLe.isLocationEnabled();
280
+ return result.value;
281
+ });
282
+ return enabled;
283
+ }
284
+ async openLocationSettings() {
285
+ await this.queue(async () => {
286
+ await BluetoothLe.openLocationSettings();
287
+ });
288
+ }
289
+ async openBluetoothSettings() {
290
+ await this.queue(async () => {
291
+ await BluetoothLe.openBluetoothSettings();
292
+ });
293
+ }
294
+ async openAppSettings() {
295
+ await this.queue(async () => {
296
+ await BluetoothLe.openAppSettings();
297
+ });
298
+ }
299
+ async setDisplayStrings(displayStrings) {
300
+ await this.queue(async () => {
301
+ await BluetoothLe.setDisplayStrings(displayStrings);
302
+ });
303
+ }
304
+ async requestDevice(options) {
305
+ options = options ? this.validateRequestBleDeviceOptions(options) : undefined;
306
+ const result = await this.queue(async () => {
307
+ const device = await BluetoothLe.requestDevice(options);
308
+ return device;
309
+ });
310
+ return result;
311
+ }
312
+ async requestLEScan(options, callback) {
313
+ options = this.validateRequestBleDeviceOptions(options);
314
+ await this.queue(async () => {
315
+ var _a;
316
+ await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
317
+ this.scanListener = await BluetoothLe.addListener('onScanResult', (resultInternal) => {
318
+ const result = Object.assign(Object.assign({}, resultInternal), { manufacturerData: this.convertObject(resultInternal.manufacturerData), serviceData: this.convertObject(resultInternal.serviceData), rawAdvertisement: resultInternal.rawAdvertisement
319
+ ? this.convertValue(resultInternal.rawAdvertisement)
320
+ : undefined });
321
+ callback(result);
322
+ });
323
+ await BluetoothLe.requestLEScan(options);
324
+ });
325
+ }
326
+ async stopLEScan() {
327
+ await this.queue(async () => {
328
+ var _a;
329
+ await ((_a = this.scanListener) === null || _a === undefined ? undefined : _a.remove());
330
+ this.scanListener = null;
331
+ await BluetoothLe.stopLEScan();
332
+ });
333
+ }
334
+ async getDevices(deviceIds) {
335
+ if (!Array.isArray(deviceIds)) {
336
+ throw new Error('deviceIds must be an array');
337
+ }
338
+ return this.queue(async () => {
339
+ const result = await BluetoothLe.getDevices({ deviceIds });
340
+ return result.devices;
341
+ });
342
+ }
343
+ async getConnectedDevices(services) {
344
+ if (!Array.isArray(services)) {
345
+ throw new Error('services must be an array');
346
+ }
347
+ services = services.map(parseUUID);
348
+ return this.queue(async () => {
349
+ const result = await BluetoothLe.getConnectedDevices({ services });
350
+ return result.devices;
351
+ });
352
+ }
353
+ async getBondedDevices() {
354
+ return this.queue(async () => {
355
+ const result = await BluetoothLe.getBondedDevices();
356
+ return result.devices;
357
+ });
358
+ }
359
+ async connect(deviceId, onDisconnect, options) {
360
+ await this.queue(async () => {
361
+ var _a;
362
+ if (onDisconnect) {
363
+ const key = `disconnected|${deviceId}`;
364
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
365
+ const listener = await BluetoothLe.addListener(key, () => {
366
+ onDisconnect(deviceId);
367
+ });
368
+ this.eventListeners.set(key, listener);
369
+ }
370
+ await BluetoothLe.connect(Object.assign({ deviceId }, options));
371
+ });
372
+ }
373
+ async createBond(deviceId, options) {
374
+ await this.queue(async () => {
375
+ await BluetoothLe.createBond(Object.assign({ deviceId }, options));
376
+ });
377
+ }
378
+ async isBonded(deviceId) {
379
+ const isBonded = await this.queue(async () => {
380
+ const result = await BluetoothLe.isBonded({ deviceId });
381
+ return result.value;
382
+ });
383
+ return isBonded;
384
+ }
385
+ async disconnect(deviceId) {
386
+ await this.queue(async () => {
387
+ await BluetoothLe.disconnect({ deviceId });
388
+ });
389
+ }
390
+ async getServices(deviceId) {
391
+ const services = await this.queue(async () => {
392
+ const result = await BluetoothLe.getServices({ deviceId });
393
+ return result.services;
394
+ });
395
+ return services;
396
+ }
397
+ async discoverServices(deviceId) {
398
+ await this.queue(async () => {
399
+ await BluetoothLe.discoverServices({ deviceId });
400
+ });
401
+ }
402
+ async getMtu(deviceId) {
403
+ const value = await this.queue(async () => {
404
+ const result = await BluetoothLe.getMtu({ deviceId });
405
+ return result.value;
406
+ });
407
+ return value;
408
+ }
409
+ async requestConnectionPriority(deviceId, connectionPriority) {
410
+ await this.queue(async () => {
411
+ await BluetoothLe.requestConnectionPriority({ deviceId, connectionPriority });
412
+ });
413
+ }
414
+ async readRssi(deviceId) {
415
+ const value = await this.queue(async () => {
416
+ const result = await BluetoothLe.readRssi({ deviceId });
417
+ return parseFloat(result.value);
418
+ });
419
+ return value;
420
+ }
421
+ async read(deviceId, service, characteristic, options) {
422
+ service = parseUUID(service);
423
+ characteristic = parseUUID(characteristic);
424
+ const value = await this.queue(async () => {
425
+ const result = await BluetoothLe.read(Object.assign({ deviceId,
426
+ service,
427
+ characteristic }, options));
428
+ return this.convertValue(result.value);
429
+ });
430
+ return value;
431
+ }
432
+ async write(deviceId, service, characteristic, value, options) {
433
+ service = parseUUID(service);
434
+ characteristic = parseUUID(characteristic);
435
+ return this.queue(async () => {
436
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
437
+ throw new Error('Invalid data.');
438
+ }
439
+ let writeValue = value;
440
+ if (core.Capacitor.getPlatform() !== 'web') {
441
+ // on native we can only write strings
442
+ writeValue = dataViewToHexString(value);
443
+ }
444
+ await BluetoothLe.write(Object.assign({ deviceId,
445
+ service,
446
+ characteristic, value: writeValue }, options));
447
+ });
448
+ }
449
+ async writeWithoutResponse(deviceId, service, characteristic, value, options) {
450
+ service = parseUUID(service);
451
+ characteristic = parseUUID(characteristic);
452
+ await this.queue(async () => {
453
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
454
+ throw new Error('Invalid data.');
455
+ }
456
+ let writeValue = value;
457
+ if (core.Capacitor.getPlatform() !== 'web') {
458
+ // on native we can only write strings
459
+ writeValue = dataViewToHexString(value);
460
+ }
461
+ await BluetoothLe.writeWithoutResponse(Object.assign({ deviceId,
462
+ service,
463
+ characteristic, value: writeValue }, options));
464
+ });
465
+ }
466
+ async readDescriptor(deviceId, service, characteristic, descriptor, options) {
467
+ service = parseUUID(service);
468
+ characteristic = parseUUID(characteristic);
469
+ descriptor = parseUUID(descriptor);
470
+ const value = await this.queue(async () => {
471
+ const result = await BluetoothLe.readDescriptor(Object.assign({ deviceId,
472
+ service,
473
+ characteristic,
474
+ descriptor }, options));
475
+ return this.convertValue(result.value);
476
+ });
477
+ return value;
478
+ }
479
+ async writeDescriptor(deviceId, service, characteristic, descriptor, value, options) {
480
+ service = parseUUID(service);
481
+ characteristic = parseUUID(characteristic);
482
+ descriptor = parseUUID(descriptor);
483
+ return this.queue(async () => {
484
+ if (!(value === null || value === undefined ? undefined : value.buffer)) {
485
+ throw new Error('Invalid data.');
486
+ }
487
+ let writeValue = value;
488
+ if (core.Capacitor.getPlatform() !== 'web') {
489
+ // on native we can only write strings
490
+ writeValue = dataViewToHexString(value);
491
+ }
492
+ await BluetoothLe.writeDescriptor(Object.assign({ deviceId,
493
+ service,
494
+ characteristic,
495
+ descriptor, value: writeValue }, options));
496
+ });
497
+ }
498
+ async startNotifications(deviceId, service, characteristic, callback, options) {
499
+ service = parseUUID(service);
500
+ characteristic = parseUUID(characteristic);
501
+ await this.queue(async () => {
502
+ var _a;
503
+ const key = `notification|${deviceId}|${service}|${characteristic}`;
504
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
505
+ const listener = await BluetoothLe.addListener(key, (event) => {
506
+ callback(this.convertValue(event === null || event === undefined ? undefined : event.value));
507
+ });
508
+ this.eventListeners.set(key, listener);
509
+ await BluetoothLe.startNotifications(Object.assign({ deviceId,
510
+ service,
511
+ characteristic }, options));
512
+ });
513
+ }
514
+ async stopNotifications(deviceId, service, characteristic) {
515
+ service = parseUUID(service);
516
+ characteristic = parseUUID(characteristic);
517
+ await this.queue(async () => {
518
+ var _a;
519
+ const key = `notification|${deviceId}|${service}|${characteristic}`;
520
+ await ((_a = this.eventListeners.get(key)) === null || _a === undefined ? undefined : _a.remove());
521
+ this.eventListeners.delete(key);
522
+ await BluetoothLe.stopNotifications({
523
+ deviceId,
524
+ service,
525
+ characteristic,
526
+ });
527
+ });
528
+ }
529
+ validateRequestBleDeviceOptions(options) {
530
+ if (options.services) {
531
+ options.services = options.services.map(parseUUID);
532
+ }
533
+ if (options.optionalServices) {
534
+ options.optionalServices = options.optionalServices.map(parseUUID);
535
+ }
536
+ if (options.serviceData && core.Capacitor.getPlatform() !== 'web') {
537
+ // Native platforms: convert to hex strings
538
+ options.serviceData = options.serviceData.map((filter) => (Object.assign(Object.assign({}, filter), { serviceUuid: parseUUID(filter.serviceUuid), dataPrefix: toHexString(filter.dataPrefix), mask: toHexString(filter.mask) })));
539
+ }
540
+ if (options.manufacturerData) {
541
+ if (core.Capacitor.getPlatform() !== 'web') {
542
+ // Native platforms: convert to hex strings
543
+ options.manufacturerData = options.manufacturerData.map((filter) => (Object.assign(Object.assign({}, filter), { dataPrefix: toHexString(filter.dataPrefix), mask: toHexString(filter.mask) })));
544
+ }
545
+ else {
546
+ // Web platform: convert to Uint8Array for Web Bluetooth API
547
+ options.manufacturerData = options.manufacturerData.map((filter) => (Object.assign(Object.assign({}, filter), { dataPrefix: toUint8Array(filter.dataPrefix), mask: toUint8Array(filter.mask) })));
548
+ }
549
+ }
550
+ return options;
551
+ }
552
+ convertValue(value) {
553
+ if (typeof value === 'string') {
554
+ return hexStringToDataView(value);
555
+ }
556
+ else if (value === undefined) {
557
+ return new DataView(new ArrayBuffer(0));
558
+ }
559
+ return value;
560
+ }
561
+ convertObject(obj) {
562
+ if (obj === undefined) {
563
+ return undefined;
564
+ }
565
+ const result = {};
566
+ for (const key of Object.keys(obj)) {
567
+ result[key] = this.convertValue(obj[key]);
568
+ }
569
+ return result;
570
+ }
571
+ }
572
572
  const BleClient = new BleClientClass();
573
573
 
574
- async function runWithTimeout(promise, time, exception) {
575
- let timer;
576
- return Promise.race([
577
- promise,
578
- new Promise((_, reject) => {
579
- timer = setTimeout(() => reject(exception), time);
580
- }),
581
- ]).finally(() => clearTimeout(timer));
574
+ async function runWithTimeout(promise, time, exception) {
575
+ let timer;
576
+ return Promise.race([
577
+ promise,
578
+ new Promise((_, reject) => {
579
+ timer = setTimeout(() => reject(exception), time);
580
+ }),
581
+ ]).finally(() => clearTimeout(timer));
582
582
  }
583
583
 
584
- class BluetoothLeWeb extends core.WebPlugin {
585
- constructor() {
586
- super(...arguments);
587
- this.deviceMap = new Map();
588
- this.discoveredDevices = new Map();
589
- this.scan = null;
590
- this.DEFAULT_CONNECTION_TIMEOUT = 10000;
591
- this.onAdvertisementReceivedCallback = this.onAdvertisementReceived.bind(this);
592
- this.onDisconnectedCallback = this.onDisconnected.bind(this);
593
- this.onCharacteristicValueChangedCallback = this.onCharacteristicValueChanged.bind(this);
594
- }
595
- async initialize() {
596
- if (typeof navigator === 'undefined' || !navigator.bluetooth) {
597
- throw this.unavailable('Web Bluetooth API not available in this browser.');
598
- }
599
- const isAvailable = await navigator.bluetooth.getAvailability();
600
- if (!isAvailable) {
601
- throw this.unavailable('No Bluetooth radio available.');
602
- }
603
- }
604
- async isEnabled() {
605
- // not available on web
606
- return { value: true };
607
- }
608
- async requestEnable() {
609
- throw this.unavailable('requestEnable is not available on web.');
610
- }
611
- async enable() {
612
- throw this.unavailable('enable is not available on web.');
613
- }
614
- async disable() {
615
- throw this.unavailable('disable is not available on web.');
616
- }
617
- async startEnabledNotifications() {
618
- // not available on web
619
- }
620
- async stopEnabledNotifications() {
621
- // not available on web
622
- }
623
- async isLocationEnabled() {
624
- throw this.unavailable('isLocationEnabled is not available on web.');
625
- }
626
- async openLocationSettings() {
627
- throw this.unavailable('openLocationSettings is not available on web.');
628
- }
629
- async openBluetoothSettings() {
630
- throw this.unavailable('openBluetoothSettings is not available on web.');
631
- }
632
- async openAppSettings() {
633
- throw this.unavailable('openAppSettings is not available on web.');
634
- }
635
- async setDisplayStrings() {
636
- // not available on web
637
- }
638
- async requestDevice(options) {
639
- const filters = this.getFilters(options);
640
- const device = await navigator.bluetooth.requestDevice({
641
- filters: filters.length ? filters : undefined,
642
- optionalServices: options === null || options === void 0 ? void 0 : options.optionalServices,
643
- acceptAllDevices: filters.length === 0,
644
- });
645
- this.deviceMap.set(device.id, device);
646
- const bleDevice = this.getBleDevice(device);
647
- return bleDevice;
648
- }
649
- async requestLEScan(options) {
650
- this.requestBleDeviceOptions = options;
651
- const filters = this.getFilters(options);
652
- await this.stopLEScan();
653
- this.discoveredDevices = new Map();
654
- navigator.bluetooth.removeEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
655
- navigator.bluetooth.addEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
656
- this.scan = await navigator.bluetooth.requestLEScan({
657
- filters: filters.length ? filters : undefined,
658
- acceptAllAdvertisements: filters.length === 0,
659
- keepRepeatedDevices: options === null || options === void 0 ? void 0 : options.allowDuplicates,
660
- });
661
- }
662
- onAdvertisementReceived(event) {
663
- var _a, _b, _c;
664
- const deviceId = event.device.id;
665
- this.deviceMap.set(deviceId, event.device);
666
- const isNew = !this.discoveredDevices.has(deviceId);
667
- // Apply service data filtering client-side (Web Bluetooth API doesn't support it in scan filters)
668
- if (((_a = this.requestBleDeviceOptions) === null || _a === void 0 ? void 0 : _a.serviceData) && !this.matchesServiceDataFilter(event)) {
669
- return;
670
- }
671
- if (isNew || ((_b = this.requestBleDeviceOptions) === null || _b === void 0 ? void 0 : _b.allowDuplicates)) {
672
- this.discoveredDevices.set(deviceId, true);
673
- const device = this.getBleDevice(event.device);
674
- const result = {
675
- device,
676
- localName: device.name,
677
- rssi: event.rssi,
678
- txPower: event.txPower,
679
- manufacturerData: mapToObject(event.manufacturerData),
680
- serviceData: mapToObject(event.serviceData),
681
- uuids: (_c = event.uuids) === null || _c === void 0 ? void 0 : _c.map(webUUIDToString),
682
- };
683
- this.notifyListeners('onScanResult', result);
684
- }
685
- }
686
- async stopLEScan() {
687
- var _a;
688
- if ((_a = this.scan) === null || _a === void 0 ? void 0 : _a.active) {
689
- this.scan.stop();
690
- }
691
- this.scan = null;
692
- }
693
- async getDevices(options) {
694
- const devices = await navigator.bluetooth.getDevices();
695
- const bleDevices = devices
696
- .filter((device) => options.deviceIds.includes(device.id))
697
- .map((device) => {
698
- this.deviceMap.set(device.id, device);
699
- const bleDevice = this.getBleDevice(device);
700
- return bleDevice;
701
- });
702
- return { devices: bleDevices };
703
- }
704
- async getConnectedDevices(_options) {
705
- const devices = await navigator.bluetooth.getDevices();
706
- const bleDevices = devices
707
- .filter((device) => {
708
- var _a;
709
- return (_a = device.gatt) === null || _a === void 0 ? void 0 : _a.connected;
710
- })
711
- .map((device) => {
712
- this.deviceMap.set(device.id, device);
713
- const bleDevice = this.getBleDevice(device);
714
- return bleDevice;
715
- });
716
- return { devices: bleDevices };
717
- }
718
- async getBondedDevices() {
719
- return {};
720
- }
721
- async connect(options) {
722
- var _a, _b;
723
- const device = this.getDeviceFromMap(options.deviceId);
724
- device.removeEventListener('gattserverdisconnected', this.onDisconnectedCallback);
725
- device.addEventListener('gattserverdisconnected', this.onDisconnectedCallback);
726
- const timeoutError = Symbol();
727
- if (device.gatt === undefined) {
728
- throw new Error('No gatt server available.');
729
- }
730
- try {
731
- const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.DEFAULT_CONNECTION_TIMEOUT;
732
- await runWithTimeout(device.gatt.connect(), timeout, timeoutError);
733
- }
734
- catch (error) {
735
- // cancel pending connect call, does not work yet in chromium because of a bug:
736
- // https://bugs.chromium.org/p/chromium/issues/detail?id=684073
737
- await ((_b = device.gatt) === null || _b === void 0 ? void 0 : _b.disconnect());
738
- if (error === timeoutError) {
739
- throw new Error('Connection timeout');
740
- }
741
- else {
742
- throw error;
743
- }
744
- }
745
- }
746
- onDisconnected(event) {
747
- const deviceId = event.target.id;
748
- const key = `disconnected|${deviceId}`;
749
- this.notifyListeners(key, null);
750
- }
751
- async createBond(_options) {
752
- throw this.unavailable('createBond is not available on web.');
753
- }
754
- async isBonded(_options) {
755
- throw this.unavailable('isBonded is not available on web.');
756
- }
757
- async disconnect(options) {
758
- var _a;
759
- (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.disconnect();
760
- }
761
- async getServices(options) {
762
- var _a, _b;
763
- const services = (_b = (await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.getPrimaryServices()))) !== null && _b !== void 0 ? _b : [];
764
- const bleServices = [];
765
- for (const service of services) {
766
- const characteristics = await service.getCharacteristics();
767
- const bleCharacteristics = [];
768
- for (const characteristic of characteristics) {
769
- bleCharacteristics.push({
770
- uuid: characteristic.uuid,
771
- properties: this.getProperties(characteristic),
772
- descriptors: await this.getDescriptors(characteristic),
773
- });
774
- }
775
- bleServices.push({ uuid: service.uuid, characteristics: bleCharacteristics });
776
- }
777
- return { services: bleServices };
778
- }
779
- async getDescriptors(characteristic) {
780
- try {
781
- const descriptors = await characteristic.getDescriptors();
782
- return descriptors.map((descriptor) => ({
783
- uuid: descriptor.uuid,
784
- }));
785
- }
786
- catch (_a) {
787
- return [];
788
- }
789
- }
790
- getProperties(characteristic) {
791
- return {
792
- broadcast: characteristic.properties.broadcast,
793
- read: characteristic.properties.read,
794
- writeWithoutResponse: characteristic.properties.writeWithoutResponse,
795
- write: characteristic.properties.write,
796
- notify: characteristic.properties.notify,
797
- indicate: characteristic.properties.indicate,
798
- authenticatedSignedWrites: characteristic.properties.authenticatedSignedWrites,
799
- reliableWrite: characteristic.properties.reliableWrite,
800
- writableAuxiliaries: characteristic.properties.writableAuxiliaries,
801
- };
802
- }
803
- async getCharacteristic(options) {
804
- var _a;
805
- const service = await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === void 0 ? void 0 : _a.getPrimaryService(options === null || options === void 0 ? void 0 : options.service));
806
- return service === null || service === void 0 ? void 0 : service.getCharacteristic(options === null || options === void 0 ? void 0 : options.characteristic);
807
- }
808
- async getDescriptor(options) {
809
- const characteristic = await this.getCharacteristic(options);
810
- return characteristic === null || characteristic === void 0 ? void 0 : characteristic.getDescriptor(options === null || options === void 0 ? void 0 : options.descriptor);
811
- }
812
- async discoverServices(_options) {
813
- throw this.unavailable('discoverServices is not available on web.');
814
- }
815
- async getMtu(_options) {
816
- throw this.unavailable('getMtu is not available on web.');
817
- }
818
- async requestConnectionPriority(_options) {
819
- throw this.unavailable('requestConnectionPriority is not available on web.');
820
- }
821
- async readRssi(_options) {
822
- throw this.unavailable('readRssi is not available on web.');
823
- }
824
- async read(options) {
825
- const characteristic = await this.getCharacteristic(options);
826
- const value = await (characteristic === null || characteristic === void 0 ? void 0 : characteristic.readValue());
827
- return { value };
828
- }
829
- async write(options) {
830
- const characteristic = await this.getCharacteristic(options);
831
- let dataView;
832
- if (typeof options.value === 'string') {
833
- dataView = hexStringToDataView(options.value);
834
- }
835
- else {
836
- dataView = options.value;
837
- }
838
- await (characteristic === null || characteristic === void 0 ? void 0 : characteristic.writeValueWithResponse(toArrayBufferDataView(dataView)));
839
- }
840
- async writeWithoutResponse(options) {
841
- const characteristic = await this.getCharacteristic(options);
842
- let dataView;
843
- if (typeof options.value === 'string') {
844
- dataView = hexStringToDataView(options.value);
845
- }
846
- else {
847
- dataView = options.value;
848
- }
849
- await (characteristic === null || characteristic === void 0 ? void 0 : characteristic.writeValueWithoutResponse(toArrayBufferDataView(dataView)));
850
- }
851
- async readDescriptor(options) {
852
- const descriptor = await this.getDescriptor(options);
853
- const value = await (descriptor === null || descriptor === void 0 ? void 0 : descriptor.readValue());
854
- return { value };
855
- }
856
- async writeDescriptor(options) {
857
- const descriptor = await this.getDescriptor(options);
858
- let dataView;
859
- if (typeof options.value === 'string') {
860
- dataView = hexStringToDataView(options.value);
861
- }
862
- else {
863
- dataView = options.value;
864
- }
865
- await (descriptor === null || descriptor === void 0 ? void 0 : descriptor.writeValue(toArrayBufferDataView(dataView)));
866
- }
867
- async startNotifications(options) {
868
- const characteristic = await this.getCharacteristic(options);
869
- characteristic === null || characteristic === void 0 ? void 0 : characteristic.removeEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
870
- characteristic === null || characteristic === void 0 ? void 0 : characteristic.addEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
871
- await (characteristic === null || characteristic === void 0 ? void 0 : characteristic.startNotifications());
872
- }
873
- onCharacteristicValueChanged(event) {
874
- var _a, _b;
875
- const characteristic = event.target;
876
- const key = `notification|${(_a = characteristic.service) === null || _a === void 0 ? void 0 : _a.device.id}|${(_b = characteristic.service) === null || _b === void 0 ? void 0 : _b.uuid}|${characteristic.uuid}`;
877
- this.notifyListeners(key, {
878
- value: characteristic.value,
879
- });
880
- }
881
- async stopNotifications(options) {
882
- const characteristic = await this.getCharacteristic(options);
883
- await (characteristic === null || characteristic === void 0 ? void 0 : characteristic.stopNotifications());
884
- }
885
- getFilters(options) {
886
- var _a, _b;
887
- const filters = [];
888
- for (const service of (_a = options === null || options === void 0 ? void 0 : options.services) !== null && _a !== void 0 ? _a : []) {
889
- filters.push({
890
- services: [service],
891
- name: options === null || options === void 0 ? void 0 : options.name,
892
- namePrefix: options === null || options === void 0 ? void 0 : options.namePrefix,
893
- });
894
- }
895
- if (((options === null || options === void 0 ? void 0 : options.name) || (options === null || options === void 0 ? void 0 : options.namePrefix)) && filters.length === 0) {
896
- filters.push({
897
- name: options.name,
898
- namePrefix: options.namePrefix,
899
- });
900
- }
901
- for (const manufacturerData of (_b = options === null || options === void 0 ? void 0 : options.manufacturerData) !== null && _b !== void 0 ? _b : []) {
902
- // Cast to any to avoid type incompatibility - conversion is handled in bleClient.ts
903
- filters.push({
904
- manufacturerData: [manufacturerData],
905
- });
906
- }
907
- // Note: Web Bluetooth API does not support service data in scan filters.
908
- // Service data filtering will be done client-side in onAdvertisementReceived.
909
- // We still accept serviceData in options for API consistency across platforms.
910
- return filters;
911
- }
912
- matchesServiceDataFilter(event) {
913
- var _a;
914
- const filters = (_a = this.requestBleDeviceOptions) === null || _a === void 0 ? void 0 : _a.serviceData;
915
- if (!filters || filters.length === 0) {
916
- return true; // No filters, accept all
917
- }
918
- if (!event.serviceData) {
919
- return false; // No service data in advertisement
920
- }
921
- // Check if any filter matches (OR logic)
922
- for (const filter of filters) {
923
- const serviceData = event.serviceData.get(filter.serviceUuid);
924
- if (!serviceData) {
925
- continue; // This filter doesn't match, try next
926
- }
927
- // If we have service data for this UUID
928
- if (!filter.dataPrefix) {
929
- return true; // Filter matched by service UUID alone
930
- }
931
- // Check data prefix (DataView on web)
932
- const data = new Uint8Array(serviceData.buffer);
933
- const prefixView = filter.dataPrefix;
934
- if (data.length < prefixView.byteLength) {
935
- continue; // Data too short
936
- }
937
- // Apply mask if provided
938
- if (filter.mask) {
939
- const maskView = filter.mask;
940
- let matches = true;
941
- for (let i = 0; i < prefixView.byteLength; i++) {
942
- if ((data[i] & maskView.getUint8(i)) !== (prefixView.getUint8(i) & maskView.getUint8(i))) {
943
- matches = false;
944
- break;
945
- }
946
- }
947
- if (matches) {
948
- return true;
949
- }
950
- }
951
- else {
952
- // Check if data starts with prefix
953
- let matches = true;
954
- for (let i = 0; i < prefixView.byteLength; i++) {
955
- if (data[i] !== prefixView.getUint8(i)) {
956
- matches = false;
957
- break;
958
- }
959
- }
960
- if (matches) {
961
- return true;
962
- }
963
- }
964
- }
965
- return false; // No filter matched
966
- }
967
- getDeviceFromMap(deviceId) {
968
- const device = this.deviceMap.get(deviceId);
969
- if (device === undefined) {
970
- throw new Error('Device not found. Call "requestDevice", "requestLEScan" or "getDevices" first.');
971
- }
972
- return device;
973
- }
974
- getBleDevice(device) {
975
- var _a;
976
- const bleDevice = {
977
- deviceId: device.id,
978
- // use undefined instead of null if name is not available
979
- name: (_a = device.name) !== null && _a !== void 0 ? _a : undefined,
980
- };
981
- return bleDevice;
982
- }
584
+ class BluetoothLeWeb extends core.WebPlugin {
585
+ constructor() {
586
+ super(...arguments);
587
+ this.deviceMap = new Map();
588
+ this.discoveredDevices = new Map();
589
+ this.scan = null;
590
+ this.DEFAULT_CONNECTION_TIMEOUT = 10000;
591
+ this.onAdvertisementReceivedCallback = this.onAdvertisementReceived.bind(this);
592
+ this.onDisconnectedCallback = this.onDisconnected.bind(this);
593
+ this.onCharacteristicValueChangedCallback = this.onCharacteristicValueChanged.bind(this);
594
+ }
595
+ async initialize() {
596
+ if (typeof navigator === 'undefined' || !navigator.bluetooth) {
597
+ throw this.unavailable('Web Bluetooth API not available in this browser.');
598
+ }
599
+ const isAvailable = await navigator.bluetooth.getAvailability();
600
+ if (!isAvailable) {
601
+ throw this.unavailable('No Bluetooth radio available.');
602
+ }
603
+ }
604
+ async isEnabled() {
605
+ // not available on web
606
+ return { value: true };
607
+ }
608
+ async requestEnable() {
609
+ throw this.unavailable('requestEnable is not available on web.');
610
+ }
611
+ async enable() {
612
+ throw this.unavailable('enable is not available on web.');
613
+ }
614
+ async disable() {
615
+ throw this.unavailable('disable is not available on web.');
616
+ }
617
+ async startEnabledNotifications() {
618
+ // not available on web
619
+ }
620
+ async stopEnabledNotifications() {
621
+ // not available on web
622
+ }
623
+ async isLocationEnabled() {
624
+ throw this.unavailable('isLocationEnabled is not available on web.');
625
+ }
626
+ async openLocationSettings() {
627
+ throw this.unavailable('openLocationSettings is not available on web.');
628
+ }
629
+ async openBluetoothSettings() {
630
+ throw this.unavailable('openBluetoothSettings is not available on web.');
631
+ }
632
+ async openAppSettings() {
633
+ throw this.unavailable('openAppSettings is not available on web.');
634
+ }
635
+ async setDisplayStrings() {
636
+ // not available on web
637
+ }
638
+ async requestDevice(options) {
639
+ const filters = this.getFilters(options);
640
+ const device = await navigator.bluetooth.requestDevice({
641
+ filters: filters.length ? filters : undefined,
642
+ optionalServices: options === null || options === undefined ? undefined : options.optionalServices,
643
+ acceptAllDevices: filters.length === 0,
644
+ });
645
+ this.deviceMap.set(device.id, device);
646
+ const bleDevice = this.getBleDevice(device);
647
+ return bleDevice;
648
+ }
649
+ async requestLEScan(options) {
650
+ this.requestBleDeviceOptions = options;
651
+ const filters = this.getFilters(options);
652
+ await this.stopLEScan();
653
+ this.discoveredDevices = new Map();
654
+ navigator.bluetooth.removeEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
655
+ navigator.bluetooth.addEventListener('advertisementreceived', this.onAdvertisementReceivedCallback);
656
+ this.scan = await navigator.bluetooth.requestLEScan({
657
+ filters: filters.length ? filters : undefined,
658
+ acceptAllAdvertisements: filters.length === 0,
659
+ keepRepeatedDevices: options === null || options === undefined ? undefined : options.allowDuplicates,
660
+ });
661
+ }
662
+ onAdvertisementReceived(event) {
663
+ var _a, _b, _c;
664
+ const deviceId = event.device.id;
665
+ this.deviceMap.set(deviceId, event.device);
666
+ const isNew = !this.discoveredDevices.has(deviceId);
667
+ // Apply service data filtering client-side (Web Bluetooth API doesn't support it in scan filters)
668
+ if (((_a = this.requestBleDeviceOptions) === null || _a === undefined ? undefined : _a.serviceData) && !this.matchesServiceDataFilter(event)) {
669
+ return;
670
+ }
671
+ if (isNew || ((_b = this.requestBleDeviceOptions) === null || _b === undefined ? undefined : _b.allowDuplicates)) {
672
+ this.discoveredDevices.set(deviceId, true);
673
+ const device = this.getBleDevice(event.device);
674
+ const result = {
675
+ device,
676
+ localName: device.name,
677
+ rssi: event.rssi,
678
+ txPower: event.txPower,
679
+ manufacturerData: mapToObject(event.manufacturerData),
680
+ serviceData: mapToObject(event.serviceData),
681
+ uuids: (_c = event.uuids) === null || _c === undefined ? undefined : _c.map(webUUIDToString),
682
+ };
683
+ this.notifyListeners('onScanResult', result);
684
+ }
685
+ }
686
+ async stopLEScan() {
687
+ var _a;
688
+ if ((_a = this.scan) === null || _a === undefined ? undefined : _a.active) {
689
+ this.scan.stop();
690
+ }
691
+ this.scan = null;
692
+ }
693
+ async getDevices(options) {
694
+ const devices = await navigator.bluetooth.getDevices();
695
+ const bleDevices = devices
696
+ .filter((device) => options.deviceIds.includes(device.id))
697
+ .map((device) => {
698
+ this.deviceMap.set(device.id, device);
699
+ const bleDevice = this.getBleDevice(device);
700
+ return bleDevice;
701
+ });
702
+ return { devices: bleDevices };
703
+ }
704
+ async getConnectedDevices(_options) {
705
+ const devices = await navigator.bluetooth.getDevices();
706
+ const bleDevices = devices
707
+ .filter((device) => {
708
+ var _a;
709
+ return (_a = device.gatt) === null || _a === undefined ? undefined : _a.connected;
710
+ })
711
+ .map((device) => {
712
+ this.deviceMap.set(device.id, device);
713
+ const bleDevice = this.getBleDevice(device);
714
+ return bleDevice;
715
+ });
716
+ return { devices: bleDevices };
717
+ }
718
+ async getBondedDevices() {
719
+ return {};
720
+ }
721
+ async connect(options) {
722
+ var _a, _b;
723
+ const device = this.getDeviceFromMap(options.deviceId);
724
+ device.removeEventListener('gattserverdisconnected', this.onDisconnectedCallback);
725
+ device.addEventListener('gattserverdisconnected', this.onDisconnectedCallback);
726
+ const timeoutError = Symbol();
727
+ if (device.gatt === undefined) {
728
+ throw new Error('No gatt server available.');
729
+ }
730
+ try {
731
+ const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.DEFAULT_CONNECTION_TIMEOUT;
732
+ await runWithTimeout(device.gatt.connect(), timeout, timeoutError);
733
+ }
734
+ catch (error) {
735
+ // cancel pending connect call, does not work yet in chromium because of a bug:
736
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=684073
737
+ await ((_b = device.gatt) === null || _b === undefined ? undefined : _b.disconnect());
738
+ if (error === timeoutError) {
739
+ throw new Error('Connection timeout');
740
+ }
741
+ else {
742
+ throw error;
743
+ }
744
+ }
745
+ }
746
+ onDisconnected(event) {
747
+ const deviceId = event.target.id;
748
+ const key = `disconnected|${deviceId}`;
749
+ this.notifyListeners(key, null);
750
+ }
751
+ async createBond(_options) {
752
+ throw this.unavailable('createBond is not available on web.');
753
+ }
754
+ async isBonded(_options) {
755
+ throw this.unavailable('isBonded is not available on web.');
756
+ }
757
+ async disconnect(options) {
758
+ var _a;
759
+ (_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.disconnect();
760
+ }
761
+ async getServices(options) {
762
+ var _a, _b;
763
+ const services = (_b = (await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryServices()))) !== null && _b !== undefined ? _b : [];
764
+ const bleServices = [];
765
+ for (const service of services) {
766
+ const characteristics = await service.getCharacteristics();
767
+ const bleCharacteristics = [];
768
+ for (const characteristic of characteristics) {
769
+ bleCharacteristics.push({
770
+ uuid: characteristic.uuid,
771
+ properties: this.getProperties(characteristic),
772
+ descriptors: await this.getDescriptors(characteristic),
773
+ });
774
+ }
775
+ bleServices.push({ uuid: service.uuid, characteristics: bleCharacteristics });
776
+ }
777
+ return { services: bleServices };
778
+ }
779
+ async getDescriptors(characteristic) {
780
+ try {
781
+ const descriptors = await characteristic.getDescriptors();
782
+ return descriptors.map((descriptor) => ({
783
+ uuid: descriptor.uuid,
784
+ }));
785
+ }
786
+ catch (_a) {
787
+ return [];
788
+ }
789
+ }
790
+ getProperties(characteristic) {
791
+ return {
792
+ broadcast: characteristic.properties.broadcast,
793
+ read: characteristic.properties.read,
794
+ writeWithoutResponse: characteristic.properties.writeWithoutResponse,
795
+ write: characteristic.properties.write,
796
+ notify: characteristic.properties.notify,
797
+ indicate: characteristic.properties.indicate,
798
+ authenticatedSignedWrites: characteristic.properties.authenticatedSignedWrites,
799
+ reliableWrite: characteristic.properties.reliableWrite,
800
+ writableAuxiliaries: characteristic.properties.writableAuxiliaries,
801
+ };
802
+ }
803
+ async getCharacteristic(options) {
804
+ var _a;
805
+ const service = await ((_a = this.getDeviceFromMap(options.deviceId).gatt) === null || _a === undefined ? undefined : _a.getPrimaryService(options === null || options === undefined ? undefined : options.service));
806
+ return service === null || service === undefined ? undefined : service.getCharacteristic(options === null || options === undefined ? undefined : options.characteristic);
807
+ }
808
+ async getDescriptor(options) {
809
+ const characteristic = await this.getCharacteristic(options);
810
+ return characteristic === null || characteristic === undefined ? undefined : characteristic.getDescriptor(options === null || options === undefined ? undefined : options.descriptor);
811
+ }
812
+ async discoverServices(_options) {
813
+ throw this.unavailable('discoverServices is not available on web.');
814
+ }
815
+ async getMtu(_options) {
816
+ throw this.unavailable('getMtu is not available on web.');
817
+ }
818
+ async requestConnectionPriority(_options) {
819
+ throw this.unavailable('requestConnectionPriority is not available on web.');
820
+ }
821
+ async readRssi(_options) {
822
+ throw this.unavailable('readRssi is not available on web.');
823
+ }
824
+ async read(options) {
825
+ const characteristic = await this.getCharacteristic(options);
826
+ const value = await (characteristic === null || characteristic === undefined ? undefined : characteristic.readValue());
827
+ return { value };
828
+ }
829
+ async write(options) {
830
+ const characteristic = await this.getCharacteristic(options);
831
+ let dataView;
832
+ if (typeof options.value === 'string') {
833
+ dataView = hexStringToDataView(options.value);
834
+ }
835
+ else {
836
+ dataView = options.value;
837
+ }
838
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithResponse(toArrayBufferDataView(dataView)));
839
+ }
840
+ async writeWithoutResponse(options) {
841
+ const characteristic = await this.getCharacteristic(options);
842
+ let dataView;
843
+ if (typeof options.value === 'string') {
844
+ dataView = hexStringToDataView(options.value);
845
+ }
846
+ else {
847
+ dataView = options.value;
848
+ }
849
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.writeValueWithoutResponse(toArrayBufferDataView(dataView)));
850
+ }
851
+ async readDescriptor(options) {
852
+ const descriptor = await this.getDescriptor(options);
853
+ const value = await (descriptor === null || descriptor === undefined ? undefined : descriptor.readValue());
854
+ return { value };
855
+ }
856
+ async writeDescriptor(options) {
857
+ const descriptor = await this.getDescriptor(options);
858
+ let dataView;
859
+ if (typeof options.value === 'string') {
860
+ dataView = hexStringToDataView(options.value);
861
+ }
862
+ else {
863
+ dataView = options.value;
864
+ }
865
+ await (descriptor === null || descriptor === undefined ? undefined : descriptor.writeValue(toArrayBufferDataView(dataView)));
866
+ }
867
+ async startNotifications(options) {
868
+ const characteristic = await this.getCharacteristic(options);
869
+ characteristic === null || characteristic === undefined ? undefined : characteristic.removeEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
870
+ characteristic === null || characteristic === undefined ? undefined : characteristic.addEventListener('characteristicvaluechanged', this.onCharacteristicValueChangedCallback);
871
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.startNotifications());
872
+ }
873
+ onCharacteristicValueChanged(event) {
874
+ var _a, _b;
875
+ const characteristic = event.target;
876
+ const key = `notification|${(_a = characteristic.service) === null || _a === undefined ? undefined : _a.device.id}|${(_b = characteristic.service) === null || _b === undefined ? undefined : _b.uuid}|${characteristic.uuid}`;
877
+ this.notifyListeners(key, {
878
+ value: characteristic.value,
879
+ });
880
+ }
881
+ async stopNotifications(options) {
882
+ const characteristic = await this.getCharacteristic(options);
883
+ await (characteristic === null || characteristic === undefined ? undefined : characteristic.stopNotifications());
884
+ }
885
+ getFilters(options) {
886
+ var _a, _b;
887
+ const filters = [];
888
+ for (const service of (_a = options === null || options === undefined ? undefined : options.services) !== null && _a !== undefined ? _a : []) {
889
+ filters.push({
890
+ services: [service],
891
+ name: options === null || options === undefined ? undefined : options.name,
892
+ namePrefix: options === null || options === undefined ? undefined : options.namePrefix,
893
+ });
894
+ }
895
+ if (((options === null || options === undefined ? undefined : options.name) || (options === null || options === undefined ? undefined : options.namePrefix)) && filters.length === 0) {
896
+ filters.push({
897
+ name: options.name,
898
+ namePrefix: options.namePrefix,
899
+ });
900
+ }
901
+ for (const manufacturerData of (_b = options === null || options === undefined ? undefined : options.manufacturerData) !== null && _b !== undefined ? _b : []) {
902
+ // Cast to any to avoid type incompatibility - conversion is handled in bleClient.ts
903
+ filters.push({
904
+ manufacturerData: [manufacturerData],
905
+ });
906
+ }
907
+ // Note: Web Bluetooth API does not support service data in scan filters.
908
+ // Service data filtering will be done client-side in onAdvertisementReceived.
909
+ // We still accept serviceData in options for API consistency across platforms.
910
+ return filters;
911
+ }
912
+ matchesServiceDataFilter(event) {
913
+ var _a;
914
+ const filters = (_a = this.requestBleDeviceOptions) === null || _a === undefined ? undefined : _a.serviceData;
915
+ if (!filters || filters.length === 0) {
916
+ return true; // No filters, accept all
917
+ }
918
+ if (!event.serviceData) {
919
+ return false; // No service data in advertisement
920
+ }
921
+ // Check if any filter matches (OR logic)
922
+ for (const filter of filters) {
923
+ const serviceData = event.serviceData.get(filter.serviceUuid);
924
+ if (!serviceData) {
925
+ continue; // This filter doesn't match, try next
926
+ }
927
+ // If we have service data for this UUID
928
+ if (!filter.dataPrefix) {
929
+ return true; // Filter matched by service UUID alone
930
+ }
931
+ // Check data prefix (DataView on web)
932
+ const data = new Uint8Array(serviceData.buffer);
933
+ const prefixView = filter.dataPrefix;
934
+ if (data.length < prefixView.byteLength) {
935
+ continue; // Data too short
936
+ }
937
+ // Apply mask if provided
938
+ if (filter.mask) {
939
+ const maskView = filter.mask;
940
+ let matches = true;
941
+ for (let i = 0; i < prefixView.byteLength; i++) {
942
+ if ((data[i] & maskView.getUint8(i)) !== (prefixView.getUint8(i) & maskView.getUint8(i))) {
943
+ matches = false;
944
+ break;
945
+ }
946
+ }
947
+ if (matches) {
948
+ return true;
949
+ }
950
+ }
951
+ else {
952
+ // Check if data starts with prefix
953
+ let matches = true;
954
+ for (let i = 0; i < prefixView.byteLength; i++) {
955
+ if (data[i] !== prefixView.getUint8(i)) {
956
+ matches = false;
957
+ break;
958
+ }
959
+ }
960
+ if (matches) {
961
+ return true;
962
+ }
963
+ }
964
+ }
965
+ return false; // No filter matched
966
+ }
967
+ getDeviceFromMap(deviceId) {
968
+ const device = this.deviceMap.get(deviceId);
969
+ if (device === undefined) {
970
+ throw new Error('Device not found. Call "requestDevice", "requestLEScan" or "getDevices" first.');
971
+ }
972
+ return device;
973
+ }
974
+ getBleDevice(device) {
975
+ var _a;
976
+ const bleDevice = {
977
+ deviceId: device.id,
978
+ // use undefined instead of null if name is not available
979
+ name: (_a = device.name) !== null && _a !== undefined ? _a : undefined,
980
+ };
981
+ return bleDevice;
982
+ }
983
983
  }
984
984
 
985
985
  var web = /*#__PURE__*/Object.freeze({