Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
react-native-ble-manager
Advanced tools
This is a porting of https://github.com/don/cordova-plugin-ble-central project to React Native.
RN 0.60+
RN 0.40-0.59 supported until 6.7.X RN 0.30-0.39 supported until 2.4.3
npm i --save react-native-ble-manager
The library support the react native autolink feature.
// file: android/app/src/main/AndroidManifest.xml
<!-- Add xmlns:tools -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="YOUR_PACKAGE_NAME">
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>
<!-- Only when targeting Android 12 or higher -->
<!-- Please make sure you read the following documentation to have a
better understanding of the new permissions.
https://developer.android.com/guide/topics/connectivity/bluetooth/permissions#assert-never-for-location
-->
<!-- If your app doesn't use Bluetooth scan results to derive physical location information,
you can strongly assert that your app
doesn't derive physical location. -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"
android:usesPermissionFlags="neverForLocation"
tools:targetApi="s" />
<!-- Needed only if your app looks for Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- Needed only if your app makes the device discoverable to Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
...
If you need communication while the app is not in the foreground you need the "ACCESS_BACKGROUND_LOCATION" permission.
In iOS >= 13 you need to add the NSBluetoothAlwaysUsageDescription
string key.
start
method before anything.retrieveServices
methodThe easiest way to test is simple make your AppRegistry point to our example component, like this:
// in your index.ios.js or index.android.js
import React, { Component } from "react";
import { AppRegistry } from "react-native";
import App from "react-native-ble-manager/example/App"; //<-- simply point to the example js!
AppRegistry.registerComponent("MyAwesomeApp", () => App);
Or, you can still look into the whole example folder for a standalone project.
Init the module.
Returns a Promise
object.
Don't call this multiple times.
Arguments
options
- JSON
The parameter is optional the configuration keys are:
showAlert
- Boolean
- [iOS only] Show or hide the alert if the bluetooth is turned off during initializationrestoreIdentifierKey
- String
- [iOS only] Unique key to use for CoreBluetooth state restorationqueueIdentifierKey
- String
- [iOS only] Unique key to use for a queue identifier on which CoreBluetooth events will be dispatchedforceLegacy
- Boolean
- [Android only] Force to use the LegacyScanManagerExamples
BleManager.start({ showAlert: false }).then(() => {
// Success code
console.log("Module initialized");
});
Scan for available peripherals.
Returns a Promise
object.
Arguments
serviceUUIDs
- Array of String
- the UUIDs of the services to looking for. On Android the filter works only for 5.0 or newer.seconds
- Integer
- the amount of seconds to scan.allowDuplicates
- Boolean
- [iOS only] allow duplicates in device scanningscanningOptions
- JSON
- [Android only] after Android 5.0, user can control specific ble scan behaviors:
numberOfMatches
- Number
- [Android only] corresponding to setNumOfMatches
. Defaults to ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT
.matchMode
- Number
- [Android only] corresponding to setMatchMode
. Defaults to ScanSettings.MATCH_MODE_AGGRESSIVE
.callbackType
- Number
- [Android only] corresponding to setCallbackType
. Defaults ScanSettings.CALLBACK_TYPE_ALL_MATCHES
.scanMode
- Number
- [Android only] corresponding to setScanMode
. Defaults to ScanSettings.SCAN_MODE_LOW_POWER
.reportDelay
- Number
- [Android only] corresponding to setReportDelay
. Defaults to 0ms
.phy
- Number
- [Android only] corresponding to setPhy
legacy
- Boolean
- [Android only] corresponding to setLegacy
Examples
BleManager.scan([], 5, true).then(() => {
// Success code
console.log("Scan started");
});
Stop the scanning.
Returns a Promise
object.
Examples
BleManager.stopScan().then(() => {
// Success code
console.log("Scan stopped");
});
Attempts to connect to a peripheral. In many case if you can't connect you have to scan for the peripheral before.
Returns a Promise
object.
In iOS, attempts to connect to a peripheral do not time out (please see Apple's doc), so you might need to set a timer explicitly if you don't want this behavior.
Arguments
peripheralId
- String
- the id/mac address of the peripheral to connect.Examples
BleManager.connect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.then(() => {
// Success code
console.log("Connected");
})
.catch((error) => {
// Failure code
console.log(error);
});
Disconnect from a peripheral.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral to disconnect.force
- boolean
- [Android only] defaults to true, if true force closes gatt
connection and send the BleManagerDisconnectPeripheral
event immediately to Javascript, else disconnects the
connection and waits for disconnected state
to
close the gatt connection
and then sends the BleManagerDisconnectPeripheral to the
JavascriptExamples
BleManager.disconnect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.then(() => {
// Success code
console.log("Disconnected");
})
.catch((error) => {
// Failure code
console.log(error);
});
Create the request to the user to activate the bluetooth.
Returns a Promise
object.
Examples
BleManager.enableBluetooth()
.then(() => {
// Success code
console.log("The bluetooth is already enabled or the user confirm");
})
.catch((error) => {
// Failure code
console.log("The user refuse to enable bluetooth");
});
Force the module to check the state of BLE and trigger a BleManagerDidUpdateState event.
Examples
BleManager.checkState();
Start the notification on the specified characteristic, you need to call retrieveServices
method before.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.Examples
BleManager.startNotification(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
)
.then(() => {
// Success code
console.log("Notification started");
})
.catch((error) => {
// Failure code
console.log(error);
});
Start the notification on the specified characteristic, you need to call retrieveServices
method before. The buffer will collect a number or messages from the server and then emit once the buffer count it reached. Helpful to reducing the number or js bridge crossings when a characteristic is sending a lot of messages.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.buffer
- Integer
- a number of message to buffer prior to emit for the characteristic.Examples
BleManager.startNotification(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
1234
)
.then(() => {
// Success code
console.log("Notification started");
})
.catch((error) => {
// Failure code
console.log(error);
});
Stop the notification on the specified characteristic.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.Read the current value of the specified characteristic, you need to call retrieveServices
method before.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.Examples
BleManager.read(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
)
.then((readData) => {
// Success code
console.log("Read: " + readData);
const buffer = Buffer.Buffer.from(readData); //https://github.com/feross/buffer#convert-arraybuffer-to-buffer
const sensorData = buffer.readUInt8(1, true);
})
.catch((error) => {
// Failure code
console.log(error);
});
Write with response to the specified characteristic, you need to call retrieveServices
method before.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.data
- Byte array
- the data to write.maxByteSize
- Integer
- specify the max byte size before splitting message, defaults to 20 bytes if not specifiedData preparation
If your data is not in byte array format you should convert it first. For strings you can use convert-string
or other npm package in order to achieve that.
Install the package first:
npm install convert-string
Then use it in your application:
// Import/require in the beginning of the file
import { stringToBytes } from "convert-string";
// Convert data to byte array before write/writeWithoutResponse
const data = stringToBytes(yourStringData);
Feel free to use other packages or google how to convert into byte array if your data has other format.
Examples
BleManager.write(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
data
)
.then(() => {
// Success code
console.log("Write: " + data);
})
.catch((error) => {
// Failure code
console.log(error);
});
Write without response to the specified characteristic, you need to call retrieveServices
method before.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUID
- String
- the UUID of the service.characteristicUUID
- String
- the UUID of the characteristic.data
- Byte array
- the data to write.maxByteSize
- Integer
- (Optional) specify the max byte sizequeueSleepTime
- Integer
- (Optional) specify the wait time before each write if the data is greater than maxByteSizeData preparation
If your data is not in byte array format check info for the write function above.
Example
BleManager.writeWithoutResponse(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
data
)
.then(() => {
// Success code
console.log("Writed: " + data);
})
.catch((error) => {
// Failure code
console.log(error);
});
Read the current value of the RSSI.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.Examples
BleManager.readRSSI("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.then((rssi) => {
// Success code
console.log("Current RSSI: " + rssi);
})
.catch((error) => {
// Failure code
console.log(error);
});
Request a connection parameter update.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.connectionPriority
- Integer
- the connection priority to be requested, as follows:
Examples
BleManager.requestConnectionPriority("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 1)
.then((status) => {
// Success code
console.log("Requested connection priority");
})
.catch((error) => {
// Failure code
console.log(error);
});
Request an MTU size used for a given connection.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.mtu
- Integer
- the MTU size to be requested in bytes.Examples
BleManager.requestMTU("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 512)
.then((mtu) => {
// Success code
console.log("MTU size changed to " + mtu + " bytes");
})
.catch((error) => {
// Failure code
console.log(error);
});
Retrieve the peripheral's services and characteristics.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.serviceUUIDs
- String[]
- [iOS only] only retrieve these services.Examples
BleManager.retrieveServices("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then(
(peripheralInfo) => {
// Success code
console.log("Peripheral info:", peripheralInfo);
}
);
refreshes the peripheral's services and characteristics cache
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.Examples
BleManager.refreshCache("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.then((peripheralInfo) => {
// Success code
console.log("cache refreshed!");
})
.catch((error) => {
console.error(error);
});
Return the connected peripherals.
Returns a Promise
object.
Arguments
serviceUUIDs
- Array of String
- the UUIDs of the services to looking for.Examples
BleManager.getConnectedPeripherals([]).then((peripheralsArray) => {
// Success code
console.log("Connected peripherals: " + peripheralsArray.length);
});
Start the bonding (pairing) process with the remote device. If you pass peripheralPin(optional), bonding will be auto(without manual entering pin)
Returns a Promise
object. The promise is resolved when either new bond successfully created
or bond already existed
, otherwise it will be rejected.
Examples
BleManager.createBond(peripheralId)
.then(() => {
console.log("createBond success or there is already an existing one");
})
.catch(() => {
console.log("fail to bond");
});
Remove a paired device.
Returns a Promise
object.
Examples
BleManager.removeBond(peripheralId)
.then(() => {
console.log("removeBond success");
})
.catch(() => {
console.log("fail to remove the bond");
});
Return the bonded peripherals.
Returns a Promise
object.
Examples
BleManager.getBondedPeripherals([]).then((bondedPeripheralsArray) => {
// Each peripheral in returned array will have id and name properties
console.log("Bonded peripherals: " + bondedPeripheralsArray.length);
});
Return the discovered peripherals after a scan.
Returns a Promise
object.
Examples
BleManager.getDiscoveredPeripherals([]).then((peripheralsArray) => {
// Success code
console.log("Discovered peripherals: " + peripheralsArray.length);
});
Removes a disconnected peripheral from the cached list.
It is useful if the device is turned off, because it will be re-discovered upon turning on again.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.Check whether a specific peripheral is connected and return true
or false
.
Returns a Promise
object.
Examples
BleManager.isPeripheralConnected(
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
[]
).then((isConnected) => {
if (isConnected) {
console.log("Peripheral is connected!");
} else {
console.log("Peripheral is NOT connected!");
}
});
Create the request to set the name of the bluetooth adapter. (https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#setName(java.lang.String))
Returns a Promise
object.
Examples
BleManager.setName("INNOVEIT_CENTRAL")
.then(() => {
// Success code
console.log("Name set successfully");
})
.catch((error) => {
// Failure code
console.log("Name could not be set");
});
The scanning for peripherals is ended.
Arguments
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 timeoutsExamples
bleManagerEmitter.addListener("BleManagerStopScan", (args) => {
// Scanning is stopped
});
The BLE change state.
Arguments
state
- String
- the new BLE state ('on'/'off').Examples
bleManagerEmitter.addListener("BleManagerDidUpdateState", (args) => {
// The new state: args.state
});
The scanning find a new peripheral.
Arguments
id
- String
- the id of the peripheralname
- String
- the name of the peripheralrssi
- Number
- the RSSI valueadvertising
- JSON
- the advertising payload, here are some examples:
isConnectable
- Boolean
serviceUUIDs
- Array of String
manufacturerData
- JSON
- contains the raw bytes
and data
(Base64 encoded string)serviceData
- JSON
- contains the raw bytes
and data
(Base64 encoded string)txPowerLevel
- Int
Examples
bleManagerEmitter.addListener("BleManagerDiscoverPeripheral", (args) => {
// The id: args.id
// The name: args.name
});
A characteristic notify a new value.
Arguments
value
— Array
— the read valueperipheral
— String
— the id of the peripheralcharacteristic
— String
— the UUID of the characteristicservice
— String
— the UUID of the characteristicEvent will only be emitted after successful
startNotification
.
Example
import { bytesToString } from "convert-string";
import { NativeModules, NativeEventEmitter } from "react-native";
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
async function connectAndPrepare(peripheral, service, characteristic) {
// Connect to device
await BleManager.connect(peripheral);
// Before startNotification you need to call retrieveServices
await BleManager.retrieveServices(peripheral);
// To enable BleManagerDidUpdateValueForCharacteristic listener
await BleManager.startNotification(peripheral, service, characteristic);
// Add event listener
bleManagerEmitter.addListener(
"BleManagerDidUpdateValueForCharacteristic",
({ value, peripheral, characteristic, service }) => {
// Convert bytes array to string
const data = bytesToString(value);
console.log(`Received ${data} for characteristic ${characteristic}`);
}
);
// Actions triggereng BleManagerDidUpdateValueForCharacteristic event
}
A peripheral was connected.
Arguments
peripheral
- String
- the id of the peripheralstatus
- Number
- [Android only] connect reasons
A peripheral was disconnected.
Arguments
peripheral
- String
- the id of the peripheralstatus
- Number
- [Android only] disconnect reasons
domain
- String
- [iOS only] disconnect error domaincode
- Number
- [iOS only] disconnect error code (https://developer.apple.com/documentation/corebluetooth/cberror/code)A bond with a peripheral was established
Arguments
Object with information about the device
This is fired when centralManager:WillRestoreState:
is called (app relaunched in the background to handle a bluetooth event).
Arguments
peripherals
- Array
- an array of previously connected peripherals.For more on performing long-term bluetooth actions in the background:
iOS Bluetooth State Preservation and Restoration
The peripheral received a request to start or stop providing notifications for a specified characteristic's value.
Arguments
peripheral
- String
- the id of the peripheralcharacteristic
- String
- the UUID of the characteristicisNotifying
- Boolean
- Is the characteristic notifying or notdomain
- String
- [iOS only] error domaincode
- Number
- [iOS only] error codeFAQs
A BLE module for react native.
The npm package react-native-ble-manager receives a total of 29,428 weekly downloads. As such, react-native-ble-manager popularity was classified as popular.
We found that react-native-ble-manager demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.