@infobiotech/react-native-bluetooth-serial-next v0.5.1
This repository is forked form the original. The README is not updated.
This repository is considered as unstable for production.
React Native Bluetooth Serial Next :)
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.
Table of Contents
Getting started
npm install react-native-bluetooth-serial-next --save
react-native link react-native-bluetooth-serial-nextFor 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_FINE_LOCATION" />Manual Installation
iOS
npm install react-native-bluetooth-serial-next --save- In XCode, in the project navigator, right click
Libraries➜Add Files to [your project's name] - Go to
node_modules➜react-native-bluetooth-serial-nextand addRCTBluetoothSerial.xcodeproj - In XCode, in the project navigator, select your project. Add
libRCTBluetoothSerial.ato your project'sBuild Phases➜Link Binary With Libraries - Click
RCTBluetoothSerial.xcodeprojin the project navigator and go theBuild Settingstab. Make sure 'All' is toggled on (instead of 'Basic'). In theSearch Pathssection, look forHeader Search Pathsand make sure it contains both$(SRCROOT)/../../react-native/Reactand$(SRCROOT)/../../../React- mark both asrecursive. - Run your project (
Cmd+R)
Android
npm install react-native-bluetooth-serial-next --save- Open up
android/app/src/main/java/[...]/MainActivity.javaorMainApplication.javafor React Native >= 0.29- Add
import com.nuttawutmalee.RCTBluetoothSerial.*;to the imports at the top of the file - Add
new RCTBluetoothSerialPackage()to the list returned by thegetPackages()method
- Add
- Append the following lines to
android/settings.gradleinclude ':react-native-bluetooth-serial-next' project(':react-native-bluetooth-serial-next').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-bluetooth-serial-next/android') - Insert the following lines inside the dependencies block in
android/app/build.gradlecompile project(':react-native-bluetooth-serial-next')
Example
git clone https://github.com/nuttawutmalee/react-native-bluetooth-serial-next.gitcd react-native-bluetooth-serial-next/examplenpm install && npm link ../npm startreact-native run-iosorreact-native run-android
API References
Device object
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',
}Service 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',
}High order component
withSubscription( options : Object ) : React.Component
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.
- options : Object
- subscriptionName : String =
'subscription'The event listener prop name. - destroyOnWillUnmount : Boolean =
trueShould event listeners remove all listeners and subscription
- subscriptionName : String =
class MyComponent extends React.Component {
...
}
export default withSubscription({
subscriptionName: 'events',
destroyOnWillUnmount: true,
})(MyComponent);Methods
Bluetooth adapter
requestEnable() : Promise\
Prompts the application device to enable bluetooth adapter.
- For iOS, this method will throw an error.
- For Android, if the user does not enable bluetooth upon request, it will throw an error.
await BluetoothSerial.requestEnable();enable() : Promise\
Enable bluetooth adapter service.
- For iOS, this method will throw an error.
await BluetoothSerial.enable();disable() : Promise\
Disable bluetooth adapter service.
- For iOS, this method will throw an error.
await BluetoothSerial.disable();isEnabled() : Promise\
Indicates bluetooth adapter service status.
const isEnabled = await BluetoothSerial.isEnabled();list() : Promise\<Device[]>
List all paired (Android) or connected (iOS) bluetooth devices.
const devices = await BluetoothSerial.list();listUnpaired() : Promise\<Device[]> | discoverUnpairedDevices() : Promise\<Device[]>
List all unpaired bluetooth devices.
const devices = await BluetoothSerial.listUnpaired();
const devices = await BluetoothSerial.discoverUnpairedDevices();cancelDiscovery() : Promise\ | stopScanning() : Promise\
Cancel bluetooth device discovery process.
await BluetoothSerial.cancelDiscovery();
await BluetoothSerial.stopScanning();setAdapterName( name : String ) : Promise\
Give bluetooth adapter a new name.
- name : String Bluetooth adapter new name.
- For iOS, this method will throw an error.
const newName = await BluetoothSerial.setAdapterName("New Adapter Name");Device pairing
pairDevice( id : String ) : Promise\<Device | null>
Pair with a bluetooth device.
- id : String Device id or uuid.
- For iOS, this method will throw an error.
const device = await BluetoothSerial.pairDevice(id);unpairDevice( id : String ) : Promise\<Device | null>
Unpair from a bluetooth device.
- id : String Device id or uuid.
- For iOS, this method will throw an error.
const device = await BluetoothSerial.unpairDevice(id);Device connection
connect( id : String ): Promise\<Device>
Connect to a specific bluetooth device.
- id : String Device id or uuid.
const device = await BluetoothSerial.connect(id);disconnect( id? : String ) : Promise\
Disconnect from the specific connected bluetooth device. If id is omitted, the first connected device will be disconnected.
- id? : String Optional device id or uuid.
await BluetoothSerial.disconnect();disconnectAll() : Promise\
Disconnect all connected bluetooth devices.
await BluetoothSerial.disconnectAll();isConnected( id? : String ) : Promise\
Indicates the specific connected bluetooth device connection status. If id is omitted, it will return the connection status of the first connected device.
- id? : String Optional device id or uuid.
const isConnected = await BluetoothSerial.isConnected();Device IO
read( callback : Function, delimiter? : String, id? : String ) : void
Listen and read data from the selected or first connected device.
- callback : Function
- data : String
- subscription : EmitterSubscription
- delimiter? : String =
'' - id? : String Optional device id or uuid.
BluetoothSerial.read((data, subscription) => {
console.log(data);
if (this.imBoredNow && subscription) {
BluetoothSerial.removeSubscription(subscription);
}
}, "\r\n");readOnce( delimiter? : String, id? : String ) : Promise\
Read data from the selected or first connected device once.
- delimiter? : String =
'' - id? : String Optional device id or uuid.
const data = await BluetoothSerial.readOnce("\r\n");readEvery( callback : Function, ms? : Number, delimiter? : String, id? : String ) : void
Read data from the selected or first connected device every n ms.
- callback : Function
- data : String
- intervalId : Number
- ms?: Number =
1000 - delimiter? : String =
'' - id? : String Optional device id or uuid.
BluetoothSerial.readEvery(
(data, intervalId) => {
console.log(data);
if (this.imBoredNow && intervalId) {
clearInterval(intervalId);
}
},
5000,
"\r\n"
);readFromDevice( id? : String ) : Promise\
Read all buffer data from the selected or first connected device.
- id? : String Optional device id or uuid.
const data = await BluetoothSerial.readFromDevice();readUntilDelimiter( delimiter : String, id? : String ) : Promise\
Read all buffer data up to certain delimiter from the selected or first connected device.
- delimiter : String
- id? : String Optional device id or uuid.
const data = await BluetoothSerial.readUntilDelimiter("\r\n");write( data : Buffer | String, id? : String ) : Promise\
Write buffer or string to the selected or first connected device.
- data : Buffer | String
- id? : String Optional device id or uuid.
await BluetoothSerial.write("This is the test message");writeToDevice( data : String, id? : String ) : Promise\
Write string to the selected or first connected device.
- data : String
- id? : String Optional device id or uuid.
await BluetoothSerial.writeToDevice("This is the test message");Device buffer
clear( id? : String ) : Promise\
Clear all buffer data of the selected or first connected device.
- id? : String Optional device id or uuid.
await BluetoothSerial.clear();available( id? : String ) : Promise\
Get length of current buffer data of the selected or first connected device.
- id? : String Optional device id or uuid.
const bufferLength = await BluetoothSerial.available();withDelimiter( delimiter : String, id? : String ) : Promise\<String | null>
Set delimiter that will split the buffer data when you are reading from device.
- delimiter : String
- id? : String Optional device id or uuid.
const deviceId = await BluetoothSerial.withDelimiter("\r\n");Service declaration for iOS
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.
setServices( services : Service[], includeDefaultServices? : Boolean ) : Promise\<Service[]>
Set custom bluetooth services for filtering out the specific protocols that you need.
- For Android, this method has no effect and will return empty array.
- services : Service[]
Array of custom service object; each of them must have
service,read, andwritekey-value. - includeDefaultServices? : Boolean =
trueShould we includeBluetoothSerial.DEFAULT_SERVICESin 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);getServices() : Promise\<Service[]>
Get current services.
- For Android, this method has no effect and will return empty array.
const currentServices = await BluetoothSerial.getServices();restoreServices() : Promise\<Service[]>
Restore services and set them to default services (BluetoothSerial.DEFAULT_SERVICES.)
- For Android, this method has no effect and will return empty array.
const services = await BluetoothSerial.restoreServices();Multiple devices connection
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.
device( id? : String ) : Object
This method gives the ability to call group of API methods instead of pass id parameter at the end of each methods.
- id? : String Optional device id or uuid.
The followings are group of methods that you can use with this method.
connectdisconnectisConnectedclearavailablewithDelimiterreadreadOncereadEveryreadUntilDelimiterreadFromDevicewritewriteToDevice
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();Events
Types
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: { ... } }readordata: String of data from device. You get object of device id and data.{ id: ..., data: ... }error: Error message from native code.{ message: ... }
Methods
once( eventName : String, handler : Function ) : EmitterSubscription
on( eventName : String, handler : Function ) : EmitterSubscription
addListener( eventName : String, handler : Function ) : EmitterSubscription
off( eventName : String, handler : Function ) : void
removeListener( eventName : String, handler : Function ) : void
removeAllListeners( eventName? : String ) : void
removeSubscription( subscription : EmitterSubscription) : void
Todos
- Write base64 image.
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago