3.2.1
This guide is an introduction to BLE stack and APIs exported by this library. All examples will be based on CC2541 SensorTag.
In the case of Expo, you will need to prepare a plugin config, detailed information can be found here: https://github.com/dotintent/react-native-ble-plx?tab=readme-ov-file#expo-sdk-43 In the case of react native CLI you need to configure two environments:
First step is to create BleManager instance which is an entry point to all available APIs. It should be declared OUTSIDE the life cycle of React. Make sure to create it after application started its execution. We can keep it as a static reference by either creating our own abstraction (ex.1) or by simply creating a new instance (ex.2).
import { BleManager } from 'react-native-ble-plx'
// create your own singleton class
class BLEServiceInstance {
manager: BleManage
constructor() {
this.manager = new BleManager()
}
}
export const BLEService = new BLEServiceInstance()
import { BleManager } from 'react-native-ble-plx'
export const manager = new BleManager()
Only one instance of BleManager is allowed. When you don't need any BLE functionality you can destroy created instance by calling manager.destroy()
function. You can then recreate BleManager
later on.
Note that you may experience undefined behavior when calling a function on one BleManager
and continuing with another instance. A frequently made error is to create a new instance of the manager for every re-render of a React Native Component.
Check if you requested following permissions
eg.
requestBluetoothPermission = async () => {
if (Platform.OS === 'ios') {
return true
}
if (Platform.OS === 'android' && PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) {
const apiLevel = parseInt(Platform.Version.toString(), 10)
if (apiLevel < 31) {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
return granted === PermissionsAndroid.RESULTS.GRANTED
}
if (PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN && PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT) {
const result = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
])
return (
result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED
)
}
}
this.showErrorToast('Permission have not been granted')
return false
}
With neverForLocation
flag active, you can remove ACCESS_FINE_LOCATION
permissions ask e.g.:
const result = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT
])
return (
result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED
)
When iOS application launches BLE stack is not immediately available and we need to check its status.
To detect current state and following state changes we can use onStateChange()
function:
React.useEffect(() => {
const subscription = manager.onStateChange(state => {
if (state === 'PoweredOn') {
scanAndConnect()
subscription.remove()
}
}, true)
return () => subscription.remove()
}, [manager])
Devices needs to be scanned first to be able to connect to them. There is a simple function which allows only one callback to be registered to handle detected devices:
function scanAndConnect() {
manager.startDeviceScan(null, null, (error, device) => {
if (error) {
// Handle error (scanning will be stopped automatically)
return
}
// Check if it is a device you are looking for based on advertisement data
// or other criteria.
if (device.name === 'TI BLE Sensor Tag' || device.name === 'SensorTag') {
// Stop scanning as it's not necessary if you are scanning for one device.
manager.stopDeviceScan()
// Proceed with connection.
}
})
}
It is worth to note that scanning function may emit one device multiple times. However when device is connected it won't broadcast and needs to be disconnected from central to be scanned again. Only one scanning listener can be registered.
To see devices that use Bluetooth 5 Advertising Extension you have to set the legacyScan
variable to false
in Scan options when you are starting BleManager.startDeviceScan(),
Once device is scanned it is in disconnected state. We need to connect to it and discover all services and characteristics it contains. Services may be understood as containers grouping characteristics based on their meaning. Characteristic is a container for a value which can be read, written and monitored based on available capabilities. For example connection may look like this:
device
.connect()
.then(device => {
return device.discoverAllServicesAndCharacteristics()
})
.then(device => {
// Do work on device with services and characteristics
})
.catch(error => {
// Handle errors
})
Discovery of services and characteristics is required to be executed once per connection*. It can be a long process depending on number of characteristics and services available.
* Extremely rarely, when peripheral's service/characteristic set can change during a connection an additional service discovery may be needed.
After successful discovery of services you can call
and other functions which are described in detail in documentation. You can also check our example app which is available in the repository.
onDeviceDisconnected
method allows you to monitor the disconnection of a device, more about the method can be found BleManager.onDeviceDisconnected(). Using it you can implement your own logic to handle the disconnection event. For example, you can try to reconnect to the device or show a notification to the user.
Note: connection will be monitored only when app is in foreground.
const setupOnDeviceDisconnected = (deviceIdToMonitor: String) => {
bleManagerInstance.onDeviceDisconnected(deviceIdToMonitor, disconnectedListener)
}
const disconnectedListener = (error: BleError | null, device: Device | null) => {
if (error) {
console.error(JSON.stringify(error, null, 4))
}
if (device) {
console.info(JSON.stringify(device, null, 4))
// reconnect to the device
device.connect()
}
}
The first thing you need to do is connect to your device. Once the connection is established you can only perform basic operations without the possibility of interacting with the services on the device. To be able to interact with the services on the device, so you need to call an additional command device.discoverAllServicesAndCharacteristics()
because even though you know what service and characteristics are on the device, they all must be visible to the GATT client, which handles all operations.
device
.connect()
.then(device => {
return device.discoverAllServicesAndCharacteristics()
})
.then(device => {
// A fully functional connection you can use, now you can read, write and monitor values
})
.catch(error => {
// Handle errors
})
To read a value from a characteristic, you need to call the readCharacteristic
method on the device object. The method returns a promise that resolves to the characteristic value.
device
.readCharacteristicForService(serviceUUID, characteristicUUID)
.then(characteristic => {
console.log('Read characteristic value:', characteristic.value)
})
.catch(error => {
console.error('Read characteristic error:', error)
})
To write a value to a characteristic, you need to call the writeCharacteristicWithResponse
or writeCharacteristicWithoutResponse
method on the device object. The method returns a promise that resolves when the write operation is completed.
device
.writeCharacteristicWithResponseForService(serviceUUID, characteristicUUID, value)
.then(() => {
console.log('Write characteristic success')
})
.catch(error => {
console.error('Write characteristic error:', error)
})
If you want to connect to a device that isn't discoverable because it is already connected to the system, you can use the getConnectedDevices
method to get a list of connected devices. Then you can use the connect
method on the device object to connect to the device, after making sure that the device is not already connected.
bleManagerInstance
.getConnectedDevices([serviceUUIDs])
.then(devices => {
const device = devices.find(d => d.id === deviceIdWeWantToConnectTo)
if (device && !device.isConnected) {
device.connect()
}
})
.catch(error => {
console.error('Get connected devices error:', error)
})
If you encounter any issues with the library, you can enable native logs to get more information about what is happening under the hood. To enable native logs, you need to set the logLevel
property on the BleManager instance to LogLevel.Verbose
.
bleManagerInstance.setLogLevel(LogLevel.Verbose)
To collect native logs on Android, you can open the Logcat in Android Studio and set filters to package:mine (tag:BluetoothGatt | tag:ReactNativeJS | RxBle)
.
To collect native logs on iOS, you can open the Xcode console.
Classes described below are main building blocks for your BLE support. They are presented in order which aligns them with usage.
BleManager is an entry point for react-native-ble-plx library. It provides all means to discover and work with
Device instances. It should be initialized only once with new
keyword and method
destroy() should be called on its instance when user wants to deallocate all resources.
In case you want to properly support Background Mode, you should provide restoreStateIdentifier
and
restoreStateFunction
in BleManagerOptions.
(BleManagerOptions
= {}
)
const manager = new BleManager();
// ... work with BLE manager ...
manager.destroy();
Destroys BleManager instance. A new instance needs to be created to continue working with this library. All operations which were in progress completes with
Promise<void>
:
Promise may return an error when the function cannot be called.
BluetoothManagerDestroyed
error code.
Cancels pending transaction.
Few operations such as monitoring characteristic's value changes can be cancelled by a user. Basically every API
entry which accepts transactionId
allows to call cancelTransaction
function. When cancelled operation is a
promise or a callback which registers errors, BleError with error code
OperationCancelled will be emitted in that case. Cancelling transaction
which doesn't exist is ignored.
(TransactionId)
Id of pending transactions.
Promise<void>
:
const transactionId = 'monitor_battery';
// Monitor battery notifications
manager.monitorCharacteristicForDevice(
device.id, '180F', '2A19',
(error, characteristic) => {
// Handle battery level changes...
}, transactionId);
// Cancel after specified amount of time
setTimeout(() => manager.cancelTransaction(transactionId), 2000);
Enable Bluetooth. This function blocks until BLE is in PoweredOn state. [Android only]
(TransactionId?)
Transaction handle used to cancel operation
Promise<BleManager>
:
Promise completes when state transition was successful.
Deprecated Disable Bluetooth. This function blocks until BLE is in PoweredOff state. [Android only]
(TransactionId?)
Transaction handle used to cancel operation
Promise<BleManager>
:
Promise completes when state transition was successful.
Current, global State of a BleManager. All APIs are working only when active state is "PoweredOn".
Promise<State>
:
Promise which emits current state of BleManager.
Notifies about State changes of a BleManager.
(boolean
= false
)
If true, current state will be emitted as well. Defaults to false.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
const subscription = this.manager.onStateChange((state) => {
if (state === 'PoweredOn') {
this.scanAndConnect();
subscription.remove();
}
}, true);
Starts device scanning. When previous scan is in progress it will be stopped before executing this command.
(ScanOptions?)
Optional configuration for scanning operation.
Promise<void>
:
Promise may return an error when the function cannot be called.
Device
(devices may be scanned multiple times). It's first argument is potential
Error
which is set
to non
null
value when scanning failed. You have to start scanning process again if that happens. Second argument
is a scanned
Device
.
Promise<void>
:
the promise may be rejected if the operation is impossible to perform.
Request a connection parameter update. This functions may update connection parameters on Android API level 21 or above.
(DeviceId)
Device identifier.
(ConnectionPriority)
: Connection priority.
(TransactionId?)
Transaction handle used to cancel operation.
Promise<Device>
:
Connected device.
Reads RSSI for connected device.
(DeviceId)
Device identifier.
(TransactionId?)
Transaction handle used to cancel operation
Promise<Device>
:
Connected device with updated RSSI value.
Request new MTU value for this device. This function currently is not doing anything on iOS platform as MTU exchange is done automatically. Since Android 14, mtu management has been changed, more information can be found at the link: https://developer.android.com/about/versions/14/behavior-changes-all#mtu-set-to-517
(DeviceId)
Device identifier.
(number)
New MTU to negotiate.
(TransactionId?)
Transaction handle used to cancel operation
Promise<Device>
:
Device with updated MTU size. Default value is 23 (517 since Android 14)..
Returns a list of the peripherals (containing any of the specified services) currently connected to the system which have discovered services. Returned devices may not be connected to your application. Make sure to check if that's the case with function isDeviceConnected.
Promise<Array<Device>>
:
List of known devices with discovered services as stated in the parameter.
Connects to Device with provided ID.
(ConnectionOptions?)
Platform specific options for connection establishment.
Promise<Device>
:
Connected
Device
object if successful.
Monitors if Device was disconnected due to any errors or connection problems.
(function (error: BleError?, device: Device))
callback returning error as a reason of disconnection
if available and
Device
object. If an error is null, that means the connection was terminated by
bleManager.cancelDeviceConnection()
call.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
Discovers all Services, Characteristics and Descriptors for Device.
(TransactionId?)
Transaction handle used to cancel operation
Promise<Device>
:
Promise which emits
Device
object if all available services and
characteristics have been discovered.
List of discovered Characteristics for given Device and Service.
Promise<Array<Characteristic>>
:
Promise which emits array of
Characteristic
objects which are
discovered for a
Device
in specified
Service
.
List of discovered Descriptors for given Device, Service and Characteristic.
Promise<Array<Descriptor>>
:
Promise which emits array of
Descriptor
objects which are
discovered for a
Device
,
Service
in specified
Characteristic
.
Read Characteristic value.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of
Characteristic
will be stored inside returned object.
Write Characteristic value with response.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of characteristic may not be stored inside returned object.
Write Characteristic value without response.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of characteristic may not be stored inside returned object.
Monitor value changes of a Characteristic. If notifications are enabled they will be used in favour of indications.
(function (error: BleError?, characteristic: Characteristic?))
callback which emits
Characteristic
objects with modified value for each notification.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
Read Descriptor value.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Descriptor>
:
Promise which emits first
Descriptor
object matching specified
UUID paths. Latest value of
Descriptor
will be stored inside returned object.
Write Descriptor value.
(DeviceId)
Connected device identifier
(UUID)
Service UUID
(UUID)
Characteristic UUID
(UUID)
Descriptor UUID
(Base64)
Value to be set coded in Base64
(TransactionId?)
Transaction handle used to cancel operation
Promise<Descriptor>
:
Descriptor which saved passed value
Device instance which can be retrieved only by calling bleManager.startDeviceScan().
(NativeDevice)
Native device properties
Current Maximum Transmission Unit for this device. When device is not connected default value of 23 is used.
Type: number
Device's custom manufacturer data. Its format is defined by manufacturer.
Type: Base64?
Raw device scan data. When you have specific advertiser data, you can implement your own processing.
Type: Base64
Map of service UUIDs (as keys) with associated data (as values).
Type: {}?
bleManager.requestConnectionPriorityForDevice() with partially filled arguments.
(ConnectionPriority)
: Connection priority.
(TransactionId?)
Transaction handle used to cancel operation.
Promise<Device>
:
Connected device.
bleManager.readRSSIForDevice() with partially filled arguments.
(TransactionId?)
Transaction handle used to cancel operation.
Promise<Device>
:
This device with updated RSSI value.
bleManager.requestMTUForDevice() with partially filled arguments.
(number)
(TransactionId?)
Transaction handle used to cancel operation.
Promise<Device>
:
Device with updated MTU size. Default value is 23.
bleManager.connectToDevice() with partially filled arguments.
(ConnectionOptions?)
Platform specific options for connection establishment. Not used currently.
Promise<Device>
:
Connected
Device
object if successful.
bleManager.isDeviceConnected() with partially filled arguments.
Promise<boolean>
:
Promise which emits
true
if device is connected, and
false
otherwise.
bleManager.onDeviceDisconnected() with partially filled arguments.
(function (error: BleError?, device: Device))
callback returning error as a reason of disconnection
if available and
Device
object. If an error is null, that means the connection was terminated by
bleManager.cancelDeviceConnection()
call.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
bleManager.discoverAllServicesAndCharacteristicsForDevice() with partially filled arguments.
(TransactionId?)
Transaction handle used to cancel operation
Promise<Device>
:
Promise which emits
Device
object if all available services and
characteristics have been discovered.
bleManager.characteristicsForDevice() with partially filled arguments.
Promise<Array<Characteristic>>
:
Promise which emits array of
Characteristic
objects which are
discovered for a
Device
in specified
Service
.
bleManager.descriptorsForDevice() with partially filled arguments.
Promise<Array<Descriptor>>
:
Promise which emits array of
Descriptor
objects which are
discovered for this
Characteristic
.
bleManager.readCharacteristicForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of
Characteristic
will be stored inside returned object.
bleManager.writeCharacteristicWithResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of characteristic may not be stored inside returned object.
bleManager.writeCharacteristicWithoutResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID paths. Latest value of characteristic may not be stored inside returned object.
bleManager.monitorCharacteristicForDevice() with partially filled arguments.
(function (error: BleError?, characteristic: Characteristic?))
callback which emits
Characteristic
objects with modified value for each notification.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
bleManager.readDescriptorForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Descriptor>
:
Promise which emits first
Descriptor
object matching specified
UUID paths. Latest value of
Descriptor
will be stored inside returned object.
bleManager.writeDescriptorForDevice() with partially filled arguments.
(UUID)
Characteristic UUID
(UUID)
Descriptor UUID
(Base64)
Value to be set coded in Base64
(TransactionId?)
Transaction handle used to cancel operation
Promise<Descriptor>
:
Descriptor which saved passed value.
Service object.
(NativeService)
NativeService properties to be copied.
(BleManager)
Current BleManager instance.
Service unique identifier
Type: Identifier
Value indicating whether the type of service is primary or secondary.
Type: boolean
bleManager.characteristicsForDevice() with partially filled arguments.
Promise<Array<Characteristic>>
:
Promise which emits array of
Characteristic
objects which are
discovered for this service.
bleManager.descriptorsForDevice() with partially filled arguments.
Promise<Array<Descriptor>>
:
Promise which emits array of
Descriptor
objects which are
discovered for this
Service
in specified
Characteristic
.
bleManager.readCharacteristicForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID path. Latest value of
Characteristic
will be stored inside returned object.
bleManager.writeCharacteristicWithResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID path. Latest value of characteristic may not be stored inside returned object.
bleManager.writeCharacteristicWithoutResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits first
Characteristic
object matching specified
UUID path. Latest value of characteristic may not be stored inside returned object.
bleManager.monitorCharacteristicForDevice() with partially filled arguments.
(function (error: BleError?, characteristic: Characteristic?))
callback which emits
Characteristic
objects with modified value for each notification.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
bleManager.readDescriptorForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Descriptor>
:
Promise which emits first
Descriptor
object matching specified
UUID paths. Latest value of
Descriptor
will be stored inside returned object.
bleManager.writeDescriptorForDevice() with partially filled arguments.
(UUID)
Characteristic UUID
(UUID)
Descriptor UUID
(Base64)
Value to be set coded in Base64
(TransactionId?)
Transaction handle used to cancel operation
Promise<Descriptor>
:
Descriptor which saved passed value.
Characteristic object.
(NativeCharacteristic)
NativeCharacteristic
(BleManager)
BleManager
Characteristic unique identifier
Type: Identifier
Service's ID to which characteristic belongs
Type: Identifier
True if characteristic can be written with response
Type: boolean
True if characteristic can be written without response
Type: boolean
True if characteristic is monitoring value changes without ACK.
Type: boolean
True if characteristic is monitoring value changes with ACK.
Type: boolean
bleManager.descriptorsForDevice() with partially filled arguments.
Promise<Array<Descriptor>>
:
Promise which emits array of
Descriptor
objects which are
discovered for this
Characteristic
.
bleManager.readCharacteristicForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits this
Characteristic
. Latest value will be stored
inside returned object.
bleManager.writeCharacteristicWithResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits this
Characteristic
. Latest value may
not be stored inside returned object.
bleManager.writeCharacteristicWithoutResponseForDevice() with partially filled arguments.
(Base64)
Value in Base64 format.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Promise<Characteristic>
:
Promise which emits this
Characteristic
. Latest value may
not be stored inside returned object.
bleManager.monitorCharacteristicForDevice() with partially filled arguments.
(function (error: BleError?, characteristic: Characteristic?))
callback which emits
this
Characteristic
with modified value for each notification.
(TransactionId?)
optional
transactionId
which can be used in
bleManager.cancelTransaction()
function.
Subscription
:
Subscription on which
remove()
function can be called to unsubscribe.
bleManager.readDescriptorForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Descriptor>
:
Promise which emits first
Descriptor
object matching specified
UUID paths. Latest value of
Descriptor
will be stored inside returned object.
bleManager.writeDescriptorForDevice() with partially filled arguments.
(UUID)
Descriptor UUID
(Base64)
Value to be set coded in Base64
(TransactionId?)
Transaction handle used to cancel operation
Promise<Descriptor>
:
Descriptor which saved passed value.
Descriptor object.
(NativeDescriptor)
NativeDescriptor
(BleManager)
BleManager
Descriptor unique identifier
Type: Identifier
Characteristic's ID to which descriptor belongs
Type: Identifier
Characteristic's UUID to which descriptor belongs
Type: UUID
Service's ID to which descriptor belongs
Type: Identifier
bleManager.readDescriptorForDevice() with partially filled arguments.
(TransactionId?)
optional
transactionId
which can be used in
cancelTransaction()
function.
Promise<Descriptor>
:
Promise which emits first
Descriptor
object matching specified
UUID paths. Latest value of
Descriptor
will be stored inside returned object.
bleManager.writeDescriptorForDevice() with partially filled arguments.
(Base64)
Value to be set coded in Base64
(TransactionId?)
Transaction handle used to cancel operation
Promise<Descriptor>
:
Descriptor which saved passed value.
Utility functions and classes.
Converts UUID to full 128bit, lowercase format which should be used to compare UUID values.
(UUID)
16bit, 32bit or 128bit UUID.
UUID
:
128bit lowercase UUID.
Types and classes related to BLE errors.
BleError is an error class which is guaranteed to be thrown by all functions of this library. It contains additional properties which help to identify problems in platform independent way.
Extends Error
((NativeBleError | string))
(BleErrorCodeMessageMapping)
Platform independent error code. Possible values are defined in BleErrorCode.
Type: $Values<any>
Platform independent error code related to ATT errors.
Type: $Values<any>?
iOS specific error code (if not an ATT error).
Type: $Values<any>?
Android specific error code (if not an ATT error).
Type: $Values<any>?
Platform independent error code map adjusted to this library's use cases.
This error can be thrown when unexpected error occurred and in most cases it is related to implementation bug. Original message is available in reason property.
Current promise failed to finish due to BleManager shutdown. It means that user called manager.destroy() function before all operations completed.
Promise was explicitly cancelled by a user with manager.cancelTransaction() function call.
Operation timed out and was cancelled.
Native module couldn't start operation due to internal state, which doesn't allow to do that.
Invalid UUIDs or IDs were passed to API call.
Bluetooth is not supported for this particular device. It may happen on iOS simulator for example.
There are no granted permissions which allow to use BLE functionality. On Android it may require android.permission.ACCESS_COARSE_LOCATION permission or android.permission.ACCESS_FINE_LOCATION permission.
BLE is powered off on device. All previous operations and their state is invalidated.
BLE stack is in unspecified state.
BLE stack is resetting.
BLE state change failed.
Couldn't connect to specified device.
Device was disconnected.
Couldn't read RSSI from device.
Device is already connected. It is not allowed to connect twice to the same device.
Couldn't find device with specified ID.
Operation failed because device has to be connected to perform it.
Device could not change MTU value.
Couldn't discover services for specified device.
Couldn't discover included services for specified service.
Service with specified ID or UUID couldn't be found. User may need to call manager.discoverAllServicesAndCharacteristicsForDevice to cache them.
Services were not discovered. User may need to call manager.discoverAllServicesAndCharacteristicsForDevice to cache them.
Couldn't discover characteristics for specified service.
Couldn't write to specified characteristic. Make sure that characteristic.isWritableWithResponse or characteristic.isWritableWithoutResponse is set to true.
Couldn't read from specified characteristic. Make sure that characteristic.isReadable is set to true.
Couldn't set notification or indication for specified characteristic. Make sure that characteristic.isNotifiable or characteristic.isIndicatable is set to true.
Characteristic with specified ID or UUID couldn't be found. User may need to call manager.discoverAllServicesAndCharacteristicsForDevice to cache them.
Characteristic were not discovered for specified service. User may need to call manager.discoverAllServicesAndCharacteristicsForDevice to cache them.
Invalid Base64 format was passed to characteristic API function call.
Couldn't discover descriptor for specified characteristic.
Couldn't write to specified descriptor.
Couldn't read from specified descriptor.
Couldn't find specified descriptor.
Descriptors are not discovered for specified characteristic.
Invalid Base64 format was passed to descriptor API function call.
Issued a write to a descriptor, which is handled by OS.
Cannot start scanning operation.
Location services are disabled.
Mapping of error codes to error messages
Error codes for ATT errors.
The ATT command or request successfully completed.
The attribute handle is invalid on this device.
The attribute’s value cannot be read.
The attribute’s value cannot be written.
The attribute Protocol Data Unit (PDU) or “message” is invalid.
The attribute requires authentication before its value can be read or written.
The attribute server does not support the request received by the client.
The specified offset value was past the end of the attribute’s value.
The attribute requires authorization before its value can be read or written.
The prepare queue is full, because too many prepare write requests have been queued.
The attribute is not found within the specified attribute handle range.
The attribute cannot be read or written using the ATT read blob request.
The encryption key size used for encrypting this link is insufficient.
The length of the attribute’s value is invalid for the intended operation.
The ATT request has encountered an unlikely error and therefore could not be completed.
The attribute requires encryption before its value can be read or written.
The attribute type is not a supported grouping attribute as defined by a higher-layer specification.
Resources are insufficient to complete the ATT request.
Android specific error codes.
The device has insufficient resources to complete the intended operation.
Internal error occurred which may happen due to implementation error in BLE stack.
BLE stack implementation entered illegal state and operation couldn't complete.
BLE stack didn't allocate sufficient memory buffer for internal caches.
Maximum number of pending operations was exceeded.
Generic BLE stack error.
Command is already queued up in GATT.
Illegal parameter was passed to internal BLE stack function.
Operation is pending.
Authorization failed before performing read or write operation.
More cache entries were loaded then expected.
Invalid configuration
GATT service already started.
GATT link is encrypted but prone to man in the middle attacks.
GATT link is not encrypted.
ATT command was sent but channel is congested.
iOS specific error codes.
An unknown error occurred.
The specified parameters are invalid.
The specified attribute handle is invalid.
The device is not currently connected.
The device has run out of space to complete the intended operation.
The operation is canceled.
The connection timed out.
The peripheral disconnected.
The specified UUID is not permitted.
The peripheral is already advertising.
The connection failed.
The device already has the maximum number of connections.
Unknown device.
All Flow aliases and Flow types used in this library.
Native module logging log level. By default it is set to None.
Logging in native module is disabled
All logs in native module are shown
Only debug logs and of higher importance are shown in native module.
Only info logs and of higher importance are shown in native module.
Only warning logs and of higher importance are shown in native module.
Only error logs and of higher importance are shown in native module.
Connection priority of BLE link determining the balance between power consumption and data throughput.
Device Bluetooth Low Energy state. It's keys are used to check #blemanagerstate values received by BleManager
The current state of the manager is unknown; an update is imminent.
The connection with the system service was momentarily lost; an update is imminent.
The platform does not support Bluetooth low energy.
The app is not authorized to use Bluetooth low energy.
Bluetooth is currently powered off.
Bluetooth is currently powered on and available to use.
Type of error code mapping table
Type: {}
Options which can be passed to when creating BLE Manager
BLE State restoration identifier used to restore state.
Type: string
Optional function which is used to properly restore state of your BLE Manager. Callback
is emitted in the beginning of BleManager creation and optional BleRestoreState
is passed. When value is null
application is launching for the first time, otherwise
it contains saved state which may be used by developer to continue working with
connected peripherals.
Type: function (restoredState: BleRestoredState?): void
(BleRestoredState?)
void
Optional mapping of error codes to error messages. Uses BleErrorCodeMessage by default.
To override logging UUIDs or MAC adresses in error messages copy the original object and overwrite values of interest to you.
Object representing information about restored BLE state after application relaunch.
Options which can be passed to scanning function
By allowing duplicates scanning records are received more frequently [iOS only]
Type: boolean
Scan mode for Bluetooth LE scan [Android only]
Type: $Values<any>
Scan callback type for Bluetooth LE scan [Android only]
Type: $Values<any>
Use legacyScan (default true) [Android only] https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder#setLegacy(boolean)
Type: boolean
Scan callback type for Bluetooth LE scan.
Trigger a callback for every Bluetooth advertisement found that matches the filter criteria. If no filter is active, all advertisement packets are reported. [default value]
A result callback is only triggered for the first advertisement packet received that matches the filter criteria.
Receive a callback when advertisements are no longer received from a device that has been previously reported by a first match callback.
Scan mode for Bluetooth LE scan.
A special Bluetooth LE scan mode. Applications using this scan mode will passively listen for other scan results without starting BLE scans themselves.
Perform Bluetooth LE scan in low power mode. This is the default scan mode as it consumes the least power. [default value]
Perform Bluetooth LE scan in balanced power mode. Scan results are returned at a rate that provides a good trade-off between scan frequency and power consumption.
Scan using highest duty cycle. It's recommended to only use this mode when the application is running in the foreground.
Connection specific options to be passed before connection happen. [Not used]
Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true). [Android only]
Type: boolean
Whether MTU size will be negotiated to this value. It is not guaranteed to get it after connection is successful.
Type: number
Whether action will be taken to reset services cache. This option may be useful when a peripheral's firmware was updated and it's services/characteristics were added/removed/altered. [Android only] https://stackoverflow.com/questions/22596951/how-to-programmatically-force-bluetooth-low-energy-service-discovery-on-android
Type: RefreshGattMoment
Bluetooth device id.
Type: string
Unique identifier for BLE objects.
Type: number
Bluetooth UUID
Type: string
Transaction identifier. All transaction identifiers in numeric form are reserved for internal use.
Type: string
Subscription
Base64 value
Type: string
[Android only] ConnectionOptions parameter to describe when to call BluetoothGatt.refresh()
Type:
"OnConnected"