This plugin enables communication between a phone and Bluetooth Low Energy (BLE) peripherals.
The plugin provides a simple JavaScript API for iOS and Android.
Advertising information is returned when scanning for peripherals. Service, characteristic, and property info is returned when connecting to a peripheral. All access is via service and characteristic UUIDs. The plugin manages handles internally.
Simultaneous connections to multiple peripherals are supported.
See the examples for ideas on how this plugin can be used.
$ cordova plugin add cordova-plugin-ble-central
$ phonegap plugin add cordova-plugin-ble-central
Edit config.xml to install the plugin for PhoneGap Build.
<gap:plugin name="cordova-plugin-ble-central" source="npm" />
<preference name="phonegap-version" value="cli-6.1.0" />
This plugin is included in iOS and Android versions of the PhoneGap Developer App.
Note that this plugin's id changed from com.megster.cordova.ble
to cordova-plugin-ble-central
as part of the migration from the Cordova plugin repo to npm.
For iOS 10, apps will crash unless they include usage description keys for the types of data they access. For Bluetooth, NSBluetoothPeripheralUsageDescription must be defined.
This can be done when the plugin is installed using the BLUETOOTH_USAGE_DESCRIPTION variable.
$ cordova plugin add cordova-plugin-ble-central --variable BLUETOOTH_USAGE_DESCRIPTION="Your description here"
Scan and discover BLE peripherals.
ble.scan(services, seconds, success, failure);
Function scan
scans for BLE devices. The success callback is called each time a peripheral is discovered. Scanning automatically stops after the specified number of seconds.
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
Advertising information format varies depending on your platform. See Advertising Data for more information.
ble.scan([], 5, function(device) {
console.log(JSON.stringify(device));
}, failure);
Scan and discover BLE peripherals.
ble.startScan(services, success, failure);
Function startScan
scans for BLE devices. The success callback is called each time a peripheral is discovered. Scanning will continue until stopScan
is called.
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
Advertising information format varies depending on your platform. See Advertising Data for more information.
ble.startScan([], function(device) {
console.log(JSON.stringify(device));
}, failure);
setTimeout(ble.stopScan,
5000,
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
Scan and discover BLE peripherals, specifying scan options.
ble.startScanWithOptions(services, options, success, failure);
Function startScanWithOptions
scans for BLE devices. It operates similarly to the startScan
function, but allows you to specify extra options (like allowing duplicate device reports). The success callback is called each time a peripheral is discovered. Scanning will continue until stopScan
is called.
{
"name": "TI SensorTag",
"id": "BD922605-1B07-4D55-8D09-B66653E51BBA",
"rssi": -79,
"advertising": /* ArrayBuffer or map */
}
Advertising information format varies depending on your platform. See Advertising Data for more information.
ble.startScan([],
{ reportDuplicates: true }
function(device) {
console.log(JSON.stringify(device));
},
failure);
setTimeout(ble.stopScan,
5000,
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
Stop scanning for BLE peripherals.
ble.stopScan(success, failure);
Function stopScan
stops scanning for BLE devices.
ble.startScan([], function(device) {
console.log(JSON.stringify(device));
}, failure);
setTimeout(ble.stopScan,
5000,
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
/* Alternate syntax
setTimeout(function() {
ble.stopScan(
function() { console.log("Scan complete"); },
function() { console.log("stopScan failed"); }
);
}, 5000);
*/
Connect to a peripheral.
ble.connect(device_id, connectSuccess, connectFailure);
Function connect
connects to a BLE peripheral. The callback is long running. Success will be called when the connection is successful. Service and characteristic info will be passed to the success callback in the peripheral object. Failure is called if the connection fails, or later if the peripheral disconnects. An peripheral object is passed to the failure callback.
NOTE: the connect failure callback will be called if the peripheral disconnects.
Disconnect.
ble.disconnect(device_id, [success], [failure]);
Function disconnect
disconnects the selected device.
Reads the value of a characteristic.
ble.read(device_id, service_uuid, characteristic_uuid, success, failure);
Function read
reads the value of the characteristic.
Raw data is passed from native code to the callback as an ArrayBuffer.
Writes data to a characteristic.
ble.write(device_id, service_uuid, characteristic_uuid, data, success, failure);
Function write
writes data to a characteristic.
Use an ArrayBuffer when writing data.
// send 1 byte to switch a light on
var data = new Uint8Array(1);
data[0] = 1;
ble.write(device_id, "FF10", "FF11", data.buffer, success, failure);
// send a 3 byte value with RGB color
var data = new Uint8Array(3);
data[0] = 0xFF; // red
data[1] = 0x00; // green
data[2] = 0xFF; // blue
ble.write(device_id, "ccc0", "ccc1", data.buffer, success, failure);
// send a 32 bit integer
var data = new Uint32Array(1);
data[0] = counterInput.value;
ble.write(device_id, SERVICE, CHARACTERISTIC, data.buffer, success, failure);
Writes data to a characteristic without confirmation from the peripheral.
ble.writeWithoutResponse(device_id, service_uuid, characteristic_uuid, data, success, failure);
Function writeWithoutResponse
writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. The success callback is be called when the characteristic is written.
Register to be notified when the value of a characteristic changes.
ble.startNotification(device_id, service_uuid, characteristic_uuid, success, failure);
Function startNotification
registers a callback that is called every time the value of a characteristic changes. This method handles both notifications
and indications
. The success callback is called multiple times.
Raw data is passed from native code to the success callback as an ArrayBuffer.
See Background Notifications on iOS
var onData = function(buffer) {
// Decode the ArrayBuffer into a typed Array based on the data you expect
var data = new Uint8Array(buffer);
alert("Button state changed to " + data[0]);
}
ble.startNotification(device_id, "FFE0", "FFE1", onData, failure);
Stop being notified when the value of a characteristic changes.
ble.stopNotification(device_id, service_uuid, characteristic_uuid, success, failure);
Function stopNotification
stops a previously registered notification callback.
Reports the connection status.
ble.isConnected(device_id, success, failure);
Function isConnected
calls the success callback when the peripheral is connected and the failure callback when not connected.
ble.isConnected(
'FFCA0B09-CB1D-4DC0-A1EF-31AFD3EDFB53',
function() {
console.log("Peripheral is connected");
},
function() {
console.log("Peripheral is *not* connected");
}
);
Reports if bluetooth is enabled.
ble.isEnabled(success, failure);
Function isEnabled
calls the success callback when Bluetooth is enabled and the failure callback when Bluetooth is not enabled.
ble.isEnabled(
function() {
console.log("Bluetooth is enabled");
},
function() {
console.log("Bluetooth is *not* enabled");
}
);
Registers to be notified when Bluetooth state changes on the device.
ble.startStateNotifications(success, failure);
Function startStateNotifications
calls the success callback when the Bluetooth is enabled or disabled on the device.
States
ble.startStateNotifications(
function(state) {
console.log("Bluetooth is " + state);
}
);
Stops state notifications.
ble.startStateNotifications(success, failure);
Function stopStateNotifications
calls the success callback when Bluetooth state notifications have been stopped.
Show the Bluetooth settings on the device.
ble.showBluetoothSettings(success, failure);
Function showBluetoothSettings
opens the Bluetooth settings for the operating systems.
showBluetoothSettings
is not supported on iOS.
ble.showBluetoothSettings();
Enable Bluetooth on the device.
ble.enable(success, failure);
Function enable
prompts the user to enable Bluetooth.
enable
is only supported on Android and does not work on iOS.
If enable
is called when Bluetooth is already enabled, the user will not prompted and the success callback will be invoked.
ble.enable(
function() {
console.log("Bluetooth is enabled");
},
function() {
console.log("The user did *not* enable Bluetooth");
}
);
Read the RSSI value on the device connection.
ble.readRSSI(device_id, success, failure);
Samples the RSSI value (a measure of signal strength) on the connection to a bluetooth device. Requires that you have established a connection before invoking (otherwise an error will be raised).
var rssiSample;
ble.connect(device_id,
function(device) {
rssiSample = setInterval(function() {
ble.readRSSI(device_id, function(rssi) {
console.log('read RSSI',rssi,'with device', device_id);
}, function(err) {
console.error('unable to read RSSI',err);
clearInterval(rssiSample);
})
}, 5000);
},
function(err) { console.error('error connecting to device')}
);
Peripheral Data is passed to the success callback when scanning and connecting. Limited data is passed when scanning.
{
"name": "Battery Demo",
"id": "20:FF:D0:FF:D1:C0",
"advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],
"rssi": -55
}
After connecting, the peripheral object also includes service, characteristic and descriptor information.
{
"name": "Battery Demo",
"id": "20:FF:D0:FF:D1:C0",
"advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],
"rssi": -55,
"services": [
"1800",
"1801",
"180f"
],
"characteristics": [
{
"service": "1800",
"characteristic": "2a00",
"properties": [
"Read"
]
},
{
"service": "1800",
"characteristic": "2a01",
"properties": [
"Read"
]
},
{
"service": "1801",
"characteristic": "2a05",
"properties": [
"Read"
]
},
{
"service": "180f",
"characteristic": "2a19",
"properties": [
"Read"
],
"descriptors": [
{
"uuid": "2901"
},
{
"uuid": "2904"
}
]
}
]
}
Bluetooth advertising data is returned in when scanning for devices. The format format varies depending on your platform. On Android advertising data will be the raw advertising bytes. iOS does not allow access to raw advertising data, so a dictionary of data is returned.
The advertising information for both Android and iOS appears to be a combination of advertising data and scan response data.
Ideally a common format (map or array) would be returned for both platforms in future versions. If you have ideas, please contact me.
{
"name": "demo",
"id": "00:1A:7D:DA:71:13",
"advertising": ArrayBuffer,
"rssi": -37
}
Convert the advertising info to a Uint8Array for processing. var adData = new Uint8Array(peripheral.advertising)
Note that iOS uses the string value of the constants for the Advertisement Data Retrieval Keys. This will likely change in the future.
{
"name": "demo",
"id": "D8479A4F-7517-BCD3-91B5-3302B2F81802",
"advertising": {
"kCBAdvDataChannel": 37,
"kCBAdvDataServiceData": {
"FED8": {
"byteLength": 7 // data not shown
}
},
"kCBAdvDataLocalName": "demo",
"kCBAdvDataServiceUUIDs": ["FED8"],
"kCBAdvDataManufacturerData": {
"byteLength": 7 // data not shown
},
"kCBAdvDataTxPowerLevel": 32,
"kCBAdvDataIsConnectable": true
},
"rssi": -53
}
This plugin uses typed Arrays or ArrayBuffers for sending and receiving data.
This means that you need convert your data to ArrayBuffers before sending and from ArrayBuffers when receiving.
// ASCII only
function stringToBytes(string) {
var array = new Uint8Array(string.length);
for (var i = 0, l = string.length; i < l; i++) {
array[i] = string.charCodeAt(i);
}
return array.buffer;
}
// ASCII only
function bytesToString(buffer) {
return String.fromCharCode.apply(null, new Uint8Array(buffer));
}
You can read more about typed arrays in these articles on MDN and HTML5 Rocks.
UUIDs are always strings and not numbers. Some 16-bit UUIDs, such as '2220' look like integers, but they're not. (The integer 2220 is 0x8AC in hex.) This isn't a problem with 128 bit UUIDs since they look like strings 82b9e6e1-593a-456f-be9b-9215160ebcac. All 16-bit UUIDs should also be passed to methods as strings.
# Background Scanning and Notifications on iOSAndroid applications will continue to receive notification while the application is in the background.
iOS applications need additional configuration to allow Bluetooth to run in the background.
Install the cordova-custom-config plugin.
cordova plugin add cordova-custom-config
Add a new section to config.xml
<platform name="ios">
<config-file parent="UIBackgroundModes" target="*-Info.plist">
<array>
<string>bluetooth-central</string>
</array>
</config-file>
</platform>
See ble-background example project for more details.
Tests require the Cordova Plugin Test Framework
Create a new project
git clone https://github.com/don/cordova-plugin-ble-central
cordova create ble-test com.example.ble.test BLETest
cd ble-test
cordova platform add android
cordova plugin add ../cordova-plugin-ble-central
cordova plugin add ../cordova-plugin-ble-central/tests
cordova plugin add cordova-plugin-test-framework
Change the start page in config.xml
<content src="cdvtests/index.html" />
Run the app on your phone
cordova run android --device
Apache 2.0
Try the code. If you find an problem or missing feature, file an issue or create a pull request.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型