当前位置: 首页 > 软件库 > 手机/移动开发 > >

react-native-ble-manager

React Native BLE communication module
授权协议 Apache-2.0 License
开发语言 Java
所属分类 手机/移动开发
软件类型 开源软件
地区 不详
投 递 者 高自怡
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

react-native-ble-manager

This is a porting of https://github.com/don/cordova-plugin-ble-central project to React Native.

Requirements

RN 0.60+

RN 0.40-0.59 supported until 6.7.XRN 0.30-0.39 supported until 2.4.3

Supported Platforms

  • iOS 8+
  • Android (API 19+)

Install

npm i --save react-native-ble-manager
npx react-native link
Android - Update 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" />
...

In Android API 29 >= you need to use "ACCESS_FINE_LOCATION" instead of "ACCESS_COARSE_LOCATION".

If you need communication while the app is not in the foreground you need the "ACCESS_BACKGROUND_LOCATION" permission.

iOS - Update Info.plist

In iOS >= 13 you need to add the NSBluetoothAlwaysUsageDescription string key.

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.
  • Android API >= 29 require the ACCESS_FINE_LOCATION permission to scan for peripherals.React-Native 0.63.X started targeting Android API 29.
  • 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:

// 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.

Methods

start(options)

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 initialization
  • restoreIdentifierKey - String - [iOS only] Unique key to use for CoreBluetooth state restoration
  • queueIdentifierKey - String - [iOS only] Unique key to use for a queue identifier on which CoreBluetooth events will be dispatched
  • forceLegacy - Boolean - [Android only] Force to use the LegacyScanManager

Examples

BleManager.start({ showAlert: false }).then(() => {
  // Success code
  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 scanning
  • scanningOptions - JSON - [Android only] after Android 5.0, user can control specific ble scan behaviors:

Examples

BleManager.scan([], 5, true).then(() => {
  // Success code
  console.log("Scan started");
});

stopScan()

Stop the scanning.Returns a Promise object.

Examples

BleManager.stopScan().then(() => {
  // Success code
  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.

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(peripheralId, force)

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 gattconnection and send the BleManagerDisconnectPeripheralevent immediately to Javascript, else disconnects theconnection and waits for disconnected state toclose the gatt connectionand then sends the BleManagerDisconnectPeripheral to theJavascript

Examples

BleManager.disconnect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
  .then(() => {
    // Success code
    console.log("Disconnected");
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

enableBluetooth() [Android only]

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");
  });

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(() => {
    // Success code
    console.log("Notification started");
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

startNotificationUseBuffer(peripheralId, serviceUUID, characteristicUUID, buffer) [Android only]

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);
  });

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) => {
    // 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(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/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);
  });

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 size
  • queueSleepTime - 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(() => {
    // Success code
    console.log("Writed: " + data);
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

readRSSI(peripheralId)

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);
  });

requestConnectionPriority(peripheralId, connectionPriority) [Android only API 21+]

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:
    • 0 - balanced priority connection
    • 1 - high priority connection
    • 2 - low power priority connection

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);
  });

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((mtu) => {
    // Success code
    console.log("MTU size changed to " + mtu + " bytes");
  })
  .catch((error) => {
    // Failure code
    console.log(error);
  });

retrieveServices(peripheralId[, serviceUUIDs])

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);
  }
);

refreshCache(peripheralId) [Android only]

refreshes the peripheral's services and characteristics cacheReturns 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);
  });

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) => {
  // Success code
  console.log("Connected peripherals: " + peripheralsArray.length);
});

createBond(peripheralId,peripheralPin) [Android only]

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");
  });

removeBond(peripheralId) [Android only]

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");
  });

getBondedPeripherals() [Android only]

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);
});

getDiscoveredPeripherals()

Return the discovered peripherals after a scan.Returns a Promise object.

Examples

BleManager.getDiscoveredPeripherals([]).then((peripheralsArray) => {
  // Success code
  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

  • none

Examples

bleManagerEmitter.addListener("BleManagerStopScan", () => {
  // Scanning is stopped
});

BleManagerDidUpdateState

The BLE change state.

Arguments

  • state - String - the new BLE state ('on'/'off').

Examples

bleManagerEmitter.addListener("BleManagerDidUpdateState", (args) => {
  // The new state: args.state
});

BleManagerDiscoverPeripheral

The scanning find a new peripheral.

Arguments

  • id - String - the id of the peripheral
  • name - String - the name of the peripheral
  • rssi - Number - the RSSI value
  • advertising - 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
});

BleManagerDidUpdateValueForCharacteristic

A characteristic notify a new value.

Arguments

  • valueArray — the read value
  • peripheralString — the id of the peripheral
  • characteristicString — the UUID of the characteristic
  • serviceString — the UUID of the characteristic

Event 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(`Recieved ${data} for characteristic ${characteristic}`);
    }
  );
  // Actions triggereng BleManagerDidUpdateValueForCharacteristic event
}

BleManagerConnectPeripheral

A peripheral was connected.

Arguments

  • peripheral - String - the id of the peripheral
  • status - Number - [Android only] connect reasons

BleManagerDisconnectPeripheral

A peripheral was disconnected.

Arguments

  • peripheral - String - the id of the peripheral
  • status - Number - [Android only] disconnect reasons

BleManagerCentralManagerWillRestoreState [iOS only]

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

iOS Relaunch Conditions

  • 一些小问题都小记一下 react-native run-android的时候要求当前只运行一个模拟器或者连接真机,rn会自动把app打包进去并运行。可是有时候却出现设备连接正常,跑react-native run-android却报找不到设备的异常,报错信息: FAILURE: Build failed with an exception. * What went wrong: Executio

  • react-native 问题记录 1 解决react-native-swiper: cannot read property ‘x’ of undefined 2 解决React Native unable to load script from assets index.android.bundle on windows 3 android stuido 打包报错:Error: Duplica

  • 转载 https://blog.csdn.net/mapbar_front/article/details/76165239 error: bundling failed: “Unable to resolve module react from C:\\Users\\liwd\\Desktop\\mywork\\react-native\\Navigator\\index.android.js:

  • react-native零散记录 — sundashan 导航栏 react-navigation、react-native-navigation各有千秋,看自己选择 蓝牙 react-native-ble-plx react-native-ble-manager react-native-bluetooth-serial 都可以看下,我用的是react-native-ble-plx,文档比较全面

  • 组件是 React 代码复用的主要单元,但如何将一个组件封装的状态或行为共享给其他需要相同状态的组件并不是显而易见的。 ReactNative 和 React 一样可以使用函数式组件或 Class 组件。最开始只有 Class 组件能够使用 state ,函数式组件都是无状态的。并且渲染结果只与参数有关,参数相同,每次渲染结果都相同。 组件之间如果有复用的需求,有一些可复用的逻辑需要从组件中抽取出

  • 最近几个月从h5转到RN的开发,其中遇到了很多坑,因为我们做的是物联网项目,然后又刚好用到了蓝牙组件,蓝牙组件我选择的是react-native-ble-manager,目前我已经跟硬件实现了通信,所以现在想简单写写蓝牙通信以及使用这个组件的的注意事项,本人才疏学浅,博客也写的比较少,不喜勿喷。实现这个ble蓝牙通信我很多是参照https://blog.csdn.net/withings/arti

  • 此文记录本人在学习、进行 React-native 在Android端开发过程中遇到的问题,以及当时的解决方案。 1、Execution failed for task ‘:app:processDebugResources’. 在React-native run-android 运行项目命令中出现错误: Execution failed for task ‘:app:processDebugRe

  • 主要为大家大致的介绍React-Native的蓝牙对接使用与开发等经验分享        简言:最近公司需要开发一款APP,在现有资源中采取了前端使用react-native来进行一个APP的开发。 

  • 今天运行React-Native app时候遇到的一个错误: react-native:Task:react-native-gesture-handler:compileDebugJavaWithJavac Failed 原因未知,网上说是sdk问题, 解决方法:运行: npm i jetifier npx jetify    

 相关资料
  • 本文向大家介绍react-native 启动React Native Packager,包括了react-native 启动React Native Packager的使用技巧和注意事项,需要的朋友参考一下 示例 在最新版本的React Native上,无需运行打包程序。它将自动运行。 默认情况下,这将在端口8081上启动服务器。要指定服务器所在的端口            

  • 百度移动统计SDK支持使用react native框架的H5页面统计,封装好的插件已经在github上开源,相关用法具体请参考:https://github.com/BaiduMobileAnalysis/baidumobstat-react-native。

  • The React Native environment has a lot of little quirks, so this documentation is aimed at helping smooth those over. Please feel free to create issues on GitHub for recommendations and additions to t

  • React Native 可以基于目前大热的开源JavaScript库React.js来开发iOS和Android原生App。而且React Native已经用于生产环境——Facebook Groups iOS 应用就是基于它开发的。 React Native的原理是在JavaScript中用React抽象操作系统原生的UI组件,代替DOM元素来渲染,比如以<View>取代<div>,以<Ima

  • 本文向大家介绍react-native setState,包括了react-native setState的使用技巧和注意事项,需要的朋友参考一下 示例 要在应用程序中更改视图,可以使用setState-这将重新渲染您的组件及其任何子组件。setState在新状态和先前状态之间执行浅表合并,并触发组件的重新呈现。 setState 接受键值对象或返回键值对象的函数 键值对象 功能 使用函数对于基于

  • 诸葛io移动统计支持React Native插件,以下为集成方法。 1. 环境准备 1.1. iOS环境 iOS 8.0+ 代码支持iOS8.0的系统 pod 1.0+ iOS系统的集成依赖于cocoaPod工具 1.2. Android环境 Android SDK 16+ 代码支持Android 16+ 1.3. React Native环境 react-native 0.50+ react-n