react-native-ble-manager 11.0.7 → 11.1.0

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/README.md CHANGED
@@ -21,7 +21,7 @@ RN 0.30-0.39 supported until 2.4.3
21
21
 
22
22
  ## Supported Platforms
23
23
 
24
- - iOS 8+
24
+ - iOS 10+
25
25
  - Android (API 19+)
26
26
 
27
27
  ## Install
@@ -32,70 +32,10 @@ npm i --save react-native-ble-manager
32
32
 
33
33
  The library support the react native autolink feature.
34
34
 
35
- ##### Android - Update Manifest
35
+ ## Documentation
36
36
 
37
- ```xml
38
- // file: android/app/src/main/AndroidManifest.xml
39
- <!-- Add xmlns:tools -->
40
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
41
- xmlns:tools="http://schemas.android.com/tools"
42
- package="YOUR_PACKAGE_NAME">
37
+ Read here [the full documentation](https://innoveit.github.io/react-native-ble-manager/)
43
38
 
44
- <!--
45
- HACK: this permission should not be needed on android 12+ devices anymore,
46
- but in fact some manufacturers still need it for BLE to properly work :
47
- https://stackoverflow.com/a/72370969
48
- -->
49
- <uses-permission android:name="android.permission.BLUETOOTH" tools:remove="android:maxSdkVersion" />
50
- <!--
51
- should normally only be needed on android < 12 if you want to:
52
- - activate bluetooth programmatically
53
- - discover local BLE devices
54
- see: https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#discover-local-devices.
55
- Same as above, may still be wrongly needed by some manufacturers on android 12+.
56
- -->
57
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" tools:remove="android:maxSdkVersion" />
58
-
59
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
60
- <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
61
-
62
- <!-- Only when targeting Android 12 or higher -->
63
- <!--
64
- Please make sure you read the following documentation
65
- to have a better understanding of the new permissions.
66
- https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#assert-never-for-location
67
- -->
68
-
69
- <!-- Needed if your app search for Bluetooth devices. -->
70
- <!--
71
- If your app doesn't use Bluetooth scan results to derive physical location information,
72
- you can strongly assert that your app doesn't derive physical location.
73
- -->
74
- <uses-permission android:name="android.permission.BLUETOOTH_SCAN"
75
- android:usesPermissionFlags="neverForLocation" />
76
- <!-- Needed if you want to interact with a BLE device. -->
77
- <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
78
- <!-- Needed if your app makes the current device discoverable to other Bluetooth devices. -->
79
- <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
80
- ...
81
- ```
82
-
83
- If you need communication while the app is not in the foreground you need the "ACCESS_BACKGROUND_LOCATION" permission.
84
-
85
- ##### iOS - Update Info.plist
86
-
87
- In iOS >= 13 you need to add the `NSBluetoothAlwaysUsageDescription` string key.
88
- If the deployment target is earlier than iOS 13, you also need to add the `NSBluetoothPeripheralUsageDescription` string key.
89
-
90
- ## Note
91
-
92
- - Remember to use the `start` method before anything.
93
- - If you have problem with old devices try avoid to connect/read/write to a peripheral during scan.
94
- - Android API >= 23 require the ACCESS_COARSE_LOCATION permission to scan for peripherals. React Native >= 0.33 natively support PermissionsAndroid like in the example.
95
- - Android API >= 29 require the ACCESS_FINE_LOCATION permission to scan for peripherals.
96
- React-Native 0.63.X started targeting Android API 29.
97
- - Before write, read or start notification you need to call `retrieveServices` method
98
- - Because location and bluetooth permissions are runtime permissions, you **must** request these permissions at runtime along with declaring them in your manifest.
99
39
 
100
40
  ## Example
101
41
 
@@ -115,836 +55,6 @@ AppRegistry.registerComponent("MyAwesomeApp", () => App);
115
55
 
116
56
  Or, [use the example directly](example)
117
57
 
118
- ## Methods
119
-
120
- ### start(options)
121
-
122
- Init the module.
123
- Returns a `Promise` object.
124
- Don't call this multiple times.
125
-
126
- **Arguments**
127
-
128
- - `options` - `JSON`
129
-
130
- The parameter is optional the configuration keys are:
131
-
132
- - `showAlert` - `Boolean` - [iOS only] Show or hide the alert if the bluetooth is turned off during initialization
133
- - `restoreIdentifierKey` - `String` - [iOS only] Unique key to use for CoreBluetooth state restoration
134
- - `queueIdentifierKey` - `String` - [iOS only] Unique key to use for a queue identifier on which CoreBluetooth events will be dispatched
135
- - `forceLegacy` - `Boolean` - [Android only] Force to use the LegacyScanManager
136
-
137
- **Examples**
138
-
139
- ```js
140
- BleManager.start({ showAlert: false }).then(() => {
141
- // Success code
142
- console.log("Module initialized");
143
- });
144
- ```
145
-
146
- ### scan(serviceUUIDs, seconds, allowDuplicates, scanningOptions)
147
-
148
- Scan for available peripherals.
149
- Returns a `Promise` object.
150
-
151
- **Arguments**
152
-
153
- - `serviceUUIDs` - `Array of String` - the UUIDs of the services to looking for. On Android the filter works only for 5.0 or newer.
154
- - `seconds` - `Integer` - the amount of seconds to scan.
155
- - `allowDuplicates` - `Boolean` - [iOS only] allow duplicates in device scanning
156
- - `scanningOptions` - `JSON` - [Android only] after Android 5.0, user can control specific ble scan behaviors:
157
- - `numberOfMatches` - `Number` - [Android only] corresponding to [`setNumOfMatches`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setNumOfMatches(int)>). Defaults to `ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT`. /!\ anything other than default may only work when a `ScanFilter` is active /!\
158
- - `matchMode` - `Number` - [Android only] corresponding to [`setMatchMode`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setMatchMode(int)>). Defaults to `ScanSettings.MATCH_MODE_AGGRESSIVE`.
159
- - `callbackType` - `Number` - [Android only] corresponding to [`setCallbackType`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setCallbackType(int)>). Defaults `ScanSettings.CALLBACK_TYPE_ALL_MATCHES`. /!\ anything other than default may only work when a `ScanFilter` is active /!\
160
- - `scanMode` - `Number` - [Android only] corresponding to [`setScanMode`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setScanMode(int)>). Defaults to `ScanSettings.SCAN_MODE_LOW_POWER`.
161
- - `reportDelay` - `Number` - [Android only] corresponding to [`setReportDelay`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setReportDelay(long)>). Defaults to `0ms`.
162
- - `phy` - `Number` - [Android only] corresponding to [`setPhy`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder#setPhy(int)>)
163
- - `legacy` - `Boolean` - [Android only] corresponding to [`setLegacy`](<https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder#setLegacy(boolean)>)
164
- - `exactAdvertisingName` - `string[]` - In Android corresponds to the `ScanFilter` [deviceName](<https://developer.android.com/reference/android/bluetooth/le/ScanFilter.Builder#setDeviceName(java.lang.String)>). In ios the filter is done manually before sending the peripheral.
165
-
166
- **Examples**
167
-
168
- ```js
169
- BleManager.scan([], 5, true).then(() => {
170
- // Success code
171
- console.log("Scan started");
172
- });
173
- ```
174
-
175
- ### stopScan()
176
-
177
- Stop the scanning.
178
- Returns a `Promise` object.
179
-
180
- **Examples**
181
-
182
- ```js
183
- BleManager.stopScan().then(() => {
184
- // Success code
185
- console.log("Scan stopped");
186
- });
187
- ```
188
-
189
- ### connect(peripheralId, options)
190
-
191
- Attempts to connect to a peripheral. In many case if you can't connect you have to scan for the peripheral before.
192
- Returns a `Promise` object.
193
-
194
- > In iOS, attempts to connect to a peripheral do not time out (please see [Apple's doc](https://developer.apple.com/documentation/corebluetooth/cbcentralmanager/1518766-connect)), so you might need to set a timer explicitly if you don't want this behavior.
195
-
196
- **Arguments**
197
-
198
- - `peripheralId` - `String` - the id/mac address of the peripheral to connect.
199
- - `options` - `JSON` - The parameter is optional the configuration keys are:
200
-
201
- - `phy` - `Number` - [Android only] corresponding to the preferred phy channel ([`Android doc`](<https://developer.android.com/reference/android/bluetooth/BluetoothDevice?hl=en#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback,%20int,%20int)>))
202
- - `autoconnect` - `Boolean` - [Android only] whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true) ([`Android doc`](<https://developer.android.com/reference/android/bluetooth/BluetoothDevice?hl=en#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback,%20int,%20int)>))
203
-
204
-
205
- **Examples**
206
-
207
- ```js
208
- BleManager.connect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
209
- .then(() => {
210
- // Success code
211
- console.log("Connected");
212
- })
213
- .catch((error) => {
214
- // Failure code
215
- console.log(error);
216
- });
217
- ```
218
-
219
- ### disconnect(peripheralId, force)
220
-
221
- Disconnect from a peripheral.
222
- Returns a `Promise` object.
223
-
224
- **Arguments**
225
-
226
- - `peripheralId` - `String` - the id/mac address of the peripheral to disconnect.
227
- - `force` - `boolean` - [Android only] defaults to true, if true force closes gatt
228
- connection and send the BleManagerDisconnectPeripheral
229
- event immediately to Javascript, else disconnects the
230
- connection and waits for [`disconnected state`](https://developer.android.com/reference/android/bluetooth/BluetoothProfile#STATE_DISCONNECTED) to
231
- [`close the gatt connection`](<https://developer.android.com/reference/android/bluetooth/BluetoothGatt#close()>)
232
- and then sends the BleManagerDisconnectPeripheral to the
233
- Javascript
234
-
235
- **Examples**
236
-
237
- ```js
238
- BleManager.disconnect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
239
- .then(() => {
240
- // Success code
241
- console.log("Disconnected");
242
- })
243
- .catch((error) => {
244
- // Failure code
245
- console.log(error);
246
- });
247
- ```
248
-
249
- ### enableBluetooth() [Android only]
250
-
251
- Create the request to the user to activate the bluetooth.
252
- Returns a `Promise` object.
253
-
254
- **Examples**
255
-
256
- ```js
257
- BleManager.enableBluetooth()
258
- .then(() => {
259
- // Success code
260
- console.log("The bluetooth is already enabled or the user confirm");
261
- })
262
- .catch((error) => {
263
- // Failure code
264
- console.log("The user refuse to enable bluetooth");
265
- });
266
- ```
267
-
268
- ### checkState()
269
-
270
- Force the module to check the state of the native BLE manager and trigger a BleManagerDidUpdateState event.
271
- Resolves to a promise containing the current BleState.
272
-
273
- **Examples**
274
-
275
- ```js
276
- BleManager.checkState().then((state) =>
277
- console.log(`current BLE state = '${state}'.`)
278
- );
279
- ```
280
-
281
- ### startNotification(peripheralId, serviceUUID, characteristicUUID)
282
-
283
- Start the notification on the specified characteristic, you need to call `retrieveServices` method before.
284
- Returns a `Promise` object.
285
-
286
- **Arguments**
287
-
288
- - `peripheralId` - `String` - the id/mac address of the peripheral.
289
- - `serviceUUID` - `String` - the UUID of the service.
290
- - `characteristicUUID` - `String` - the UUID of the characteristic.
291
-
292
- **Examples**
293
-
294
- ```js
295
- BleManager.startNotification(
296
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
297
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
298
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
299
- )
300
- .then(() => {
301
- // Success code
302
- console.log("Notification started");
303
- })
304
- .catch((error) => {
305
- // Failure code
306
- console.log(error);
307
- });
308
- ```
309
-
310
- ### startNotificationUseBuffer(peripheralId, serviceUUID, characteristicUUID, buffer) [Android only]
311
-
312
- Start the notification on the specified characteristic, you need to call `retrieveServices` method before. The buffer collect messages until the buffer of messages bytes reaches the limit defined with the `buffer` argument and then emit all the collected data. Helpful to reducing the number or js bridge crossings when a characteristic is sending a lot of messages.
313
- Returns a `Promise` object.
314
-
315
- **Arguments**
316
-
317
- - `peripheralId` - `String` - the id/mac address of the peripheral.
318
- - `serviceUUID` - `String` - the UUID of the service.
319
- - `characteristicUUID` - `String` - the UUID of the characteristic.
320
- - `buffer` - `Integer` - the capacity of the buffer (bytes) stored before emitting the data for the characteristic.
321
-
322
- **Examples**
323
-
324
- ```js
325
- BleManager.startNotification(
326
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
327
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
328
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
329
- 1234
330
- )
331
- .then(() => {
332
- // Success code
333
- console.log("Notification started");
334
- })
335
- .catch((error) => {
336
- // Failure code
337
- console.log(error);
338
- });
339
- ```
340
-
341
- ### stopNotification(peripheralId, serviceUUID, characteristicUUID)
342
-
343
- Stop the notification on the specified characteristic.
344
- Returns a `Promise` object.
345
-
346
- **Arguments**
347
-
348
- - `peripheralId` - `String` - the id/mac address of the peripheral.
349
- - `serviceUUID` - `String` - the UUID of the service.
350
- - `characteristicUUID` - `String` - the UUID of the characteristic.
351
-
352
- ### read(peripheralId, serviceUUID, characteristicUUID)
353
-
354
- Read the current value of the specified characteristic, you need to call `retrieveServices` method before.
355
- Returns a `Promise` object that will resolves to an array of plain integers (`number[]`) representing a `ByteArray` structure.
356
- That array can then be converted to a JS `ArrayBuffer` for example using `Buffer.from()` [thanks to this buffer module](https://github.com/feross/buffer).
357
-
358
- **Arguments**
359
-
360
- - `peripheralId` - `String` - the id/mac address of the peripheral.
361
- - `serviceUUID` - `String` - the UUID of the service.
362
- - `characteristicUUID` - `String` - the UUID of the characteristic.
363
-
364
- **Examples**
365
-
366
- ```js
367
- BleManager.read(
368
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
369
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
370
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
371
- )
372
- .then((readData) => {
373
- // Success code
374
- console.log("Read: " + readData);
375
-
376
- // https://github.com/feross/buffer
377
- // https://nodejs.org/api/buffer.html#static-method-bufferfromarray
378
- const buffer = Buffer.from(readData);
379
- const sensorData = buffer.readUInt8(1, true);
380
- })
381
- .catch((error) => {
382
- // Failure code
383
- console.log(error);
384
- });
385
- ```
386
-
387
- ### write(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize)
388
-
389
- Write with response to the specified characteristic, you need to call `retrieveServices` method before.
390
- Returns a `Promise` object.
391
-
392
- **Arguments**
393
-
394
- - `peripheralId` - `String` - the id/mac address of the peripheral.
395
- - `serviceUUID` - `String` - the UUID of the service.
396
- - `characteristicUUID` - `String` - the UUID of the characteristic.
397
- - `data` - `number[]` - the data to write as a plain integer array representing a `ByteArray` structure.
398
- - `maxByteSize` - `Integer` - specify the max byte size before splitting message, defaults to 20 bytes if not specified
399
-
400
- **Data preparation**
401
-
402
- To convert your data to a `number[]`, you should probably be manipulating a `Buffer` or anything representing a JS `ArrayBuffer`.
403
- This will make sure you are converting from valid byte representations of your data first and not with [an integer outside the expected range](https://techtutorialsx.com/2019/10/27/node-js-converting-array-to-buffer/).
404
-
405
- You can create a buffer from files, numbers or strings easily (see examples bellow).
406
-
407
- ```js
408
- // https://github.com/feross/buffer
409
- import { Buffer } from 'buffer';
410
-
411
- * // Creates a Buffer containing the bytes [0x01, 0x02, 0x03].
412
- * const buffer = Buffer.from([1, 2, 3]);
413
- *
414
- * // Creates a Buffer containing the bytes [0x01, 0x01, 0x01, 0x01] – the entries
415
- * // are all truncated using `(value & 255)` to fit into the range 0–255.
416
- * const buffer = Buffer.from([257, 257.5, -255, '1']);
417
- *
418
- * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
419
- * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
420
- * // [116, 195, 169, 115, 116] (in decimal notation)
421
- * const buffer = Buffer.from('tést');
422
- ```
423
-
424
- Feel free to use other packages or google how to convert into byte array if your data has other format.
425
-
426
- **Examples**
427
-
428
- ```js
429
- BleManager.write(
430
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
431
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
432
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
433
- // encode & extract raw `number[]`.
434
- // Each number should be in the 0-255 range as it is converted from a valid byte.
435
- buffer.toJSON().data
436
- )
437
- .then(() => {
438
- // Success code
439
- console.log("Write: " + data);
440
- })
441
- .catch((error) => {
442
- // Failure code
443
- console.log(error);
444
- });
445
- ```
446
-
447
- ### writeWithoutResponse(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize, queueSleepTime)
448
-
449
- Write without response to the specified characteristic, you need to call `retrieveServices` method before.
450
- Returns a `Promise` object.
451
-
452
- **Arguments**
453
-
454
- - `peripheralId` - `String` - the id/mac address of the peripheral.
455
- - `serviceUUID` - `String` - the UUID of the service.
456
- - `characteristicUUID` - `String` - the UUID of the characteristic.
457
- - `data` - `number[]` - the data to write as a plain integer array representing a `ByteArray` structure. (see `write()`).
458
- - `maxByteSize` - `Integer` - (Optional) specify the max byte size
459
- - `queueSleepTime` - `Integer` - (Optional) specify the wait time before each write if the data is greater than maxByteSize
460
-
461
- **Data preparation**
462
-
463
- If your data is not in `number[]` format check info fom the `write()` function example above.
464
-
465
- **Example**
466
-
467
- ```js
468
- BleManager.writeWithoutResponse(
469
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
470
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
471
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
472
- data
473
- )
474
- .then(() => {
475
- // Success code
476
- console.log("Writed: " + data);
477
- })
478
- .catch((error) => {
479
- // Failure code
480
- console.log(error);
481
- });
482
- ```
483
-
484
- ### readRSSI(peripheralId)
485
-
486
- Read the current value of the RSSI.
487
- Returns a `Promise` object resolving with the updated RSSI value (`number`) if it succeeds.
488
-
489
- **Arguments**
490
-
491
- - `peripheralId` - `String` - the id/mac address of the peripheral.
492
-
493
- **Examples**
494
-
495
- ```js
496
- BleManager.readRSSI("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
497
- .then((rssi) => {
498
- // Success code
499
- console.log("Current RSSI: " + rssi);
500
- })
501
- .catch((error) => {
502
- // Failure code
503
- console.log(error);
504
- });
505
- ```
506
-
507
- ### readDescriptor(peripheralId, serviceId, characteristicId, descriptorId)
508
-
509
- Read the current value of the specified descriptor, you need to call `retrieveServices` method before.
510
- Returns a `Promise` object that will resolves to an array of plain integers (`number[]`) representing a `ByteArray` structure.
511
- That array can then be converted to a JS `ArrayBuffer` for example using `Buffer.from()` [thanks to this buffer module](https://github.com/feross/buffer).
512
-
513
- **Arguments**
514
-
515
- - `peripheralId` - `String` - the id/mac address of the peripheral.
516
- - `serviceUUID` - `String` - the UUID of the service.
517
- - `characteristicUUID` - `String` - the UUID of the characteristic.
518
- - `descriptorUUID` - `String` - the UUID of the descriptor.
519
-
520
- **Examples**
521
-
522
- ```js
523
- BleManager.readDescriptor(
524
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
525
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
526
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
527
- "XXXX"
528
- )
529
- .then((readData) => {
530
- // Success code
531
- console.log("Read: " + readData);
532
-
533
- // https://github.com/feross/buffer
534
- // https://nodejs.org/api/buffer.html#static-method-bufferfromarray
535
- const buffer = Buffer.from(readData);
536
- const sensorData = buffer.readUInt8(1, true);
537
- })
538
- .catch((error) => {
539
- // Failure code
540
- console.log(error);
541
- });
542
- ```
543
-
544
- ### requestConnectionPriority(peripheralId, connectionPriority) [Android only API 21+]
545
-
546
- Request a connection parameter update.
547
- Returns a `Promise` object which fulfills with the status of the request.
548
-
549
- **Arguments**
550
-
551
- - `peripheralId` - `String` - the id/mac address of the peripheral.
552
- - `connectionPriority` - `Integer` - the connection priority to be requested, as follows:
553
- - 0 - balanced priority connection
554
- - 1 - high priority connection
555
- - 2 - low power priority connection
556
-
557
- **Examples**
558
-
559
- ```js
560
- BleManager.requestConnectionPriority("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 1)
561
- .then((status) => {
562
- // Success code
563
- console.log("Requested connection priority");
564
- })
565
- .catch((error) => {
566
- // Failure code
567
- console.log(error);
568
- });
569
- ```
570
-
571
- ### requestMTU(peripheralId, mtu) [Android only API 21+]
572
-
573
- Request an MTU size used for a given connection.
574
- Returns a `Promise` object.
575
-
576
- **Arguments**
577
-
578
- - `peripheralId` - `String` - the id/mac address of the peripheral.
579
- - `mtu` - `Integer` - the MTU size to be requested in bytes.
580
-
581
- **Examples**
582
-
583
- ```js
584
- BleManager.requestMTU("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 512)
585
- .then((mtu) => {
586
- // Success code
587
- console.log("MTU size changed to " + mtu + " bytes");
588
- })
589
- .catch((error) => {
590
- // Failure code
591
- console.log(error);
592
- });
593
- ```
594
-
595
- ### retrieveServices(peripheralId[, serviceUUIDs])
596
-
597
- Retrieve the peripheral's services and characteristics.
598
- Returns a `Promise` object.
599
-
600
- **Arguments**
601
-
602
- - `peripheralId` - `String` - the id/mac address of the peripheral.
603
- - `serviceUUIDs` - `String[]` - [iOS only] only retrieve these services.
604
-
605
- **Examples**
606
-
607
- ```js
608
- BleManager.retrieveServices("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then(
609
- (peripheralInfo) => {
610
- // Success code
611
- console.log("Peripheral info:", peripheralInfo);
612
- }
613
- );
614
- ```
615
-
616
- ### refreshCache(peripheralId) [Android only]
617
-
618
- refreshes the peripheral's services and characteristics cache
619
- Returns a `Promise` object.
620
-
621
- **Arguments**
622
-
623
- - `peripheralId` - `String` - the id/mac address of the peripheral.
624
-
625
- **Examples**
626
-
627
- ```js
628
- BleManager.refreshCache("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
629
- .then((peripheralInfo) => {
630
- // Success code
631
- console.log("cache refreshed!");
632
- })
633
- .catch((error) => {
634
- console.error(error);
635
- });
636
- ```
637
-
638
- ### getConnectedPeripherals(serviceUUIDs)
639
-
640
- Return the connected peripherals.
641
- Returns a `Promise` object.
642
-
643
- **Arguments**
644
-
645
- - `serviceUUIDs` - `Array of String` - the UUIDs of the services to looking for.
646
-
647
- **Examples**
648
-
649
- ```js
650
- BleManager.getConnectedPeripherals([]).then((peripheralsArray) => {
651
- // Success code
652
- console.log("Connected peripherals: " + peripheralsArray.length);
653
- });
654
- ```
655
-
656
- ### createBond(peripheralId,peripheralPin) [Android only]
657
-
658
- Start the bonding (pairing) process with the remote device. If you pass peripheralPin(optional), bonding will be auto(without manual entering pin)
659
- Returns a `Promise` object that will resolves if the bond is successfully created, otherwise it will be rejected with the appropriate error message.
660
-
661
- **Examples**
662
-
663
- ```js
664
- BleManager.createBond(peripheralId)
665
- .then(() => {
666
- console.log("createBond success or there is already an existing one");
667
- })
668
- .catch(() => {
669
- console.log("fail to bond");
670
- });
671
- ```
672
-
673
- ### removeBond(peripheralId) [Android only]
674
-
675
- Remove a paired device.
676
- Returns a `Promise` object.
677
-
678
- **Examples**
679
-
680
- ```js
681
- BleManager.removeBond(peripheralId)
682
- .then(() => {
683
- console.log("removeBond success");
684
- })
685
- .catch(() => {
686
- console.log("fail to remove the bond");
687
- });
688
- ```
689
-
690
- ### getBondedPeripherals() [Android only]
691
-
692
- Return the bonded peripherals.
693
- Returns a `Promise` object.
694
-
695
- **Examples**
696
-
697
- ```js
698
- BleManager.getBondedPeripherals([]).then((bondedPeripheralsArray) => {
699
- // Each peripheral in returned array will have id and name properties
700
- console.log("Bonded peripherals: " + bondedPeripheralsArray.length);
701
- });
702
- ```
703
-
704
- ### getDiscoveredPeripherals()
705
-
706
- Return the discovered peripherals after a scan.
707
- Returns a `Promise` object.
708
-
709
- **Examples**
710
-
711
- ```js
712
- BleManager.getDiscoveredPeripherals([]).then((peripheralsArray) => {
713
- // Success code
714
- console.log("Discovered peripherals: " + peripheralsArray.length);
715
- });
716
- ```
717
-
718
- ### removePeripheral(peripheralId) [Android only]
719
-
720
- Removes a disconnected peripheral from the cached list.
721
- It is useful if the device is turned off, because it will be re-discovered upon turning on again.
722
- Returns a `Promise` object.
723
-
724
- **Arguments**
725
-
726
- - `peripheralId` - `String` - the id/mac address of the peripheral.
727
-
728
- ### isPeripheralConnected(peripheralId, serviceUUIDs)
729
-
730
- Check whether a specific peripheral is connected and return `true` or `false`.
731
- Returns a `Promise` object.
732
-
733
- **Examples**
734
-
735
- ```js
736
- BleManager.isPeripheralConnected(
737
- "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
738
- []
739
- ).then((isConnected) => {
740
- if (isConnected) {
741
- console.log("Peripheral is connected!");
742
- } else {
743
- console.log("Peripheral is NOT connected!");
744
- }
745
- });
746
- ```
747
-
748
- ### setName(name) [Android only]
749
-
750
- Create the request to set the name of the bluetooth adapter. (https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#setName(java.lang.String))
751
- Returns a `Promise` object.
752
-
753
- **Examples**
754
-
755
- ```js
756
- BleManager.setName("INNOVEIT_CENTRAL")
757
- .then(() => {
758
- // Success code
759
- console.log("Name set successfully");
760
- })
761
- .catch((error) => {
762
- // Failure code
763
- console.log("Name could not be set");
764
- });
765
- ```
766
-
767
- ### getMaximumWriteValueLengthForWithoutResponse(peripheralId) [iOS only]
768
-
769
- Return the maximum value length for WriteWithoutResponse.
770
- Returns a `Promise` object.
771
-
772
- **Examples**
773
-
774
- ```js
775
- BleManager.getMaximumWriteValueLengthForWithoutResponse("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then((maxValue) => {
776
- console.log("Maximum length for WriteWithoutResponse: " + maxValue);
777
- });
778
- ```
779
-
780
- ### getMaximumWriteValueLengthForWitResponse(peripheralId) [iOS only]
781
-
782
- Return the maximum value length for WriteWithResponse.
783
- Returns a `Promise` object.
784
-
785
- **Examples**
786
-
787
- ```js
788
- BleManager.getMaximumWriteValueLengthForWitResponse("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then((maxValue) => {
789
- console.log("Maximum length for WriteWithResponse: " + maxValue);
790
- });
791
- ```
792
-
793
- ## Events
794
-
795
- ### BleManagerStopScan
796
-
797
- The scanning for peripherals is ended.
798
-
799
- **Arguments**
800
-
801
- - `status` - `Number` - [iOS] the reason for stopping the scan. Error code 10 is used for timeouts, 0 covers everything else. [Android] the reason for stopping the scan (<https://developer.android.com/reference/android/bluetooth/le/ScanCallback#constants_1>). Error code 10 is used for timeouts
802
-
803
- **Examples**
804
-
805
- ```js
806
- bleManagerEmitter.addListener("BleManagerStopScan", (args) => {
807
- // Scanning is stopped
808
- });
809
- ```
810
-
811
- ### BleManagerDidUpdateState
812
-
813
- The BLE change state.
814
-
815
- **Arguments**
816
-
817
- - `state` - `String` - the new BLE state. can be one of `unknown` (iOS only), `resetting` (iOS only), `unsupported`, `unauthorized` (iOS only), `on`, `off`, `turning_on` (android only), `turning_off` (android only).
818
-
819
- **Examples**
820
-
821
- ```js
822
- bleManagerEmitter.addListener("BleManagerDidUpdateState", (args) => {
823
- // The new state: args.state
824
- });
825
- ```
826
-
827
- ### BleManagerDiscoverPeripheral
828
-
829
- The scanning find a new peripheral.
830
-
831
- **Arguments**
832
-
833
- - `id` - `String` - the id of the peripheral
834
- - `name` - `String` - the name of the peripheral
835
- - `rssi` - `Number` - the RSSI value
836
- - `advertising` - `JSON` - the advertising payload, here are some examples:
837
- - `isConnectable` - `Boolean`
838
- - `serviceUUIDs` - `Array of String`
839
- - `manufacturerData` - `JSON` - contains a json with the company id as field and the custom value as raw `bytes` and `data` (Base64 encoded string)
840
- - `serviceData` - `JSON` - contains the raw `bytes` and `data` (Base64 encoded string)
841
- - `txPowerLevel` - `Int`
842
- - `rawData` - [Android only] `JSON` - contains the raw `bytes` and `data` (Base64 encoded string) of the all advertising data
843
-
844
- **Examples**
845
-
846
- ```js
847
- bleManagerEmitter.addListener("BleManagerDiscoverPeripheral", (args) => {
848
- // The id: args.id
849
- // The name: args.name
850
- });
851
- ```
852
-
853
- ### BleManagerDidUpdateValueForCharacteristic
854
-
855
- A characteristic notify a new value.
856
-
857
- **Arguments**
858
-
859
- - `value` — `Array` — the read value
860
- - `peripheral` — `String` — the id of the peripheral
861
- - `characteristic` — `String` — the UUID of the characteristic
862
- - `service` — `String` — the UUID of the characteristic
863
-
864
- > Event will only be emitted after successful `startNotification`.
865
-
866
- **Example**
867
-
868
- ```js
869
- import { bytesToString } from "convert-string";
870
- import { NativeModules, NativeEventEmitter } from "react-native";
871
-
872
- const BleManagerModule = NativeModules.BleManager;
873
- const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
874
-
875
- async function connectAndPrepare(peripheral, service, characteristic) {
876
- // Connect to device
877
- await BleManager.connect(peripheral);
878
- // Before startNotification you need to call retrieveServices
879
- await BleManager.retrieveServices(peripheral);
880
- // To enable BleManagerDidUpdateValueForCharacteristic listener
881
- await BleManager.startNotification(peripheral, service, characteristic);
882
- // Add event listener
883
- bleManagerEmitter.addListener(
884
- "BleManagerDidUpdateValueForCharacteristic",
885
- ({ value, peripheral, characteristic, service }) => {
886
- // Convert bytes array to string
887
- const data = bytesToString(value);
888
- console.log(`Received ${data} for characteristic ${characteristic}`);
889
- }
890
- );
891
- // Actions triggereng BleManagerDidUpdateValueForCharacteristic event
892
- }
893
- ```
894
-
895
- ### BleManagerConnectPeripheral
896
-
897
- A peripheral was connected.
898
-
899
- **Arguments**
900
-
901
- - `peripheral` - `String` - the id of the peripheral
902
- - `status` - `Number` - [Android only] connect [`reasons`](<https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onConnectionStateChange(android.bluetooth.BluetoothGatt,%20int,%20int)>)
903
-
904
- ### BleManagerDisconnectPeripheral
905
-
906
- A peripheral was disconnected.
907
-
908
- **Arguments**
909
-
910
- - `peripheral` - `String` - the id of the peripheral
911
- - `status` - `Number` - [Android only] disconnect [`reasons`](<https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html#onConnectionStateChange(android.bluetooth.BluetoothGatt,%20int,%20int)>)
912
- - `domain` - `String` - [iOS only] disconnect error domain
913
- - `code` - `Number` - [iOS only] disconnect error code (<https://developer.apple.com/documentation/corebluetooth/cberror/code>)
914
-
915
- ### BleManagerPeripheralDidBond
916
-
917
- A bond with a peripheral was established
918
-
919
- **Arguments**
920
-
921
- Object with information about the device
922
-
923
- ### BleManagerCentralManagerWillRestoreState [iOS only]
924
-
925
- This is fired when [`centralManager:WillRestoreState:`](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerdelegate/1518819-centralmanager) is called (app relaunched in the background to handle a bluetooth event).
926
-
927
- **Arguments**
928
-
929
- - `peripherals` - `Array` - an array of previously connected peripherals.
930
-
931
- _For more on performing long-term bluetooth actions in the background:_
932
-
933
- [iOS Bluetooth State Preservation and Restoration](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW10)
934
-
935
- [iOS Relaunch Conditions](https://developer.apple.com/library/archive/qa/qa1962/_index.html)
936
-
937
- ### BleManagerDidUpdateNotificationStateFor [iOS only]
938
-
939
- The peripheral received a request to start or stop providing notifications for a specified characteristic's value.
940
-
941
- **Arguments**
942
-
943
- - `peripheral` - `String` - the id of the peripheral
944
- - `characteristic` - `String` - the UUID of the characteristic
945
- - `isNotifying` - `Boolean` - Is the characteristic notifying or not
946
- - `domain` - `String` - [iOS only] error domain
947
- - `code` - `Number` - [iOS only] error code
948
58
 
949
59
  ## Library development
950
60