Git Product home page Git Product logo

react-native-ble-manager's Introduction

react-native-ble-manager

npm version npm downloads GitHub issues

A React Native Bluetooth Low Energy library.

Originally inspired by https://github.com/don/cordova-plugin-ble-central.

Introduction

The library is a simple connection with the OS APIs, the BLE stack should be standard but often has different behaviors based on the device used, the operating system and the BLE chip it connects to. Before opening an issue verify that the problem is really the library.

Requirements

RN 0.60+

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

Supported Platforms

  • iOS 10+
  • Android (API 19+)

Install

npm i --save react-native-ble-manager

The library support the react native autolink feature.

Documentation

Read here the full documentation

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!
/* 
Note: The react-native-ble-manager/example directory is only included when cloning the repo, the above import will not work 
if trying to import react-native-ble-manager/example from node_modules
*/
AppRegistry.registerComponent("MyAwesomeApp", () => App);

Or, use the example directly

Library development

  • the library is written in typescript and needs to be built before being used for publication or local development, using the provided npm scripts in package.json.
  • the local example project is configured to work with the locally built version of the library. To be able to run it, you need to build at least once the library so that its outputs listed as entrypoint in package.json (in the dist folder) are properly generated for consumption by the example project:

from the root folder:

npm install
npm run build

if you are modifying the typescript files of the library (in src/) on the fly, you can run npm run watch instead. If you are modifying files from the native counterparts, you'll need to rebuild the whole app for your target environnement (npm run android/ios).

react-native-ble-manager's People

Contributors

amit-beehero avatar anees17861 avatar anwarhamr avatar bazsy01 avatar chrischares avatar ciand7 avatar danijelbojcic avatar dbarth avatar delgerdalai avatar dependabot[bot] avatar dryna avatar eleroy avatar gaishimo avatar glenne avatar joshreeves avatar kobbok avatar lucaswitch avatar marcosinigaglia avatar marvedog avatar me-shaon avatar niclas-jetset avatar nikhilgupta240 avatar quatrix avatar rmannn avatar thomasttvo avatar trafritcr avatar uniphix avatar vikeri avatar volcore avatar whitedogg13 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

react-native-ble-manager's Issues

Android Integration Issues

I have been unable to get the module working in a demo android app.

Can you confirm

  1. The current module stands compatible with the latest versions of react and react-native (
    e.g. on close inspection in the latest version of react-native to call NativeModules one has to use
    import { NativeModules } from 'react-native'; ) ??

The following is a simple code written in index.android.js but BleManager always returns undefined..

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

class bluetooth extends Component {

componentWillMount () {
//BleManager returns undefined//
console.log(BleManager.checkState())
}

render() {
return (


Welcome to React Native!


);
}
}

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

AppRegistry.registerComponent('bluetooth', () => bluetooth);
`

I have followed all the steps of adding code in
1 . app/build.gradle
2. android/settings.gradle
3. MainApplication

But The BleManager always returns undefined...

NativeAppEventEmitter is wrong

AwersomeProjeect, one question,
NativeAppEventEmitter should be DeviceEventEmitter according to the docs of react-native;

The connect success callback is never called if the peripheral has no service

I encounter a issue, when my ble device has no service, the connect success callback is never called after I call:

BLEManager.connect(peripheralId)
.then(() => {
  // the code here is never called
})

After research the code, I find that after connected the peripheral, connect callback is not called, but discoverServices method and discoverCharacteristics:forService: is called immediately.
I think this is not a best practice and it is better to split discoverServices from connect.

Example lacking instructions

Hi,

The example in the readme doesn't show how to import/require the ble-manager.

I tried

var BleManager = require('react-native-ble-manager');

and

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

but both result in an undefined BleManager.

Where can i obtain the characteristicUUID?

Hey there. I am tryinig to read and write to a bluetooth module. I have problems to understand how this works obviously, but maybe someone could help me with this... Discovering and connecting to the Bluetooth MOdule works great and wasn´t that hard, but now i would like to read data from the module. Where do i find the characteristicUUID which is needed to read from module?

This is what i receive from the module out of discovery:

screen shot 2016-10-10 at 15 11 06

How to read output from bluetooth device?

It seems this is (and all the other similar projects I've come across) are simply bluetooth managers IE. you can disconnect and connect to devices from within in app which seems rather odd since the OS can typically handle that on its own. Perhaps I'm not understanding the documentation correctly but how can I do something like this..

bluetoothHeartMonitor.listenForInput(input) {
 this.setState{
    pulse: input;
  }
}

render() {
  <text>{this.state.pulse}</text>
}

Where input is the value that came from the bluetooth device. Any help is much appreciated, thanks.

Anaren Atmosphere

Hi there,
I use react-native-ble-manager with android. Does this module can be used for connection to the anaren atmosphere device?

problem in introduction

use as follow when use in android
protected List getPackages() {
return Arrays.asList(
new MainReactPackage(),
new BleManagerPackage(this)
);
}

BleManager is undefined

I have performed the initial set up steps within Xcode.

I also added the line import { BleManager } from 'react-native-ble-manager';
but when I try to console.log(BleManager), it says undefined.

Any idea?

write

Hello, I need to write a byte 01 in characteristic, but can not,
You could put me an example.
Thank you!!

Disconnect to device before app shuts down

Hi! Is there any way to disconnect to a device when the app shuts down? Since we don't want any leaking open connections. How do you other guys deal with it? I have tried to put the the disconnection request in the componentWillUnmount function but it doesn't work.
Thanks.

write's serviceUUID can be acquired from?

write(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize)

when call method:
BleManager.connect(data.id) .then((peripheralInfo) => { console.log('connected'); console.log('peripheralInfo:', peripheralInfo); })
result peripheralInfo like:
{ "services": [{"uuid": "1800"}], "characteristics": [{"service": "1800", "characteristic": "2a00", "properties": {"Read": "Read"}}] }
what's the meaning of the result peripheralInfo?
how to use it?
hope to have some examples with more detail.

get Could not find peripheral XXXX error when connect a peripheral

react-native-ble-manager version: 2.0.0, same in 1.4.0

like #60 , when I connect a peripheral by id that getting from getConnectedPeripherals, I got error

Could not find peripheral XXXX

I check the code and find that it checks if the id is in the discovered peripherals before connecting to it, but in my scenario, the scan operation is skipped if I find the peripheral in the connected peripherals.

As apple recommend at https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForInteractingWithARemotePeripheralDevice/BestPracticesForInteractingWithARemotePeripheralDevice.html#//apple_ref/doc/uid/TP40013257-CH6-SW9

when reconnecting a peripheral, it is better to get connected peripherals to check if the peripheral is connected before scan.

Permission on Android API >= 23

For scanning ble peripherals on Android 6.x the apps need ACCESS_COARSE_LOCATION permission. RN 0.33 added a library for requesting Android M Permissions, for now is better use an external library like react-native-android-permissions .

Android writeWithoutResponse callback error

I get this error for Android writeWithoutResponse.

The callback writeWithoutResponse() exists in module BleManager, but only one callback may be registered to a function in a native module.

The problem seems to be that successCallback is invoked twice within writeWithoutResponse. Once in here and again here

Example of startNotification / stopNotification?

I am unable to get startNotification / stopNotification working. My peripheral is a RPI3 running Node JS Bleno. The characteristic works with the subscribe, read, and write operations using the nRF Connect application on Android. I can get the read and write operations to work calling them individually. All operations fail after the application calls startNotification. Does anyone have a good example of startNotification working?

Checking connection state?

Love this library, but is there no way to check the connection status of a peripheral? Without that capability it is difficult to manage the connection state between the app and the pairing of devices in iOS system settings. Thanks in advance.

Bluetooth connection examples

Could you post some more examples on how to connect to a device?

I tried using the examples from the README.md to connect my iphone to my mac using the UUID and MAC address, but none of them worked.

Thanks!

hi i'm keeping getting error ' The callback write() exists in module BleManager, but only one callback may be registered to a function in a native module.'

I want to scan some my bluetooth module and connect to it. after i connected to it, i want to write data to specific characteristic UUID. but i've kept getting error

The callback write() exists in module BleManager, but only one callback may be registered to a function in a native module.

my whole code is below

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
Image,
ActivityIndicator,
TouchableHighlight,
NativeAppEventEmitter
} from 'react-native';

var Button = require('../common/button');
var BleManager=require('react-native-ble-manager');
var base64 = require('base64-js');

var b_list;
var dev;
var sub;

module.exports = React.createClass({
getInitialState: function(){
return {
username: '',
password: '',
animating: true,
service: 'ddsjdsljslks',
};
},

render: function(){
return (
<View style={ styles.container2 }>
<View style={ styles.p1 }>
Sign Out
<TouchableHighlight onPress = { this.btnPress }>
Bluetooth test

{this.state.service}

      <TouchableHighlight
        style={styles.button}
        underlayColor={'gray'}
        onPress={this.onSkipPress}
        >
        <Text style={styles.t3}>Skip</Text>
      </TouchableHighlight>

    </View>

    <View style={styles.p2}>
      <Image
        style={styles.img1}
        source={{uri: 'https://d30y9cdsu7xlg0.cloudfront.net/png/37728-200.png'}
      }/>

      <View style={styles.p2_row}>
        <ActivityIndicator animating={this.state.animating} color="black" style={ {paddingRight:15} }/>
        <Text>Your device has Blueooth {"\n"} turned off. Please swipe up {"\n"} and turn it on.</Text>
      </View>
    </View>

    <View style={styles.p3}>
      <Text>Need help with pairing?</Text>
    </View>

  </View>
);

},

componentDidMount: function() {
this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);

sub= NativeAppEventEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral); 

},

onSkipPress: function(){
//this.props.navigator.push({name: 'v2_calm'});

var data = base64.fromByteArray('HeckYes');
BleManager.write(dev.id, "00002220-0000-1000-8000-00805F9B34FB", "00002221-0000-1000-8000-00805F9B34FB", data)

},

onPress: function(){
// Log the user in
this.setState({
password: ''
});

},

btnPress: function(){
BleManager.scan([], 5);

},

handleDiscoverPeripheral: function(device){
dev=device;
console.log(typeof device);
console.log(Object.getOwnPropertyNames(device));
console.log(device);
if(typeof device===undefined)
{ this.setState({service: 'unde'}) }
else
{
this.setState({service: device.name});
BleManager.connect(device.id)
.then(() => {
// Success code
console.log('Connected');
})
.catch((error) => {
// Failure code
console.log(error);
});
//this.props.navigator.push({name: 'v2_calm'});
sub.remove();
}
}

});

Scan not filtering on Android ?

Scanning with a service UUID doesn't seem to filter anything, I still discover every peripheral around.
But it's working on iOS.

Tested on HTC M7, Samsung GT-i9505 (both running 5.0.1) and iPhone 6 Plus running iOS 9

Cannot read property 'scan' of undefined

Hi,

Thanks for this excellent job. I was trying to scan for devices with this module but I can not make it work. I am developing an Android app using a Samsung Galaxy S3 phone with Android 4.3. I am also using the last version of React Native (0.29). I did all the configurations described in the README file, but when I try to run the application appears the error: "cannot read property 'scan' of undefined". Could you please help me with this problem?
question

List of devices

Hi everyone!
How can I get the list of all available bluetooth devices?

BleManagerDidUpdateValueForCharacteristic is never called

Hey there, i need to read the value of an characteristic (in this case a private service !?)
One problem is, when i read() nothing happens. I tried to trace the native code on ios as well as on android. This is how my read looks like.

First example is when i read "public services":

let peripheralId = "some peripheral UUID or MAC address";
let serviceUUID = "180A";
let characteristicUUID = "2A25";
BleManager.read(peripheralId, serviceUUID, characteristicUUID).then((readData) => {
            console.log('value', readData);
            that.hex2a(readData); -> Response is Bluetooth Manufacturer in this case: Mircochip
        }).catch((error) => {
            console.log('err', error);
        });

Second example is when i read from "private services":

let peripheralId = "some peripheral UUID or MAC address";
let serviceUUID = "00035B03-58E6-07DD-021A-08123A000300";
let characteristicUUID = "00035B03-58E6-07DD-021A-08123A000301";
BleManager.read(peripheralId, serviceUUID, characteristicUUID).then((readData) => {
            console.log('value', readData);
            that.hex2a(readData);
        }).catch((error) => {
            console.log('err', error);
        });

Nothing happens when i try the second example...I am not sure what the problem is...maybe the UUID´s are too long :P

iOS scan not working in 2.x version

RN 0.37
iOS 10.1.1
XCode 8.1

scan is failing to discover peripheral on iOS for all 2.x releases. It works fine on 1.4.0.
Did anything change related to linking the project? I have BleManager.xcodeproj in Libraries and linked libBleManager.a, CoreBluetooth.framework in Build Phases.

hi i'm keeping getting error ' The callback write() exists in module BleManager, but only one callback may be registered to a function in a native module.'

I want to scan some my bluetooth module and connect to it. after i connected to it, i want to write data to specific characteristic UUID. but i've kept getting error

The callback write() exists in module BleManager, but only one callback may be registered to a function in a native module.

my whole code is below

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
Image,
ActivityIndicator,
TouchableHighlight,
NativeAppEventEmitter
} from 'react-native';

var Button = require('../common/button');
var BleManager=require('react-native-ble-manager');
var base64 = require('base64-js');

var b_list;
var dev;
var sub;

module.exports = React.createClass({
getInitialState: function(){
return {
username: '',
password: '',
animating: true,
service: 'ddsjdsljslks',
};
},

render: function(){
return (
<View style={ styles.container2 }>
<View style={ styles.p1 }>
Sign Out
<TouchableHighlight onPress = { this.btnPress }>
Bluetooth test

{this.state.service}

      <TouchableHighlight
        style={styles.button}
        underlayColor={'gray'}
        onPress={this.onSkipPress}
        >
        <Text style={styles.t3}>Skip</Text>
      </TouchableHighlight>

    </View>

    <View style={styles.p2}>
      <Image
        style={styles.img1}
        source={{uri: 'https://d30y9cdsu7xlg0.cloudfront.net/png/37728-200.png'}
      }/>

      <View style={styles.p2_row}>
        <ActivityIndicator animating={this.state.animating} color="black" style={ {paddingRight:15} }/>
        <Text>Your device has Blueooth {"\n"} turned off. Please swipe up {"\n"} and turn it on.</Text>
      </View>
    </View>

    <View style={styles.p3}>
      <Text>Need help with pairing?</Text>
    </View>

  </View>
);

},

componentDidMount: function() {
this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);

sub= NativeAppEventEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral); 

},

onSkipPress: function(){
//this.props.navigator.push({name: 'v2_calm'});

var data = base64.fromByteArray('HeckYes');
BleManager.write(dev.id, "00002220-0000-1000-8000-00805F9B34FB", "00002221-0000-1000-8000-00805F9B34FB", data)

},

onPress: function(){
// Log the user in
this.setState({
password: ''
});

},

btnPress: function(){
BleManager.scan([], 5);

},

handleDiscoverPeripheral: function(device){
dev=device;
console.log(typeof device);
console.log(Object.getOwnPropertyNames(device));
console.log(device);
if(typeof device===undefined)
{ this.setState({service: 'unde'}) }
else
{
this.setState({service: device.name});
BleManager.connect(device.id)
.then(() => {
// Success code
console.log('Connected');
})
.catch((error) => {
// Failure code
console.log(error);
});
//this.props.navigator.push({name: 'v2_calm'});
sub.remove();
}
}

});

Build error

* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 18 declared in library [NativeCloudMsgs:react-native-ble-manager:unspecified] /.../android/app/build/intermediates/exploded-aar/NativeCloudMsgs/react-native-ble-manager/unspecified/AndroidManifest.xml
    Suggestion: use tools:overrideLibrary="it.innove" to force usage

Any idea why?

ble manager

Hi, thanks for this module, awesome job!!
one question,
Is there in the library a FIFO queue?

Can't read advertisment raw data.

Hey! I am trying to decode the raw data of the advertising package (advertising.data). First I decoded the string to a byte array with bas64-js package and then I tried the following node packages:

https://github.com/tessel/bleadvertise - Didn't work. "Can't find variable: Buffer"
https://www.npmjs.com/package/ble-ad-parser - - Didn't work. "Can't find variable: Buffer"
https://github.com/mfgCode/ble-packet-parser - Didn't work. Reports are undefined.

Does anyone know how to read the data? :)

Example how the whole package looks like. I am trying to decode the advertising.data part.

{
rssi: -93,
name: 'Liee_A3',
id: '4E:3C:B1:F7:A0:F9',
advertising: 
{ CDVType: 'ArrayBuffer',
data: 'AgEGE/9MAAwOAEGAkOLfaaB9WE7cR0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } 
}

Device name

Why device name is always null? I tried with iOS

Bluetooth.scan([], 5, false)
.then(() => {
// Success code
console.log('Scan started');
});

NativeAppEventEmitter.addListener(
'BleManagerDiscoverPeripheral',
(args) => {
console.log(args)
}
);

args is object like this:
{ id: 'C92C740D-A084-FAB7-7A44-251D12F7D099',
advertising: { kCBAdvDataIsConnectable: true } }
2016-08-05 18:43:12.399 [info][tid:com.facebook.react.JavaScript] { id: 'C92C740D-A084-FAB7-7A44-251D12F7D099',
advertising:
{ kCBAdvDataServiceData:
{ '8EB5':
{ CDVType: 'ArrayBuffer',
data: 'AZAGmKhr6ZF2x0/EiSpVGs8Hx3wADgK7+ANY' } },
kCBAdvDataIsConnectable: true } }

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.