react-native-ble-manager
This is a porting of https://github.com/don/cordova-plugin-ble-central project to React Native.
Requirements
RN 0.40+
RN 0.30-0.39 supported until 2.4.3
Supported Platforms
Install
npm i --save react-native-ble-manager
After installing, you need to link the native library. You can either:
- Link native library with
react-native link
, or - Link native library manually
Both approaches are described below.
Link Native Library with react-native link
react-native link react-native-ble-manager
After this step:
- iOS should be linked properly.
- Android will need one more step, you need to edit
android/app/build.gradle
:
// file: android/app/build.gradle
...
android {
...
defaultConfig {
...
minSdkVersion 19 // <--- make sure this is 19 or greater
...
}
...
}
Link Native Library Manually
iOS
- Open the node_modules/react-native-ble-manager/ios folder and drag BleManager.xcodeproj into your Libraries group.
- Check the "Build Phases"of your project and add "libBleManager.a" in the "Link Binary With Libraries" section.
Android
Update Gradle Settings
// file: android/settings.gradle
...
include ':react-native-ble-manager'
project(':react-native-ble-manager').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-ble-manager/android')
Update Gradle Build
// file: android/app/build.gradle
...
android {
...
defaultConfig {
...
minSdkVersion 19 // <--- make sure this is 19 or greater
...
}
...
}
dependencies {
...
compile project(':react-native-ble-manager')
}
Update Android Manifest
// file: android/app/src/main/AndroidManifest.xml
...
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
...
Register React Package
...
import it.innove.BleManagerPackage;
public class MainApplication extends Application implements ReactApplication {
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new BleManagerPackage()
);
}
...
}
Note
- Remember to use the
start
method before anything. - If you have problem with old devices try avoid to connect/read/write to a peripheral during scan.
- Android API >= 23 require the ACCESS_COARSE_LOCATION permission to scan for peripherals. React Native >= 0.33 natively support PermissionsAndroid like in the example.
- Before write, read or start notification you need to call
retrieveServices
method
Example
The easiest way to test is simple make your AppRegistry point to our example component, like this:
import React, { Component } from 'react';
import {
AppRegistry,
} from 'react-native';
import App from 'react-native-ble-manager/example/App'
AppRegistry.registerComponent('MyAwesomeApp', () => App);
Or, you can still look into the whole example folder for a standalone project.
Methods
start(options)
Init the module.
Returns a Promise
object.
Don't call this multiple times.
Arguments
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 restorationforceLegacy
- Boolean
- [Android only] Force to use the LegacyScanManager
Examples
BleManager.start({showAlert: false})
.then(() => {
console.log('Module initialized');
});
scan(serviceUUIDs, seconds, allowDuplicates, scanningOptions)
Scan for availables 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:
Examples
BleManager.scan([], 5, true)
.then(() => {
console.log('Scan started');
});
stopScan()
Stop the scanning.
Returns a Promise
object.
Examples
BleManager.stopScan()
.then(() => {
console.log('Scan stopped');
});
connect(peripheralId)
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.
Arguments
peripheralId
- String
- the id/mac address of the peripheral to connect.
Examples
BleManager.connect('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.then(() => {
console.log('Connected');
})
.catch((error) => {
console.log(error);
});
disconnect(peripheralId)
Disconnect from a peripheral.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral to disconnect.
Examples
BleManager.disconnect('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.then(() => {
console.log('Disconnected');
})
.catch((error) => {
console.log(error);
});
enableBluetooth() [Android only]
Create the request to the user to activate the bluetooth.
Returns a Promise
object.
Examples
BleManager.enableBluetooth()
.then(() => {
console.log('The bluetooh is already enabled or the user confirm');
})
.catch((error) => {
console.log('The user refuse to enable bluetooth');
});
checkState()
Force the module to check the state of BLE and trigger a BleManagerDidUpdateState event.
Examples
BleManager.checkState();
startNotification(peripheralId, serviceUUID, characteristicUUID)
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(() => {
console.log('Notification started');
})
.catch((error) => {
console.log(error);
});
stopNotification(peripheralId, serviceUUID, characteristicUUID)
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(peripheralId, serviceUUID, characteristicUUID)
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) => {
console.log('Read: ' + readData);
const buffer = Buffer.Buffer.from(readData);
const sensorData = buffer.readUInt8(1, true);
})
.catch((error) => {
console.log(error);
});
write(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize)
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
Data 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 { stringToBytes } from 'convert-string';
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(() => {
console.log('Write: ' + data);
})
.catch((error) => {
console.log(error);
});
writeWithoutResponse(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize, queueSleepTime)
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 maxByteSize
Data 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(() => {
console.log('Writed: ' + data);
})
.catch((error) => {
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) => {
console.log('Current RSSI: ' + rssi);
})
.catch((error) => {
console.log(error);
});
requestMTU(peripheralId, mtu) [Android only API 21+]
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(() => {
console.log('MTU size changed');
})
.catch((error) => {
console.log(error);
});
retrieveServices(peripheralId)
Retrieve the peripheral's services and characteristics.
Returns a Promise
object.
Arguments
peripheralId
- String
- the id/mac address of the peripheral.
Examples
BleManager.retrieveServices('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.then((peripheralInfo) => {
console.log('Peripheral info:', peripheralInfo);
});
getConnectedPeripherals(serviceUUIDs)
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) => {
console.log('Connected peripherals: ' + peripheralsArray.length);
});
createBond(peripheralId) [Android only]
Start the bonding (pairing) process with the remote device.
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');
})
getBondedPeripherals() [Android only]
Return the bonded peripherals.
Returns a Promise
object.
Examples
BleManager.getBondedPeripherals([])
.then((bondedPeripheralsArray) => {
console.log('Bonded peripherals: ' + bondedPeripheralsArray.length);
});
getDiscoveredPeripherals()
Return the discovered peripherals after a scan.
Returns a Promise
object.
Examples
BleManager.getDiscoveredPeripherals([])
.then((peripheralsArray) => {
console.log('Discovered peripherals: ' + peripheralsArray.length);
});
removePeripheral(peripheralId) [Android only]
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.
isPeripheralConnected(peripheralId, serviceUUIDs)
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!');
}
});
Events
BleManagerStopScan
The scanning for peripherals is ended.
Arguments
Examples
bleManagerEmitter.addListener(
'BleManagerStopScan',
() => {
}
);
BleManagerDidUpdateState
The BLE change state.
Arguments
state
- String
- the new BLE state ('on'/'off').
Examples
bleManagerEmitter.addListener(
'BleManagerDidUpdateState',
(args) => {
}
);
BleManagerDiscoverPeripheral
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, according to platforms:
- [Android] contains the raw
bytes
and data
(Base64 encoded string) - [iOS] contains a JSON object with different keys according to Apple's doc, here are some examples:
kCBAdvDataChannel
- Number
kCBAdvDataIsConnectable
- Number
kCBAdvDataLocalName
- String
kCBAdvDataManufacturerData
- JSON
- contains the raw bytes
and data
(Base64 encoded string)
Examples
bleManagerEmitter.addListener(
'BleManagerDiscoverPeripheral',
(args) => {
}
);
BleManagerDidUpdateValueForCharacteristic
A characteristic notify a new value.
Arguments
peripheral
- String
- the id of the peripheralcharacteristic
- String
- the UUID of the characteristicvalue
- Array
- the read value
BleManagerConnectPeripheral
A peripheral was connected.
Arguments
peripheral
- String
- the id of the peripheral
BleManagerDisconnectPeripheral
A peripheral was disconnected.
Arguments
peripheral
- String
- the id of the peripheral