Giter Site home page Giter Site logo

dotintent / react-native-ble-plx Goto Github PK

View Code? Open in Web Editor NEW
3.0K 69.0 496.0 8.55 MB

React Native BLE library

License: Apache License 2.0

Java 12.29% JavaScript 11.60% Objective-C 4.09% C 0.01% Ruby 0.29% Shell 0.26% Objective-C++ 0.05% Swift 65.02% TypeScript 6.22% Kotlin 0.16%

react-native-ble-plx's Introduction

react-native-ble-plx library logo

About this library

It supports:

It does NOT support:

  • bluetooth classic devices.
  • communicating between phones using BLE (Peripheral support)
  • bonding peripherals

Table of Contents

  1. Compatibility
  2. Recent Changes
  3. Documentation & Support
  4. Configuration & Installation
  5. Troubleshooting
  6. Contributions

Compatibility

For old RN versions (<0.60) please check old README (1.x) for the old instructions or migration guide.

React Native 3.1.2
0.74.1
0.69.6
Expo 51

Recent Changes

3.2.0

  • Added Android Instance checking before calling its method, an error will be visible on the RN side
  • Added information related to Android 14 to the documentation.
  • Changed destroyClient, cancelTransaction, setLogLevel, startDeviceScan, stopDeviceScan calls to promises to allow error reporting if it occurs.
  • Fixed one of the functions calls that clean up the BLE instance after it is destroyed.

Current version changes All previous changes

Documentation & Support

Interested in React Native project involving Bluetooth Low Energy? We can help you!

Documentation can be found here.

Quick introduction can be found here

Contact us at intent.

Configuration & Installation

Expo SDK 43+

Tested against Expo SDK 49 This package cannot be used in the "Expo Go" app because it requires custom native code. First install the package with yarn, npm, or npx expo install.

After installing this npm package, add the config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "plugins": ["react-native-ble-plx"]
  }
}

Then you should build the version using native modules (e.g. with npx expo prebuild command). And install it directly into your device with npx expo run:android.

You can find more details in the "Adding custom native code" guide.

API

The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild) the native app. If no extra properties are added, defaults will be used.

  • isBackgroundEnabled (boolean): Enable background BLE support on Android. Adds <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> to the AndroidManifest.xml. Default false.
  • neverForLocation (boolean): Set to true only if you can strongly assert that your app never derives physical location from Bluetooth scan results. The location permission will be still required on older Android devices. Note, that some BLE beacons are filtered from the scan results. Android SDK 31+. Default false. WARNING: This parameter is experimental and BLE might not work. Make sure to test before releasing to production.
  • modes (string[]): Adds iOS UIBackgroundModes to the Info.plist. Options are: peripheral, and central. Defaults to undefined.
  • bluetoothAlwaysPermission (string | false): Sets the iOS NSBluetoothAlwaysUsageDescription permission message to the Info.plist. Setting false will skip adding the permission. Defaults to Allow $(PRODUCT_NAME) to connect to bluetooth devices.

Expo SDK 48 supports iOS 13+ which means NSBluetoothPeripheralUsageDescription is fully deprecated. It is no longer setup in @config-plugins/[email protected] and greater.

Example

{
  "expo": {
    "plugins": [
      [
        "react-native-ble-plx",
        {
          "isBackgroundEnabled": true,
          "modes": ["peripheral", "central"],
          "bluetoothAlwaysPermission": "Allow $(PRODUCT_NAME) to connect to bluetooth devices"
        }
      ]
    ]
  }
}

Legacy Expo (SDK < 43)

  1. Make sure your Expo project is ejected (formerly: detached). You can read how to do it here. (only for Expo SDK < 43)
  2. Follow steps for iOS/Android.
  1. npm install --save react-native-ble-plx
  2. Enter ios folder and run pod update
  3. Add NSBluetoothAlwaysUsageDescription in info.plist file. (it is a requirement since iOS 13)
  4. If you want to support background mode:
    • In your application target go to Capabilities tab and enable Uses Bluetooth LE Accessories in Background Modes section.
    • Pass restoreStateIdentifier and restoreStateFunction to BleManager constructor.

Android (example setup)

  1. npm install --save react-native-ble-plx

  2. In top level build.gradle make sure that min SDK version is at least 23:

    buildscript {
        ext {
            ...
            minSdkVersion = 23
            ...
  3. In build.gradle make sure to add jitpack repository to known repositories:

    allprojects {
        repositories {
          ...
          maven { url 'https://www.jitpack.io' }
        }
    }
  4. In AndroidManifest.xml, add Bluetooth permissions and update <uses-sdk/>:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
       ...
    
       <!-- Android >= 12 -->
       <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
       <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
       <!-- Android < 12 -->
       <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
       <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
       <!-- common -->
       <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
       <!-- Add this line if your application always requires BLE. More info can be found on:
           https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#permissions
         -->
       <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
    
        ...
  5. (Optional) In SDK 31+ You can remove ACCESS_FINE_LOCATION (or mark it as android:maxSdkVersion="30" ) from AndroidManifest.xml and add neverForLocation flag into BLUETOOTH_SCAN permissions which says that you will not use location based on scanning eg:

     <uses-permission android:name="android.permission.INTERNET" />
     <!-- Android >= 12 -->
     <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
     <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
     <!-- Android < 12 -->
     <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_FINE_LOCATION" android:maxSdkVersion="30" />
    
        ...

    With neverForLocation flag active, you no longer need to ask for ACCESS_FINE_LOCATION in your app

Troubleshooting

Contributions

  • Special thanks to @EvanBacon for supporting the expo config plugin.

react-native-ble-plx's People

Contributors

barbiero avatar bartoszwilk avatar bitcrumb avatar bor-ski avatar cierpliwy avatar dariuszseweryn avatar dimninik avatar dominik-czupryna-withintent avatar gmiszewski-intent avatar intent-kacper-cyranowski avatar kacper-cyra avatar kamilnatonek avatar konradrodzik avatar literator avatar lukerayman avatar mciechanowicz avatar mikolak avatar mutablestudio avatar pandabearcoder avatar patlux avatar piotrdubiel avatar pjpsoares avatar pouljohn1 avatar radko93 avatar rnigro-rwb avatar shabith avatar shumih avatar stinodes avatar wouterh-dev avatar wung-s avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-ble-plx's Issues

Module 'BleClientManager' not found

I get this error while trying to build your example in Xcode: /examples/ReactBLEScanner/node_modules/react-native-ble-plx/ios/BleClient.m:10:9: fatal error: module 'BleClientManager' not found

Monitoring characteristic on multiple devices

I am trying to monitor a characteristic on multiple devices. I call something like:

remove_functions{device_uuid+':'+char_uuid} = ble.monitorCharacteristicForDevice(device_uuid, service_uuid, char_uuid,
        (error, characteristic) => {
            if (error) {
                console.log('ERROR ', error);
            }
            else {
                const value = new Buffer(characteristic.value, 'base64').toString('utf8');
                console.log('listener called', value)
            }
        }
    );

I call this twice, once for each device. The call is successful, no errors, and I can see the "remove" functions in the remove_functions object.

When a characteristic changes on one device, the monitoring works great - I can see the changes on the console, as events are properly emitted. However, when I change the characteristics on the other device, the listener is never invoked.

I am able to read a characteristics on multiple devices, and I am able to monitor several characteristics on the same device (I've tested that, and it works great) but I can't seem to monitor multiple devices.

Any help or suggestions where to look would be greatly appreciated. I did a cursory look at the javascript library, and nothing jumped out at me.

Thanks again for this library - it's been a big help!

Cheers,
L3

ADDENDUM - which device works is sort of random, and appears to be determined by which listener is created first. IOW, if device 1 creates the listener for characteristic A before device 2 creates a listener for characteristic A, then the monitoring works on device 1 and does not work on device 2. Which device goes first is really a function in my code of which one pops up first when I start scanning. FWIW.

Command /bin/sh failed with exit code 1

Unrecognized arguments: "/Users/willdent/Library/Developer/Xcode/DerivedData/ble-ausclppugcjrecboiwdlaycdoyfq/Build/Intermediates/ble.build/Debug-iphoneos/ble.build/Script-5D4CFAB11E7BFAE5005783F4.sh"
Command /bin/sh failed with exit code 1

Running this on:
Version 8.2.1 (8C1002)

Build Failure with iOS

So I followed the tutorials for setting up both on iOS and Android.

Now that I've done that, iOS fails building each time with this error in Xcode:

Check dependencies Argument list too long: recursive header expansion failed at /Users/nealogrady/Dropbox/Sites/Sites/Bloom Dental/BloomDental/ios/../node_modules/react-native-ble-plx/android/build/tmp/expandedArchives/internal_impl-23.1.1.jar_7m76px62sfm8yakpu97l6umuv/android/support/v4/graphics.

When run through the terminal with react-native run-ios, it fails, takes forever but does eventually launch:

Check dependencies Argument list too long: recursive header expansion failed at /Users/nealogrady/Dropbox/Sites/Sites/Bloom Dental/BloomDental/ios/../node_modules/react-native-ble-plx/android/build/tmp/expandedArchives/internal_impl-23.1.1.jar_7m76px62sfm8yakpu97l6umuv/android/support/v4/graphics.

** BUILD FAILED **

The following build commands failed:
Check dependencies
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/BloomDental.app
Launching org.reactjs.native.example.BloomDental`

In Xcode, however, it will not build at all.

Unable to install module via npm install on Windows and Ubuntu

Hi,

I'm trying to add your library to my React Native application by following your guide on both Linux and Windows, to which I run into the same problem when npm install tries to run ./build_ios_frameworks.sh

I have attached the stack trace

Ubuntu
`╰─$ npm install

[email protected] install /mnt/f/Development/WetnessApp/node_modules/react-native-ble-plx
./build_ios_frameworks.sh

./build_ios_frameworks.sh: line 4: carthage: command not found
./build_ios_frameworks.sh: line 5: carthage: command not found
npm ERR! Linux 3.4.0+
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install"
npm ERR! node v6.4.0
npm ERR! npm v3.10.3
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn

npm ERR! [email protected] install: ./build_ios_frameworks.sh
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the [email protected] install script './build_ios_frameworks.sh'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the react-native-ble-plx package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! ./build_ios_frameworks.sh`

Windows

`$ npm install

[email protected] install F:\Development\WetnessApp\node_modules\react-native-ble-plx
./build_ios_frameworks.sh

'.' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install"
npm ERR! node v6.4.0
npm ERR! npm v3.10.3
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: ./build_ios_frameworks.sh
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script './build_ios_frameworks.sh'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the react-native-ble-plx package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! ./build_ios_frameworks.sh`

Support latest versions of backend libraries

  • Make sure to update RxBluetoothKit and RxAndroidBle to latest stable versions before release
  • Make sure to all required features are implemented such as fetching global BLE state.

new BleManager() failed on componentWillMount

In my own component below, I try to play with the ble but get some error:

undefined is not an object (evaluating 'BleModule.createClient')

Looks like in BleManager.js, it can not import BleModule. Any idea?

import { BleManager } from 'react-native-ble-plx';

export default class Discover extends Component {

	constructor(props) {
	  super(props);
	
	  this.state = {
	  	device: { id: '', name: '' },
	  	scanning: false
	  };
	}
	componentWillMount() {
	    this.manager = new BleManager();
	    this.subscriptions = {}
	    this.manager.onStateChange((newState) => {
	      console.log("State changed: " + newState)
	    });
	}
	componentDidUpdate(prevProps, prevState) {
		if (this.state.scanning) {
			this.manager.startDeviceScan(null, null, (error, device) => {
				if (!error) {
					console.log("Found device: ", device);
					this.setState({
						device,
						scanning: false
					})
				}
			});
		}
	  
	}
	componentWillUnmount() {
	    this.manager.destroy();
	    delete this.manager;
  	}
	render() {
		const { device } = this.state;
		return (
			<View style={{ flex: 1, justifyContent: 'center' }}>
				<Text>
				  {device.id} -- {device.name}
				</Text>
				<ButtonView
					onClick={this._startScan.bind(this)}
					text={'Start scanning'}
					color={'#beffc6'}/>
          
			</View>
		);
	}
	_startScan() {
		this.setState({ scanning: true });
	}
};

is it possible to put the device running the application in advertise mode?

i am creating a android application in react native. in this application i have to put the device in advertise mode, so other nearby devices (over bluetooth) can identify it and subscribe to it. i am seeing examples where we can listen to advertised devices and get its characteristics using plx, is it possible to advertise from my app?

Device.id is undefined v0.4.0

While i scan with filtering by service uuid, scanned device id property is undefined. It was working great with v0.3.3

BleScanner example not working

Hi,
New to react-native, trying to get example working:
Had to make changes to versions of highlighted packages
to get example to run:

"react": "15.4.1",
"react-addons-pure-render-mixin": "15.4.1",
"react-native": "0.38.0",

"redux": "3.5.2",
"react-redux": "4.4.5",
"redux-logger": "2.6.1",
"react-native-router-flux": "3.32.0",
"immutable": "3.8.1",
"redux-immutable": "3.0.6",
"react-immutable-proptypes": "2.0.0",
"react-native-button": "1.6.0",
"react-native-android-permissions": "0.0.6",
"buffer": "4.7.1",
"react-native-ble-plx": "Polidea/react-native-ble-plx"

originally had problem with:
error: Strict mode does not allow function declarations in a lexically nested statement on a newly created app

Now get:

"Warning: Failed prop type: The prop 'uuid' is marked as required in 'ScannedDeviceView', but its value is NULL"

Is there an updated version of example which works out of the box?

Additionally noticed article:

https://www.polidea.com/blog/ReactNative_and_Bluetooth_to_An_Other_level/

Is code for this exampel available on github?

Are there any other examples on github or similar which would give me some
working exampels to look at?

Thanks for any help you can provide!

BR
Paul

Consider API breaking changes.

Consider following API breaking changes before going 1.0:

  • Move all advertisement data related fields (including name and rssi) to advertisement object which will be included in Device if possible.
  • Change (error, T) => void callback types to (Result<T>) => void which will allow to apply better Flow type checking.
  • Change Device.uuid to Device.id as it's not UUID
  • Convert iOS library to Swift 3
  • Consider filtering out value updates from notification listener when read is performed on iOS. In that case behaviour will be in line with Android.
  • Change Base64 API to ArrayBuffer and do conversion on implementation side. This will allow to optimize it in further RN versions on iOS10+.

device.cancelConnection bug (and fix)

First, thanks so much for this VERY helpful module. I'm just getting into it, but it's well engineered from what I see so far. Keep up the great work!

I ran across a bug when using the device.cancelConnection() helper function. I kept getting an error "options - Variable not found" or some such. I went into your code, and found this statement (lines 14-16 of src/Device.js):

this.cancelConnection = () => { return manager.cancelDeviceConnection(this.uuid, options) }

This looks like a copy-paste of the device.connect() helper function above. I changed these lines to:

this.cancelConnection = () => { return manager.cancelDeviceConnection(this.uuid) }

and the problem went away. Just thought you'd want to know. Again, thanks, and all the best. Cheers,
L3

[iOS] Bug with discoverAllServicesAndCharacteristics

I am implementing a simple component that scans and connects to a BLE device. The device I am trying to connect to is BLE test board. Here is the code I am using:

this.bleManager.connectToDevice(device.uuid)
      .then((device) => {
        console.log("DISCOVERING");
        return device.discoverAllServicesAndCharacteristics();
      })
      .then((device) => {
        console.log("DISCOVERED");
        this.setState({
          connectedGogglesId: device.uuid,
          connectedGoggles: device
        });
      })
      .then(() => {
        console.log("SUCCESS");
      }, (error) => {
        console.log(error);
      });

On Android, everything works fine, all services and characteristics are discovered and the "SUCCESS" message is printed. One iOS, however, the connection is successful, I see the bluetooth icon flash and turn white, it prints the "DISCOVERING" log message, but it just hangs on the discoverAllServicesAndCharacteristics call and never completes the discovery.

I'm using react-native 0.37 and the master branch of react-native-ble-plx. Any help or ideas at what might be causing this is GREATLY appreciated. Thanks!

Not able to bundle js

MINGW64 ~/Downloads/ReactBLEScanner $ react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/ Unable to parse cache file. Will clear and continue. [3:18:37 PM] Building Dependency Graph [3:18:37 PM] Crawling File System [3:18:37 PM] find dependencies [3:18:48 PM] Crawling File System (10967ms) [3:18:48 PM] Building in-memory fs for JavaScript [3:18:48 PM] Building in-memory fs for JavaScript (251ms) [3:18:48 PM] Building in-memory fs for Assets [3:18:48 PM] Building in-memory fs for Assets (188ms) [3:18:48 PM] Building Haste Map [3:18:49 PM] Building (deprecated) Asset Map [3:18:49 PM] Building (deprecated) Asset Map (89ms) [3:18:49 PM] Building Haste Map (385ms) [3:18:49 PM] Building Dependency Graph (11798ms) [3:19:06 PM] find dependencies (28496ms) bundle: start bundle: finish bundle: Writing bundle output to: android/app/src/main/assets/index.android.bundle C:\Users\schava\Downloads\ReactBLEScanner\node_modules\promise\lib\done.js:10 throw err; ^

Problem to reconnect after manager.destroy()

I am using manager.destroy() when my app goes into background. I disconnect from the connected devices first.
When I go back to the app and do a new scan, I cannot find the device.
I use new BleManager() to create new manager after the app comes back.
Am I doing it wrong?

Listener string return value truncated

Another possible bug:

I have a 24-byte UUID that I store in a characteristic. I setup a listener to monitor for changes in that value using the monitorCharacteristicForDevice function. I also read that characteristic value directly from time to time using the readCharacteristicForDevice function.

When I read the value directly and convert from Base64 to utf8, I get all 24 bytes.
When I get the value initially from the listener and convert, I get all 24 bytes.
However, in subsequent calls from the listener, I only get 20 bytes.

Here is some example output:

When reading directly:

Base64: MEQ0OUFEOUYxNDc4MTMyNjY1NTQwNTk5
utf8: 0D49AD9F1478132665540599

Initial response from listener:

Base64: MEQ0OUFEOUYxNDc4MTMyNjY1NTQwNTk5
utf8: 0D49AD9F1478132665540599

Subsequent responses from listener:

Base64: MEQ0OUFEOUYxNDc4MTMyNjY1NTQ=
utf8: 0D49AD9F147813266554

This one has me stumped. Any ideas?

One more thing I've noticed that may or may not be relevant: when setting up a listener on a characteristic, it does not get called initially (which is probably correct behavior). However, when I read the characteristic after setting up the listener, the listener gets called. Now this is not really expected behavior to me; seems like a call to read a characteristic that is Read+Notify should not trigger a listener event. As it is, when I set up a listener and do a read to get the initial state, I get two identical results - one from the read, and one from the listener. (This is what I meant above as the "initial response from listener").

Thanks in advance! Cheers,

L3

Bluetooth is not supported

Hi,

I'm on the latest macOs 10.12 (on a 2015 MacBook Pro), with an updated Xcode. When I run the provided example in Xcode, the app seams to start just fine, but when I click on the Start scanning button I get an error message Bluetooth is not supported.

What causes this error? Am I missing something here?
Or is it because Apple dropped CoreBluetooth in the simulator?

Thanks!

[Android]: Unable to create paired connection

Hello,

I am using this library to connect a React Native app to a BLE device that requires an authenticated/paired connection. My code is very simple and works fine in iOS—I receive a system alert upon connection that the device is requesting to pair. However, the Android version does not work. The connection and service discovery steps work, but as soon as a call writeCharacteristicWithResponseForService I receive the following error:

{ [Error: BleGattException{status=14, bleGattOperation=BleGattOperation{description='CHARACTERISTIC_WRITE'}}]
framesToPop: 1,
code: '700',
line: 25627,
column: 21,
sourceURL: 'http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false' }

Here is my code:

this.bleManager.connectToDevice(device.uuid)
      .then((device) => {
        console.log("DISCOVERING");
        return device.discoverAllServicesAndCharacteristics();
      })
      .then((device) => {
        console.log("DISCOVERED");
        let array = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0,1, 1, 1]);
        let data = base64.fromByteArray(Buffer.from(array.buffer));
        return device.writeCharacteristicWithResponseForService('181C', '34FB', data)
        .catch((response) => {
            console.log(response);
          });
      });

Like I said, it's all working fine in iOS, but not Android. Any help is greatly appreciated!

Android: bleglattexception 133 & Chrome Debugger

I have been working with your library for the past couple of weeks now, and it works great. Although sometimes (seemingly inexplicable), I consistently get bleglattexception 133 on my Android device (HTC M9 running Android 6.0.0).

Answers on other issues mentioned using timeouts in between various connects / calls, which did not change anything in my particular case.


After not being able to pinpoint the issue and just letting it be for now, I have found out that this occurs when I am using Chrome as debugger.

The solutions proposed in other issues did not help in my case (at least the ones I could apply without editing dependencies).

I do not know whether that is something that can be fixed, but I thought sharing my findings would still be worthwhile for anyone else experiencing similar issues.

Discovering smartphones/tablets

Is it possible to discover other smartphones or tablets running the same app (in the background) with this library? Does it support advertising?

undefined is not an object (evaluating 'BleModule.createClient')

When I try to create a new instance of BleManager I get the error from the title.

The problem seems to stem from here in the code; For some reason BleModule is undefined.

I import the module like this:

import BleManager from 'react-native-ble-plx/src/BleManager.js';

and then in my app component's constructor it fails on this:

this.blem = new BleManager();

Any idea what I'm doing wrong?

Question: Background monitoring?

Hi!

Is it possible to monitor characteristics when the app is in background or sleeping?

Currently, without any additional setup, the app just does nothing when phone screen turned off. Monitoring (or receiving the values) continues after the app is opened again. (tested only on iOS)

Have you considered adding some kind of buffer to native code so that app could keep receiving data from the BLE device while screen is turned off? The buffer data would then be accessible from JavaScript.

Thanks for the great library!

Unified error format

Make sure that error format is unified between platforms.

  • All error codes on Android and iOS should have the same value for the same kind of issues
  • {Optionally} Add another field in error type which allows to see a backend specific error for development purposes
  • Consider changing behaviour of "Cancelled" error type.
  • Add reason of disconnection as an error in disconnect function.

Characteristic monitoring causes delayed execution of fetch and other Promises

I am using the library to monitor a BLE device for data, and after some amount is accumulated I upload it to a REST service.
It mostly works well in the device discovery, connection and writing data. However, there is an issue with the response received from the monitored characteristic.
I am not sure how to describe it well, but essentially any fetch calls or other Promises don't get resolved properly. The .then() or .catch() clauses after the fetch are called with a delay only after the BLE device disconnects. In most cases the fetch finishes with a 'Network request failed' error.

Here is some sample code to make it more clear:
I set up a monitor with:

    const subscription = bleManager.monitorCharacteristicForDevice(deviceId,
      'some_specification', 'some_characteristic', handleResponse, null);

The handleResponse function dispatches an async action using redux-thunk, which calls fetch to upload the REST data.

function handleResponse(error, characteristic) {
  // The action below contains a simple fetch().then() call. It is dispatched with 'redux-thunk'. However
  // in most cases the .then() executed with a very large delay, or the whole fetch ends with an error,
  // again after a delay 
  store.dispatch(uploadAction(somedata));

  // A direct call to fetch here behaves like the action above
  fetch('https://www....')
    .then((response) => { ... })
    .catch((err) => { ... });
}

Seems that any promises called directly or through actions from the handleResponse get resolved only after the BLE device is disconnected. If I disconnect it explicitly after sending the action, it all works well.
The same actions or fetch calls elsewhere in the app work properly, so I suppose this is some interaction with the BLE library that is causing the issue.

I would be grateful for any ideas how to solve that.

[2.0] Add automated tests

Consider creating a project which will simulate real world scenarios to test current APIs

  • Create test application in server role
  • Create test application in client role
  • Add scenarios/tests which covers current API

Support Flow

Add type support by using Flow, which is de facto a standard in React Native project.

  • Add Flow annotations to every item

[2.0] Allow to write to and read from descriptor

Implement following operations related to descriptors:

  • Discover descriptors for characteristics
  • Read descriptor value
  • Write descriptor value
  • Note in documentation that these operations cannot be used on Client Characteristic Configuration descriptor (on iOS) or implement a workaround.
  • Add constants for predefined descriptor UUIDs

Pre-packaged frameworks

Installing this lib with npm install currently takes quite a bit of time, which will significantly increase the time taken to build/test projects with this lib as a dependency in CI processes where package caching isn't implemented.

Would it be possible to pre-package the frameworks used by this lib to speed up the installation?

Connect Promise Hangs

I'm just getting started with this package and BLE. I have the following code block:

return manager.startDeviceScan(null, null, (error, device) => {
  if (device.name === LMU_NAME) {
    return device.isConnected().then(isConnected => {
      if (!isConnected) {
        return device.connect().then(response => {
          console.log(response);
        }).catch(err => {
          console.log(err);
        });
      }
    });
  }
});

A few seconds after connect is called, the phone prompts me to accept pairing, and I tap OK. Neither then nor catch is ever called.

Am I doing something wrong, or it's a bug?

issues installing

tall"
npm ERR! node v7.0.0
npm ERR! npm v3.10.8
npm ERR! code ELIFECYCLE

npm ERR! [email protected] postinstall: bash build_ios_frameworks.sh
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script 'bash build_ios_frameworks.sh'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the react-native-ble-plx package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! bash build_ios_frameworks.sh
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs react-native-ble-plx
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls react-native-ble-plx
npm ERR! There is likely additional logging output above.

Runtime error

TypeError undefined is not a function (evaluating '(bridgeConfig.remoteModuleConfig||[]).forEach')

Not able to read characteristics on iOS device

I'm trying with this library with a very simple example. A button handler creates a BleManager object, and tries to connect to a device with a specified name, then tires to read a characteristic with a specified UUID.

It works on Android device.

But on iOS device, it's able to scan and connect to the device, but not able to read any characteristics, in Chrome console, it shows the returned characteristics array is empty.

Can´t read from every characteristic

Hey there, i am trying to read some characteristics from my BLE-Module -> RN4020 which controls a chip over UART.

Now your module works great until i try to read some specific characteristics....

error code: 700
"BleGattException{status=2, bleGattOperation=BleGattOperation{description='CHARACTERISTIC_READ'}}"

and sometimes

error code: 600
"BleGattCannotStartException{status=-1, bleGattOperation=BleGattOperation{description='CHARACTERISTIC_READ'}}"

Any ideas on this?

And a general question, is it possible to just send something to the connected ble device? Something like write(identifier, "P0") for example or does it have to be written to an characteristic?

Good work though :P

does it support rnpm

when do you support rnpm scripting so that people dont have to do all the manual installations..

Sending/Receiving

How does one send/receive data between two devices? What functions to access??

Android setup information doesn't include importing BlePackage

Was following the directions for setting up for Android and for adding new BlePackage() into the MainApplication.java file, I get an error of "cannot resolve symbol 'BlePackage.' I tried copying the import from the example "import com.polidea.reactnativeble.BlePackage;" but that doesn't work either.

Android state

I have created a very simple Android App to test the new state functions. I believe I have followed all the steps to modify the Android code to build the correct libraries and set the correct permissions, but I get no state changes back. If I try to manually read the manager state I get a strange object back, not a string. I must be doing something stupid, but I can't spot it and I can't see an easy way of debugging it.

Attached below is simple index.android.js that for me does nothing.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import { BleManager } from 'react-native-ble-plx';

export default class BLE extends Component {

  constructor(props) {
      super(props);
      this.manager = new BleManager();
  }

  componentWillMount() {
     this.manager.onStateChange((newState) => {
          console.log("State changed: " + newState);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('BLE', () => BLE);

Question - Motivation behind this library

Hi,

I am a big fan of your work on providing reactive extensions for BLE i.e. RxAndroidBLE & RxBluetoothKit and wondering what was the motivation to build the react native plugin/part that wraps the Rx libraries and end up exposing the Promise interface to javascript.

There exists https://github.com/innoveit/react-native-ble-manager that achieves the same objective of exposing the BLE stack so am wondering since it is not the javascript observable interface that is exposed here what is the reason/motivation to create this library.

Regards & thanks
Kapil

macOS

Hi,
since this library works on iOS and the macOS Bluetooth framework should be the same (afaik), would it be possible to use this library together with react native for mac (1)

#Thanks!

  1. https://github.com/ptmt/react-native-macos

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.