React Native version of BluetoothSerial plugin for both Android and iOS. Pulled from React Native Bluetooth Serial.
For iOS, this module now support service declaration, by default, those services are Read Bear Lab, Adafruit BLE, Bluegiga, Laird Virtual Serial Port, and Rongta.
npm install react-native-bluetooth-serial-next --save
react-native link react-native-bluetooth-serial-next
For Android, you need to put the following code to AndroidManifest.xml
in android/app/src/main
at your project root folder.
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
npm install react-native-bluetooth-serial-next --save
Libraries
➜ Add Files to [your project's name]
node_modules
➜ react-native-bluetooth-serial-next
and add RCTBluetoothSerial.xcodeproj
libRCTBluetoothSerial.a
to your project’s Build Phases
➜ Link Binary With Libraries
RCTBluetoothSerial.xcodeproj
in the project navigator and go the Build Settings
tab. Make sure ‘All’ is toggled on (instead of ‘Basic’). In the Search Paths
section, look for Header Search Paths
and make sure it contains both $(SRCROOT)/../../react-native/React
and $(SRCROOT)/../../../React
- mark both as recursive
.Cmd+R
)npm install react-native-bluetooth-serial-next --save
android/app/src/main/java/[...]/MainActivity.java
or MainApplication.java
for React Native >= 0.29import com.nuttawutmalee.RCTBluetoothSerial.*;
to the imports at the top of the filenew RCTBluetoothSerialPackage()
to the list returned by the getPackages()
methodandroid/settings.gradle
include ':react-native-bluetooth-serial-next'
project(':react-native-bluetooth-serial-next').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-bluetooth-serial-next/android')
android/app/build.gradle
compile project(':react-native-bluetooth-serial-next')
git clone https://github.com/nuttawutmalee/react-native-bluetooth-serial-next.git
cd react-native-bluetooth-serial-next/example
npm install && npm link ../
npm start
react-native run-ios
or react-native run-android
This is basically the result object from API methods depending on operation system.
iOS
{
id: '111-111-111-111',
uuid: '111-111-111-111',
name: 'Bluetooth Printer',
rssi: 'This field might not be present in the object',
}
Android
{
id: '111-111-111-111',
address: '111-111-111-111',
name: 'Bluetooth Printer',
class: 'This field might not be present in the object',
}
iOS
{
name: 'This field might not be present in the object',
service: 'BLE service UUID string',
read: 'BLE read characteristic UUID string',
write: 'BLE write characteristic UUID string',
}
This method will create an event listener and send it though as a component prop and it will remove all event listeners on componentWillUnmount
as well.
'subscription'
The event listener prop name.true
Should event listeners remove all listeners and subscriptionclass MyComponent extends React.Component {
...
}
export default withSubscription({
subscriptionName: 'events',
destroyOnWillUnmount: true,
})(MyComponent);
Prompts the application device to enable bluetooth adapter.
await BluetoothSerial.requestEnable();
Enable bluetooth adapter service.
await BluetoothSerial.enable();
Disable bluetooth adapter service.
await BluetoothSerial.disable();
Indicates bluetooth adapter service status.
const isEnabled = await BluetoothSerial.isEnabled();
List all paired (Android) or connected (iOS) bluetooth devices.
const devices = await BluetoothSerial.list();
List all unpaired bluetooth devices.
const devices = await BluetoothSerial.listUnpaired();
const devices = await BluetoothSerial.discoverUnpairedDevices();
Cancel bluetooth device discovery process.
await BluetoothSerial.cancelDiscovery();
await BluetoothSerial.stopScanning();
Give bluetooth adapter a new name.
const newName = await BluetoothSerial.setAdapterName("New Adapter Name");
Pair with a bluetooth device.
const device = await BluetoothSerial.pairDevice(id);
Unpair from a bluetooth device.
const device = await BluetoothSerial.unpairDevice(id);
Connect to a specific bluetooth device.
const device = await BluetoothSerial.connect(id);
Disconnect from the specific connected bluetooth device. If id
is omitted, the first connected device will be disconnected.
await BluetoothSerial.disconnect();
Disconnect all connected bluetooth devices.
await BluetoothSerial.disconnectAll();
Indicates the specific connected bluetooth device connection status. If id
is omitted, it will return the connection status of the first connected device.
const isConnected = await BluetoothSerial.isConnected();
Listen and read data from the selected or first connected device.
''
BluetoothSerial.read((data, subscription) => {
console.log(data);
if (this.imBoredNow && subscription) {
BluetoothSerial.removeSubscription(subscription);
}
}, "\r\n");
Read data from the selected or first connected device once.
''
const data = await BluetoothSerial.readOnce("\r\n");
Read data from the selected or first connected device every n ms.
1000
''
BluetoothSerial.readEvery(
(data, intervalId) => {
console.log(data);
if (this.imBoredNow && intervalId) {
clearInterval(intervalId);
}
},
5000,
"\r\n"
);
Read all buffer data from the selected or first connected device.
const data = await BluetoothSerial.readFromDevice();
Read all buffer data up to certain delimiter from the selected or first connected device.
const data = await BluetoothSerial.readUntilDelimiter("\r\n");
Write buffer or string to the selected or first connected device.
await BluetoothSerial.write("This is the test message");
Write string to the selected or first connected device.
await BluetoothSerial.writeToDevice("This is the test message");
Clear all buffer data of the selected or first connected device.
await BluetoothSerial.clear();
Get length of current buffer data of the selected or first connected device.
const bufferLength = await BluetoothSerial.available();
Set delimiter that will split the buffer data when you are reading from device.
const deviceId = await BluetoothSerial.withDelimiter("\r\n");
You can get the default services which are Read Bear Lab, Adafruit BLE, Bluegiga, Laird Virtual Serial Port, and Rongta via BluetoothSerial.DEFAULT_SERVICES
array.
Set custom bluetooth services for filtering out the specific protocols that you need.
service
, read
, and write
key-value.true
Should we include BluetoothSerial.DEFAULT_SERVICES
in the services array?const updatedServices = await BluetoothSerial.setServices([
name: 'Custom Bluetooth Service',
service: '111-111-111-111-111-111',
read: '111-111-111-111-111-111',
write: '111-111-111-111-111-111',
], false);
Get current services.
const currentServices = await BluetoothSerial.getServices();
Restore services and set them to default services (BluetoothSerial.DEFAULT_SERVICES
.)
const services = await BluetoothSerial.restoreServices();
This module supports multiple devices connection, as you can see in API Methods, most of the connection, IO, and buffer methods have id
parameter that you can pass and specify which bluetooth device that you want to control.
However, to keep it clean and simple, you can use the following method to simplify them.
This method gives the ability to call group of API methods instead of pass id
parameter at the end of each methods.
The followings are group of methods that you can use with this method.
connect
disconnect
isConnected
clear
available
withDelimiter
read
readOnce
readEvery
readUntilDelimiter
readFromDevice
write
writeToDevice
const myDevice = BluetoothSerial.device(myId);
const yourDevice = BluetoothSerial.device(yourId);
await myDevice.connect();
await myDevice.write('This is a message for my device.');
let yourReadSubscription;
await yourDevice.connect();
await yourDevice.read((data, subscription) => {
yourReadSubscription = subscription;
console.log('Your data:', data);
if (/** */) {
BluetoothSerial.removeSubscription(subscription);
yourReadSubscription = null;
}
});
await myDevice.disconnect();
if (yourReadSubscription) {
BluetoothSerial.removeSubscription(yourReadSubscription);
}
await yourDevice.disconnect();
bluetoothEnabled
: When bluetooth adapter is turned on.
bluetoothDisabled
: When bluetooth adapter is turned off.
connectionSuccess
: When device is connected. You get object of message and device.
{
message: ...,
device: {
...
}
}
connectionFailed
: When you failed to connect to the device. You get object of message and device.{
message: ...,
device: {
...
}
}
connectionLost
: When the device connection is lost. You get object of message and device.{
message: ...,
device: {
...
}
}
read
or data
: String of data from device. You get object of device id and data.{
id: ...,
data: ...
}
error
: Error message from native code.{
message: ...
}
Author: stylder
Source Code: https://github.com/stylder/ReactNativeBluetoothSerialArduino
#react-native #react #mobile-apps