dotintent / react-native-ble-plx Goto Github PK
View Code? Open in Web Editor NEWReact Native BLE library
License: Apache License 2.0
React Native BLE library
License: Apache License 2.0
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!
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`
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)
‘null’ is not a supported event type for blemodule. supported events are 'null'
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.
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?
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?
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!
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?
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
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!
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
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 });
}
};
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.
Consider creating a project which will simulate real world scenarios to test current APIs
Implement following operations related to descriptors:
Can I get the connected Bluetooth device informations without any parameters ,and the device is connected manually in system setting.
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
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
Getting the above error. I installed as instructed but it doesn't seem to be working.
Any ideas what i might be doing wrong ?
"react": "15.4.1",
"react-native": "0.39.2",
"react-native-ble-plx": 0.3.3
I don't know if this is in the scope of this library but it would be really nice to include in this library a function that enables/disables Bluetooth. I know this only works for Android but it would still be useful.
Found some examples here: http://stackoverflow.com/a/20142972/1836121
when do you support rnpm
scripting so that people dont have to do all the manual installations..
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?
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.
While i scan with filtering by service uuid, scanned device id property is undefined. It was working great with v0.3.3
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.
TypeError undefined is not a function (evaluating '(bridgeConfig.remoteModuleConfig||[]).forEach')
All below fields from https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile should be available for user:
iOS and Android fields:
Local name (0x08 || 0x09) (ignored, name is used)
iOS only fields:
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
This feature will allow to quit chained promises faster without a need of cancelling peripheral connection.
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.
How does one send/receive data between two devices? What functions to access??
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!
How can I execute a http request for example, when a beacon is detected in the background mode?
Consider following API breaking changes before going 1.0:
name
and rssi
) to advertisement object which will be included in Device if possible.(error, T) => void
callback types to (Result<T>) => void
which will allow to apply better Flow type checking.Device.uuid
to Device.id
as it's not UUIDIs it possible to discover other smartphones or tablets running the same app (in the background) with this library? Does it support advertising?
npm ERR! [email protected] postinstall: bash build_ios_frameworks.sh
npm ERR! Exit status 1
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!
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?
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);
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; ^
Add type support by using Flow, which is de facto a standard in React Native project.
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.
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.
Make sure that error format is unified between platforms.
Sometimes when trying to reconnect to a device I get the following error:
{message: "Bluetooth is powered off", code: 102}
Even though the Bluetooth is definitely on. It also results in me not being able to reconnect.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.