Giter Club home page Giter Club logo

cordova-plugin-ble-central's Introduction

Bluetooth Low Energy (BLE) Central Plugin for Apache Cordova

npm version maintained cordova builds capacitor builds license

This plugin enables communication between a phone and Bluetooth Low Energy (BLE) peripherals.

The plugin provides a simple JavaScript API for iOS and Android.

  • Scan for peripherals
  • Connect to a peripheral
  • Read the value of a characteristic
  • Write new value to a characteristic
  • Get notified when characteristic's value changes
  • Transfer data via L2CAP channels

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.

This plugin isn't intended for scanning beacons. Try cordova-plugin-ibeacon for iBeacons.
If you want to create Bluetooth devices, try cordova-plugin-ble-peripheral.

See the examples for ideas on how this plugin can be used.

Supported Platforms

  • iOS
  • Android 6+ (8.1 or greater recommended)
  • Browser (where navigator.bluetooth is supported)

Installing

Capacitor

$ npm install cordova-plugin-ble-central
$ npx cap sync

The plugin can be further configured via the cordova preferences section of the capacitor config file:

const config = {
  ...
  cordova: {
    preferences: {
      ...
      bluetooth_restore_state: "true",
      accessBackgroundLocation: "false",
    },
  }
}
  • bluetooth_restore_state: [iOS] Enable Bluetooth state restoration, allowing an app to be woken up to receive scan results and peripheral notifications. This is needed for background scanning support. See iOS restore state. For more information about background operation with this plugin, see Background Scanning and Notifications on iOS.

  • accessBackgroundLocation: [Android] Tells the plugin to request the ACCESS_BACKGROUND_LOCATION permission on Android 10 & Android 11 in order for scanning to function when the app is not visible.

iOS

After installation, the following additions should be made to the app's Info.plist

  • Set NSBluetoothAlwaysUsageDescription to a descriptive text, to be shown to the user on first access to the Bluetooth adapter. If this is not defined the app will crash.
  • (Optional) Add bluetooth-central to UIBackgroundModes to enable background receipt of scan information and BLE notifications

Cordova

$ cordova plugin add cordova-plugin-ble-central --variable BLUETOOTH_USAGE_DESCRIPTION="Your description here" --variable IOS_INIT_ON_LOAD=true|false --variable BLUETOOTH_RESTORE_STATE=true|false --variable ACCESS_BACKGROUND_LOCATION=true|false

It's recommended to always use the latest cordova and cordova platform packages in order to ensure correct function. This plugin generally best supports the following platforms and version ranges:

cordova cordova-ios cordova-android cordova-browser
10+ 6.2.0+ 10.0+ not tested

All variables can be modified after installation by updating the values in package.json.

  • BLUETOOTH_USAGE_DESCRIPTION: [iOS] defines the values for NSBluetoothAlwaysUsageDescription.

  • IOS_INIT_ON_LOAD: [iOS] Prevents the Bluetooth plugin from being initialised until first access to the ble window object. This allows an application to warn the user before the Bluetooth access permission is requested.

  • BLUETOOTH_RESTORE_STATE: [iOS] Enable Bluetooth state restoration, allowing an app to be woken up to receive scan results and peripheral notifications. This is needed for background scanning support. See iOS restore state. For more information about background operation with this plugin, see Background Scanning and Notifications on iOS.

  • ACCESS_BACKGROUND_LOCATION: [Android] Tells the plugin to request the ACCESS_BACKGROUND_LOCATION permission on Android 10 & Android 11 in order for scanning to function when the app is not visible.

TypeScript

TypeScript definitions are provided by this plugin. These can be added to a file by adding a triple-slash reference at the top of any file using this plugin:

/// <reference types="cordova-plugin-ble-central" />

Android permission conflicts

If you are having Android permissions conflicts with other plugins, try using the slim variant of the plugin instead with cordova plugin add cordova-plugin-ble-central@slim. This variant excludes all Android permissions, leaving it to the developer to ensure the right entries are added manually to the AndroidManifest.xml (see below for an example).

To include the default set of permissions the plugin installs on Android SDK v31+, add the following snippet in your config.xml file, in the <platform name="android"> section:

    <config-file target="AndroidManifest.xml" parent="/manifest">
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" />
        <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.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
        <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    </config-file>

For the best understanding about which permissions are needed for which combinations of target SDK version & OS version, see Android Bluetooth permissions

API

scan

Scan and discover BLE peripherals.

ble.scan(services, seconds, success, failure);

Description

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.

Location Permission Notes

With Android SDK >= 23 (6.0), additional permissions are required for Bluetooth low energy scanning. The location permission ACCESS_COARSE_LOCATION is required because Bluetooth beacons can be used to determine a user's location. If necessary, the plugin will prompt the user to allow the app to access to device's location. If the user denies permission, the scan failure callback will receive the error "Location permission not granted".

Location Services must be enabled for Bluetooth scanning. If location services are disabled, the failure callback will receive the error "Location services are disabled". If you want to manage location permission and screens, try the cordova-diagonostic-plugin or the Ionic Native Diagnostic plugin.

Parameters

  • services: List of services to discover, or [] to find all devices
  • seconds: Number of seconds to run discovery
  • success: Success callback function that is invoked which each discovered device.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.scan(
    [],
    5,
    function (device) {
        console.log(JSON.stringify(device));
    },
    failure
);

startScan

Scan and discover BLE peripherals.

ble.startScan(services, success, failure);

Description

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.

See the location permission notes above for information about Location Services in Android SDK >= 23.

Parameters

  • services: List of services to discover, or [] to find all devices
  • success: Success callback function that is invoked which each discovered device.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.startScan(
    [],
    function (device) {
        console.log(JSON.stringify(device));
    },
    failure
);

setTimeout(
    ble.stopScan,
    5000,
    function () {
        console.log('Scan complete');
    },
    function () {
        console.log('stopScan failed');
    }
);

startScanWithOptions

Scan and discover BLE peripherals, specifying scan options.

ble.startScanWithOptions(services, options, success, failure);

Description

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.

See the location permission notes above for information about Location Services in Android SDK >= 23.

Parameters

  • services: List of services to discover, or [] to find all devices
  • options: an object specifying a set of name-value pairs. The currently acceptable options are:
    • reportDuplicates: true if duplicate devices should be reported, false (default) if devices should only be reported once.
    • duration: time in seconds to scan for. (default) Scans forever when not specified.
    • scanMode: String defines setScanMode() argument on Android. Default on Android is lowPower. When interactive scanning from an app, lowLatency can boost how quickly the device is found, at the expense of using more battery power. Can be one of: lowPower | balanced | lowLatency | opportunistic
    • callbackType: String defines setCallbackType() argument on Android.
      Can be one of: all | first | lost
    • matchMode: String defines setMatchMode() argument on Android.
      Can be one of: aggressive | sticky
    • numOfMatches: String defines setNumOfMatches() argument on Android.
      Can be one of: one | few | max
    • phy: String for setPhy() on Android. Can be one of: 1m | coded | all
    • legacy: true or false to control filtering bluetooth spec.pre-4.2 advertisements on Android.
    • forceScanFilter: true or false to to force an empty scan filter if no other filters are provided on Android.
    • reportDelay: Milliseconds for setReportDelay() on Android. 0 to be notified of results immediately. Values > 0 causes the scan results to be queued up and delivered after the requested delay or when the internal buffers fill up.
  • success: Success callback function that is invoked which each discovered device.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.startScanWithOptions([],
    { reportDuplicates: true }
    function(device) {
        console.log(JSON.stringify(device));
    },
    failure);

setTimeout(ble.stopScan,
    5000,
    function() { console.log("Scan complete"); },
    function() { console.log("stopScan failed"); }
);

stopScan

Stop scanning for BLE peripherals.

ble.stopScan(success, failure);
// Or using await with promises
await ble.withPromises.stopScan();

Description

Function stopScan stops scanning for BLE devices.

Parameters

  • success: Success callback function, invoked when scanning is stopped. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

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);
*/

setPin

Set device pin

ble.setPin(pin, [success], [failure]);
// Or using await with promises
await ble.withPromises.setPin(pin);

Description

Function setPin sets the pin when device requires it.

Parameters

  • pin: Pin of the device as a string
  • success: Success callback function that is invoked when the function is invoked. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

bond

Initiate a bond with a remote device

ble.bond(device_id, [success], [failure], [options]);
// Or using await with promises
await ble.withPromises.bond(device_id);
await ble.withPromises.bond(device_id, { usePairingDialog: true });

Description

Function bond initialises a bond with a peripheral. The success callback will be called when the bonding is complete. The bonding process may prompt the user to confirm the pairing process.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • success: Success callback function that is invoked when the bonding succeeds. [optional]
  • failure: Error callback function, invoked when the bonding fails. [optional]
  • options: an object specifying a set of name-value pairs. The currently acceptable options are:
    • usePairingDialog: true (default) Show pairing request as a dialog rather than a notification [optional]

Supported Platforms

  • Android

unbond

Remove a bond for a remote device

ble.unbond(device_id, [success], [failure]);
// Or using await with promises
await ble.withPromises.unbond(device_id);

Description

Function unbond removes an existing bond for a remote device. The success callback will be called when the bond has been removed.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • success: Success callback function that is invoked when the bond is removed. [optional]
  • failure: Error callback function, invoked when the bond removal fails. [optional]

Supported Platforms

  • Android

readBondState

Get the bond state of a device as a string

ble.readBondState(device_id, [success], [failure]);
// Or using await with promises
const bondState = await ble.withPromises.readBondState(device_id);

Description

Function readBondState retrieves the current bond state of the device.

States

  • "none"
  • "bonding"
  • "bonded"

Parameters

  • device_id: UUID or MAC address of the peripheral
  • success: Success callback function that is invoked with the current bond state. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Supported Platforms

  • Android

connect

Connect to a peripheral.

ble.connect(device_id, connectCallback, disconnectCallback);

Description

Function connect connects to a BLE peripheral. The callback is long running. The connect callback will be called when the connection is successful. Service and characteristic info will be passed to the connect callback in the peripheral object.

The disconnect callback is called if the connection fails, or later if the peripheral disconnects. When possible, a peripheral object is passed to the failure callback. The disconnect callback is only called when the peripheral initates the disconnection. The disconnect callback is not called when the application calls ble.disconnect. The disconnect callback is how your app knows the peripheral inintiated a disconnect.

Scanning before connecting

Android can connect to peripherals using MAC address without scanning. If the MAC address is not found the connection will time out.

For iOS, the plugin needs to know about any device UUID before calling connect. You can do this by calling ble.scan, ble.startScan, ble.connectedPeripheralsWithServices, or ble.peripheralsWithIdentifiers so the plugin has a list of available peripherals.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • connectCallback: Connect callback function that is invoked when the connection is successful.
  • disconnectCallback: Disconnect callback function, invoked when the peripheral disconnects or an error occurs.

autoConnect

Establish an automatic connection to a peripheral.

ble.autoConnect(device_id, connectCallback, disconnectCallback);

Description

Automatically connect to a device when it is in range of the phone. When the device connects, the connect callback is called with a peripheral object. The call to autoConnect will not time out. It will wait forever until the device is in range. When the peripheral disconnects, the disconnect callback is called with a peripheral object.

Calling ble.disconnect will stop the automatic reconnection.

Both the connect and disconnect callbacks can be called many times as the device connects and disconnects. Do not wrap this function in a Promise or Observable.

On iOS, background notifications on ios must be enabled if you want to run in the background. On Android, this relies on the autoConnect argument of BluetoothDevice.connectGatt(). Not all Android devices implement this feature correctly.

See notes about scanning before connecting

Parameters

  • device_id: UUID or MAC address of the peripheral
  • connectCallback: Connect callback function that is invoked when the connection is successful.
  • disconnectCallback: Disconnect callback function, invoked when the peripheral disconnects or an error occurs.

disconnect

Disconnect.

ble.disconnect(device_id, [success], [failure]);
// Or using await with promises
await ble.withPromises.disconnect(device_id);

Description

Function disconnect disconnects the selected device.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

requestMtu

requestMtu

ble.requestMtu(device_id, new_mtu, [success], [failure]);
// Or using await with promises
const actual_mtu = await ble.withPromises.requestMtu(device_id, new_mtu);

Description

This function may be used to request (on Android) a larger MTU size to be able to send more data at once. This can be useful when performing a write request operation (write without response), the data sent is truncated to the MTU size. The resulting MTU size is sent to the success callback. The requested and resulting MTU sizes are not necessarily equal.

Supported Platforms

  • Android

Parameters

  • device_id: UUID or MAC address of the peripheral
  • mtu: MTU size
  • success: Success callback function that is invoked when the MTU size request is successful. The resulting MTU size is passed as an integer.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.requestMtu(
    device_id,
    new_mtu,
    function (mtu) {
        alert('MTU set to: ' + mtu);
    },
    function (failure) {
        alert('Failed to request MTU.');
    }
);

requestConnectionPriority

requestConnectionPriority

ble.requestConnectionPriority(device_id, priority, [success], [failure]);
// Or using await with promises
await ble.withPromises.requestConnectionPriority(device_id, priority);

Description

When Connecting to a peripheral android can request for the connection priority for better communication. See BluetoothGatt#requestConnectionPriority for technical details

Connection priority can be one of:

Supported Platforms

  • Android

Parameters

  • device_id: UUID or MAC address of the peripheral
  • priority: "high", "balanced" or "low"
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.requestConnectionPriority(
    device_id,
    'high',
    function () {
        alert('success');
    },
    function (failure) {
        alert('Failed to request connection priority: ' + failure);
    }
);

refreshDeviceCache

refreshDeviceCache

ble.refreshDeviceCache(deviceId, timeoutMillis, [success], [failure]);

Description

Some poorly behaved devices show old cached services and characteristics info. (Usually because they don't implement Service Changed 0x2a05 on Generic Attribute Service 0x1801 and the central doesn't know the data needs to be refreshed.) This method might help.

NOTE Since this uses an undocumented API it's not guaranteed to work.

Supported Platforms

  • Android

Parameters

  • deviceId: UUID or MAC address of the peripheral
  • timeoutMillis: timeout in milliseconds after refresh before discovering services
  • success: Success callback function invoked with the refreshed peripheral. [optional]
  • failure: Error callback function, invoked when an error occurs. [optional]

read

Reads the value of a characteristic.

ble.read(device_id, service_uuid, characteristic_uuid, success, failure);
// Or using await with promises
const data = await ble.withPromises.read(device_id, service_uuid, characteristic_uuid);

Description

Function read reads the value of the characteristic.

Raw data is passed from native code to the callback as an ArrayBuffer.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • service_uuid: UUID of the BLE service
  • characteristic_uuid: UUID of the BLE characteristic
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

Retrieves an ArrayBuffer when reading data.

// read data from a characteristic, do something with output data
ble.read(
    device_id,
    service_uuid,
    characteristic_uuid,
    function (data) {
        console.log('Hooray we have data' + JSON.stringify(data));
        alert('Successfully read data from device.' + JSON.stringify(data));
    },
    function (failure) {
        alert('Failed to read characteristic from device.');
    }
);

write

Writes data to a characteristic.

ble.write(device_id, service_uuid, characteristic_uuid, data, success, failure);
// Or using await with promises
await ble.withPromises.write(device_id, service_uuid, characteristic_uuid, data);

Description

Function write writes data to a characteristic.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • service_uuid: UUID of the BLE service
  • characteristic_uuid: UUID of the BLE characteristic
  • data: binary data, use an ArrayBuffer
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

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

writeWithoutResponse

Writes data to a characteristic without confirmation from the peripheral.

ble.writeWithoutResponse(device_id, service_uuid, characteristic_uuid, data, success, failure);
// Or using await with promises
await ble.withPromises.writeWithoutResponse(device_id, service_uuid, characteristic_uuid, data);

Description

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.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • service_uuid: UUID of the BLE service
  • characteristic_uuid: UUID of the BLE characteristic
  • data: binary data, use an ArrayBuffer
  • success: Success callback function that is invoked when the connection is successful. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

startNotification

Register to be notified when the value of a characteristic changes.

ble.startNotification(device_id, service_uuid, characteristic_uuid, success, failure);
// Or using await with promises
// Note, initial promise resolves or rejects depending on whether the subscribe was successful
await ble.withPromises.startNotification(device_id, success, failure);

Description

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

Parameters

  • device_id: UUID or MAC address of the peripheral
  • service_uuid: UUID of the BLE service
  • characteristic_uuid: UUID of the BLE characteristic
  • success: Success callback function invoked every time a notification occurs
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

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

stopNotification

Stop being notified when the value of a characteristic changes.

ble.stopNotification(device_id, service_uuid, characteristic_uuid, success, failure);
// Or using await with promises
await ble.withPromises.stopNotification(device_id);

Description

Function stopNotification stops a previously registered notification callback.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • service_uuid: UUID of the BLE service
  • characteristic_uuid: UUID of the BLE characteristic
  • success: Success callback function that is invoked when the notification is removed. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

isConnected

Reports the connection status.

// Callbacks
ble.isConnected(device_id, success, failure);

// Promises with boolean return
const isConnected = await ble.withPromises.isConnected(device_id, false);

// Promises with rejection
await ble.withPromises.isConnected(device_id); // throws if not connected

Description

Function isConnected calls the success callback when the peripheral is connected and the failure callback when not connected.

NOTE that for many apps isConnected is unncessary. The app can track the connected state. Ater calling connect the app is connected when the success callback function is called. If the device disconnects at any point in the future, the failure callback of connect will be called.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • success: Success callback function that is invoked with a boolean for connected status.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

// Callbacks
ble.isConnected(
    'FFCA0B09-CB1D-4DC0-A1EF-31AFD3EDFB53',
    function () {
        console.log('Peripheral is connected');
    },
    function () {
        console.log('Peripheral is *not* connected');
    }
);

// Promises with boolean return
const isConnected = await ble.withPromises.isConnected(device_id, false);
if (isConnected) {
    console.log('Peripheral is connected');
} else {
    console.log('Peripheral is *not* connected');
}

// Promises with rejection
try {
    await ble.withPromises.isConnected(device_id);
    console.log('Peripheral is connected');
} catch (e) {
    console.log('Peripheral is *not* connected');
}

isEnabled

Reports if bluetooth is enabled.

ble.isEnabled(success, failure);

Description

Function isEnabled calls the success callback when Bluetooth is enabled and the failure callback when Bluetooth is not enabled.

Parameters

  • success: Success callback function, invoked when Bluetooth is enabled.
  • failure: Error callback function, invoked when Bluetooth is disabled.

Quick Example

ble.isEnabled(
    function () {
        console.log('Bluetooth is enabled');
    },
    function () {
        console.log('Bluetooth is *not* enabled');
    }
);

isLocationEnabled

Reports if location services are enabled.

ble.isLocationEnabled(success, failure);

Description

Function isLocationEnabled calls the success callback when location services are enabled and the failure callback when location services are not enabled. On some devices, location services must be enabled in order to scan for peripherals.

Supported Platforms

  • Android

Parameters

  • success: Success callback function, invoked when location services are enabled.
  • failure: Error callback function, invoked when location services are disabled.

Quick Example

ble.isLocationEnabled(
    function () {
        console.log('location services are enabled');
    },
    function () {
        console.log('location services are *not* enabled');
    }
);

startLocationStateNotifications

Registers to be notified when Location service state changes on the device.

ble.startLocationStateNotifications(success, failure);
// Or using await with promises
// Note, initial promise resolves or rejects depending on whether the subscribe was successful
await ble.withPromises.startLocationStateNotifications(success, failure);

Description

Function startLocationStateNotifications calls the success callback when the Location service is enabled or disabled on the device.

Supported Platforms

  • Android

Parameters

  • success: Success callback function that is invoked with a boolean for the Location state.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.startLocationStateNotifications(function (enabled) {
    console.log('Location is ' + enabled);
});

stopLocationStateNotifications

Stops state notifications.

ble.stopLocationStateNotifications(success, failure);
// Or using await with promises
await ble.withPromises.stopLocationStateNotifications();

Description

Function stopLocationStateNotifications calls the success callback when Location state notifications have been stopped.

Supported Platforms

  • Android

startStateNotifications

Registers to be notified when Bluetooth state changes on the device.

ble.startStateNotifications(success, failure);
// Or using await with promises
// Note, initial promise resolves or rejects depending on whether the subscribe was successful
await ble.withPromises.startStateNotifications(success, failure);

Description

Function startStateNotifications calls the success callback when the Bluetooth is enabled or disabled on the device.

States

  • "on"
  • "off"
  • "turningOn" (Android Only)
  • "turningOff" (Android Only)
  • "unknown" (iOS Only)
  • "resetting" (iOS Only)
  • "unsupported" (iOS Only)
  • "unauthorized" (iOS Only)

Supported Platforms

  • Android
  • iOS

Parameters

  • success: Success callback function that is invoked with a string for the Bluetooth state.
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.startStateNotifications(function (state) {
    console.log('Bluetooth is ' + state);
});

stopStateNotifications

Stops state notifications.

ble.stopStateNotifications(success, failure);
// Or using await with promises
await ble.withPromises.stopStateNotifications();

Description

Function stopStateNotifications calls the success callback when Bluetooth state notifications have been stopped.

Supported Platforms

  • Android
  • iOS

showBluetoothSettings

Show the Bluetooth settings on the device.

ble.showBluetoothSettings(success, failure);
// Or using await with promises
await ble.withPromises.showBluetoothSettings();

Description

Function showBluetoothSettings opens the Bluetooth settings for the operating systems.

showBluetoothSettings is not available on iOS. Plugins like cordova-diagonostic-plugin and the Ionic Native Diagnostic plugin have APIs to open Bluetooth and other settings, but will often get apps rejected by Apple.

Supported Platforms

  • Android

Parameters

  • success: Success callback function [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

ble.showBluetoothSettings();

enable

Enable Bluetooth on the device.

ble.enable(success, failure);
// Or using await with promises
ble.withPromises.enable();

Description

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.

Supported Platforms

  • Android

Parameters

  • success: Success callback function, invoked if the user enabled Bluetooth.
  • failure: Error callback function, invoked if the user does not enabled Bluetooth.

Quick Example

ble.enable(
    function () {
        console.log('Bluetooth is enabled');
    },
    function () {
        console.log('The user did *not* enable Bluetooth');
    }
);

readRSSI

Read the RSSI value on the device connection.

ble.readRSSI(device_id, success, failure);

Description

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

Parameters

  • device_id: device identifier
  • success: Success callback function, invoked with the RSSI value (as an integer)
  • failure: Error callback function, invoked if there is no current connection or if there is an error reading the RSSI.

Quick Example

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

connectedPeripheralsWithServices

Find the connected peripherals offering the listed service UUIDs.

ble.connectedPeripheralsWithServices([service], success, failure);

Description

Retreives a list of the peripherals (containing any of the specified services) currently connected to the system. The peripheral list is sent to the success callback. This function wraps CBCentralManager.retrieveConnectedPeripheralsWithServices:

Supported Platforms

  • iOS

Parameters

  • services: List of services to discover
  • success: Success callback function, invoked with a list of peripheral objects
  • failure: Error callback function

peripheralsWithIdentifiers

Find the connected peripherals offering the listed peripheral UUIDs.

ble.peripheralsWithIdentifiers([uuids], success, failure);

Description

Sends a list of known peripherals by their identifiers to the success callback. This function wraps CBCentralManager.retrievePeripheralsWithIdentifiers:

Supported Platforms

  • iOS

Parameters

  • identifiers: List of peripheral UUIDs
  • success: Success callback function, invoked with a list of peripheral objects
  • failure: Error callback function

restoredBluetoothState

Retrieve the CBManager restoration state (if applicable)

ble.restoredBluetoothState(success, failure);
// Or using await with promises
await ble.withPromises.restoredBluetoothState();

Description

Use of this feature requires the BLUETOOTH_RESTORE_STATE variable to be set to true. For more information about background operation, see Background Scanning and Notifications on iOS.

Retrives the state dictionary that iOS State Preservation and Restoration will supply when the application was launched by iOS.

If the application has no state restored, this will return an empty object.

Supported Platforms

  • iOS

Parameters

  • success: Success callback function, invoked with the restored Bluetooth state (if any)
  • failure: Error callback function

list

Lists all peripherals discovered by the plugin due to scanning or connecting since app launch.

ble.list(success, failure);
// Or using await with promises
await ble.withPromises.list();

Description

Sends a list of bonded low energy peripherals to the success callback.

Supported Platforms

  • Android

Parameters

  • success: Success callback function, invoked with a list of peripheral objects
  • failure: Error callback function

bondedDevices

Find the bonded devices.

ble.bondedDevices(success, failure);
// Or using await with promises
await ble.withPromises.bondedDevices();

Description

Sends a list of bonded low energy peripherals to the success callback.

Supported Platforms

  • Android

Parameters

  • success: Success callback function, invoked with a list of peripheral objects
  • failure: Error callback function

l2cap.open

Open an L2CAP channel with a connected peripheral. The PSM is assigned by the peripheral, or possibly defined by the Bluetooth standard.

ble.l2cap.open(device_id, psm, connectCallback, disconnectCallback);
// Or using await with promises
await ble.withPromises.l2cap.open(device_id, psm, disconnectCallback);

Android supports additional arguments in the psm flag to select whether the L2CAP channel is insecure or secure (iOS does this automatically):

ble.l2cap.open(device_id, { psm: psm, secureChannel: true }, connectCallback, disconnectCallback);
// Or using await with promises
await ble.withPromises.l2cap.open(device_id, { psm: psm, secureChannel: true }, disconnectCallback);

Description

An L2CAP channel is a duplex byte stream interface (similar to a network socket) that can be used for much more efficient binary data transfer. This is used in some streaming applications, such as the Bluetooth Object Transfer Service.

The PSM (protocol/service multiplexer) is specified by the peripheral when it opens the channel. Some channels have predefined identifiers controlled by Bluetooth organisation. Apple has also outlined a generic design for PSM exchange. To advertise an L2CAP channel on a specific service, a characteristic with the UUID "ABDD3056-28FA-441D-A470-55A75A52553A" is added to that service, and updated by the peripheral when the L2CAP channel is opened.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • psm or options: Protocol/service multiplexer, specified by the peripheral when the channel was opened. Can be an object which includes a psm key, with an optional secureChannel boolean setting to control whether the channel is encrypted or not (Android-only)
  • connectCallback: Connect callback function, invoked when an L2CAP connection is successfully opened
  • disconnectCallback: Disconnect callback function, invoked when the L2CAP stream closes or an error occurs.

Supported Platforms

  • iOS
  • Android (>= 10)

l2cap.close

Close an L2CAP channel.

ble.l2cap.close(device_id, psm, success, failure);
// Or using await with promises
await ble.withPromises.l2cap.close(device_id, psm);

Description

Closes an open L2CAP channel with the selected device. All pending reads and writes are aborted.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • psm: Protocol/service multiplexer, specified by the peripheral when the channel was opened
  • success: Success callback function that is invoked when the stream is closed successfully. [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Supported Platforms

  • iOS
  • Android (>= 10)

l2cap.receiveData

Receive data from an L2CAP channel.

ble.l2cap.receiveData(device_id, psm, dataCallback);

Description

Sets the function to be called whenever bytes are received on the L2CAP channel. This function will be used as long as the L2CAP connection remains open.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • psm: Protocol/service multiplexer, specified by the peripheral when the channel was opened
  • dataCallback: Data processing function that is invoked when bytes are received from the peripheral

Supported Platforms

  • iOS
  • Android (>= 10)

l2cap.write

Write data to an L2CAP channel.

ble.l2cap.write(device_id, psm, data, success, failure);
// Or using await with promises
await ble.withPromises.l2cap.write(device_id, psm, data);

Description

Writes all data to an open L2CAP channel. If the data exceeds the available space in the transmit buffer, the data will be automatically sent in chunks as space becomes available. The success callback is called only once after all the supplied bytes have been written to the transmit stream.

Parameters

  • device_id: UUID or MAC address of the peripheral
  • psm: Protocol/service multiplexer, specified by the peripheral when the channel was opened
  • data: Data to write to the stream
  • success: Success callback function that is invoked after all bytes have been written to the stream [optional]
  • failure: Error callback function, invoked when error occurs [optional]

Supported Platforms

  • iOS
  • Android (>= 10)

Peripheral Data

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"
                }
            ]
        }
    ]
}

Advertising Data

Bluetooth advertising data is returned in when scanning for devices. The 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.

To get consistent advertising data payloads across platforms, you can use the ble-central-advertisements module.

Android

{
    "name": "demo",
    "id": "00:1A:7D:DA:71:13",
    "advertising": ArrayBuffer,
    "rssi": -37
    "connectable":"true" /*Only on Android >= API Level 26*/
}

Convert the advertising info to a Uint8Array for processing. var adData = new Uint8Array(peripheral.advertising). You application is responsible for parsing all the information out of the advertising ArrayBuffer using the GAP type constants. For example to get the service data from the advertising info, I parse the advertising info into a map and then get the service data to retrieve a characteristic value that is being broadcast.

iOS

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": "15B4F1C5-C9C0-4441-BD9F-1A7ED8F7A365",
    "advertising": {
        "kCBAdvDataLocalName": "demo",
        "kCBAdvDataManufacturerData": {}, // arraybuffer data not shown
        "kCBAdvDataServiceUUIDs": [
            "721b"
        ],
        "kCBAdvDataIsConnectable": true,
        "kCBAdvDataServiceData": {
            "BBB0": {}   // arraybuffer data not shown
        },
    },
    "rssi": -61
}

Some of the values such as kCBAdvDataManufacturerData are ArrayBuffers. The data won't print out, but you can convert it to bytes using new Uint8Array(peripheral.advertisting.kCBAdvDataManufacturerData). Your application is responsible for parsing and decoding any binary data such as kCBAdvDataManufacturerData or kCBAdvDataServiceData.

function onDiscoverDevice(device) {
    // log the device as JSON
    console.log('Found Device', JSON.stringify(device, null, 2));

    // on iOS, print the manufacturer data if it exists
    if (device.advertising && device.advertising.kCBAdvDataManufacturerData) {
        const mfgData = new Uint8Array(device.advertising.kCBAdvDataManufacturerData);
        console.log('Manufacturer Data is', mfgData);
    }
}

ble.scan([], 5, onDiscoverDevice, onError);

Browser

Chrome

Enable: chrome://flags/#enable-experimental-web-platform-features and chrome://flags/#enable-web-bluetooth-new-permissions-backend

Scan must be initiated from a user action (click, touch, etc).

Typed Arrays

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

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.

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

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.

Additionally, iOS state restoration should be enabled if long-running scans or connects should be restarted after the phone is rebooted or the app is suspended by iOS. See iOS restore state for the details and limitations of this feature.

To activate iOS state restoration, set the BLUETOOTH_RESTORE_STATE to true when adding the plugin to the project:

--variable BLUETOOTH_RESTORE_STATE=true

By default, the app id (otherwise known as the bundle identifier) will be used as the iOS restore identifier key. This can be overridden by setting the variable to the desired key directly. For example:

--variable BLUETOOTH_RESTORE_STATE=my.custom.restoration.identifier.key

It's important to note that iOS will not automatically relaunch an application under some conditions. For a detailed list of these conditions, see the iOS Technical QA on the subject.

Testing the Plugin

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

Release process

Pre-release

  1. npm version prepatch --preid=alpha
  2. Align plugin.xml version with npm version
  3. npm publish --tag alpha

Release

  1. npm version patch
  2. npm publish

Release (slim)

  1. git merge master
  2. Align package.json and plugin.xml versions
  3. npm publish --tag slim

Nordic DFU

If you need Nordic DFU capability, Tomรกลก Bedล™ich has a fork of this plugin that adds an updateFirmware() method that allows users to upgrade nRF5x based chips over the air. https://github.com/fxe-gear/cordova-plugin-ble-central

License

Apache 2.0

Feedback

Try the code. If you find an problem or missing feature, file an issue or create a pull request.

Other Bluetooth Plugins

cordova-plugin-ble-central's People

Contributors

batcoder avatar cbolgiano avatar chris-armstrong avatar ddugue avatar domvel avatar don avatar doug-a-brunner avatar favnec5 avatar fudom avatar gargamil avatar jnoel-leviton avatar joargjersund avatar joeferner avatar jospete avatar jplourenco avatar kellycampbell avatar mandrade-digmap avatar mebrunet avatar motla avatar peacepan avatar peitschie avatar petrometro avatar riccardodegan-geekcups avatar rrharvey avatar samvimes01 avatar surajpindoria avatar tiagoblackcode avatar timburke avatar timkim avatar wynout 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

cordova-plugin-ble-central's Issues

iOS should return advertising info in scan data

iOS should return advertising info in the scan data. iOS doesn't allow access to raw advertising data so advertising info should be returned as a dictionary on both platforms or iOS should flatten back into bytes.

ipad unrecognized selector sent to instance issue while doing Scan

Hello,
I am doing a project where we are connecting to our custom device and trying to communicate over BLE. We have done succesful round of implementation and test using your plugin with Android.
Now I have to test same with ios.
I build and installed same application for ios. Now it is giving me error for scan itself.
console.log("Testing plugin");
$scope.status = "Searching...";
ble.scan([], 5, function(devices)
{
//console.log("FOunddddddddddd "+JSON.stringify(devices));
$scope.devices_.push(devices);
console.log("Address "+devices.name);
$scope.$apply();
}, failure);

THe error is

-[CBUUID UUIDString]: unrecognized selector sent to instance 0x176cf160

2015-02-19 11:40:53.930 ZenRelaxie[219:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CBUUID UUIDString]: unrecognized selector sent to instance 0x176cf160'

*** First throw call stack:

(0x30bd8f4b 0x3b36f6af 0x30bdc8e7 0x30bdb1cb 0x30b2a4d8 0x9efd7 0x9eb21 0x9b7ff 0x308ff8eb 0x308ffda7 0x30907ba3 0x3b852d1b 0x3b852d07 0x3b85978d 0x30ba3819 0x30ba20ed 0x30b0cc27 0x30b0ca0b 0x35800283 0x333b0049 0x9672b 0x3b877ab7)

libc++abi.dylib: terminating with uncaught exception of type NSException

At location

// Create a new list of Service UUIDs as Strings instead of CBUUIDs
NSMutableArray *serviceUUIDs = [dict objectForKey:CBAdvertisementDataServiceUUIDsKey];
NSMutableArray *serviceUUIDStrings;
if (serviceUUIDs) {
    serviceUUIDStrings = [[NSMutableArray alloc] initWithCapacity:serviceUUIDs.count];

    for (CBUUID *uuid in serviceUUIDs) {
        [serviceUUIDStrings addObject:[uuid UUIDString]]; //HEre is the breakpoint
    }

    // replace the UUID list with list of strings
    [dict removeObjectForKey:CBAdvertisementDataServiceUUIDsKey];
    [dict setObject:serviceUUIDStrings forKey:CBAdvertisementDataServiceUUIDsKey];

}

Can you pelase help me?
I am a newbie to ios. So if i am missing any step please tell me.

Thanks,
Regards
Shraddha

Unable to connect to devices

Hi @don, I have been trying to get your plugin to work for a few days now but I'm getting no joy.

I'm developing using Ionic on a Motorola G running KitKat 4.4.4 and ble.scan([], 5, success, fail) returns the results and I have even tried

ble.scan([], 5, function(dev) { 
  console.log(dev.name+' : '+dev.rssi+'dBm : '+dev.id+' : '+angular.equals(dev.id, 'D0:39:72:F1:E9:72')); }, 
function(err) { 
  $scope.onError(err); 
});

which returns true but connect always returns 'Peripheral D0:39:72:F1:E9:72 not found'

Any ideas?

My code for reference here

Fix for devices that fail during characteristic notification

I've been using a BLE pedometer that has issues. You ask it for its data, and it starts streaming notifications. If there is a lot of data (more than a couple of seconds of transfer time), it just stops and dies.

In Android 5.1 there is new API, "gatt.requestConnectionPriority (1);", and I change the Peripheral.java/writeCharacteristic() method and call this just before it writes the characteristic, the device works perfectly well -- no data loss, doesn't stop, doesn't hang. For some reason, this is essential, and I think a good fix (or, althernatively, add it as some sort of configuration setting).

Can't Import

I can't import to my workspace through eclipse?

Compatibility with older device (4.2 or less)

Hi, I want to create an APP that can use BLE but if not is possible, connect to my board with BT 2.0 (my board is BLE and BT 2.0 compatible).But, I want use that APP with gingerbread. When I modify the json to write the androidManifest.xml to do compatible with gingerbread, the plugin doesn't work in my Sony Xpheria Z.

I'm sorry, my english is very bad....

version problem

I'm getting this error:

cordova: 3.0.0, failed version requirement: >=3.1.0

however, I'm using

cordova -version 3.6.3-0.2.13

Thoughts?

isConnected, how does it work?

When I read the documentation about isConnected, I got the feeling that the command is used to check if there is a established connection between the device running the code (my phone, android) and the other device (arduino with BLE shield) that you have to provide a "device_id" for.

I can connect to my arduino just fine, and by looking in the logs I can see that there is a connection established, BUT when I call isConnected with the MAC address, it is returning a string JSON error.

Looking at the ble.js, it seems like the device_id isn't even used at all in the exec method.

I think this results in that the String macAddress = args.getString(0); in BLECentralPlugin.java is just an empty array ([]).

Is this by design, or a bug, or do I miss something here?

Issues with Cordova 5.0.0

The BLE scanning code that I had which was more or less the same as the code in ionic-ble doesn't seem to work anymore, and when I cloned the ionic-ble repo, nothing shows up anymore as well. Any thoughts on what happened?

Indicate issue

Hello,
I am developing an application with Ionic Cordova. We have our custom eval kit. It has 6 characteristics which i can read and write. But I cannot register to indicate for particular characteristic. I am not getting success callback it is giving invalid action.
'IndicateUUID':'xxxx',
ble.indicate( device.id, UUIDs.ServiceUUID, UUIDs.IndicateUUID, indicateSuccessCallBack, failure);

Please help.

Regards,
Shraddha

CDVCommandStatus_NO_RESULT calls failure callback on iOS

CDVCommandStatus_NO_RESULT calls failure callback on iOS for Cordova 4.1 and 4.2. This means you can see both failure and success callbacks being called when there is no failure.

This is a known issue that should be fixed in future Cordova releases.

I'll also work to remove CDVCommandStatus_NO_RESULT from this plugin.

Until this is fixed, the work-around is to use Cordova 4.0.0.

npm install -g [email protected]

How to get UUID, major, minor in scan result?

Thanks this plugin, everything works well on IOS devices.

But I can't get enough info in callback returned data. I develop mobile app using cordova, don't know much about Objective C, could anyone tell me what can I do (I guess it is necessary to change plugin Objective C codes, right?) to get UUID, major, minor in the result of ble.scan(services, seconds, success, failure);?

And after pair with iBeacon device, ble.read() only return read status, not the characteristic value. What codes should I change to return the value or do I misuse it?

I just simply use the example code:
==================== scan (after connect successfully) =====================
ble.scan([], 5, scanSuccess, scanFail);
function scanSuccess(data){
alert("scanSuccess: " + JSON.stringify(data));
}
function scanFail(data){
alert("scanFail: " + JSON.stringify(data));
}
==================== read (after write password successfully) ================
ble.read(device_id, service_uuid, characteristic_uuid, readSuccess, readFailure);
function readSuccess(data){
alert("readSuccess: " + JSON.stringify(data));
}
function readFailure(data){
alert("readFailure: " + JSON.stringify(data));
}

Any help is much appreciated.

The reason I need more info is I need to develop an app to auto configure the beacon:

After scan, generate a beacon list, click one beacon:
if its characteristics are default value, auto write them
if all its characteristic (uuid, major, minor) are written well, call web service to update database

No stopScan method

What if the user wants to stop the scanning? I think it's not implimented in the plugin.

Device getting disconnected

Hello,
I want to keep the ble device connected so that i can get notifications. But if there is no action then device gets disconnected. So how do I implement this?

Regards,
Shraddha

Getting Blood Pressure Measurement (Service: 1810)

Hi everybody,

I'm trying to get the BPM values from "A&D" device (model UA-651BLE).

The service to get that data is 1810 and the characteristic is 2A35. I used the battery example as a base to get this values, but I don't know why is always failed (print "Read failed"). I tried to get this data in pair mode (holding the power button until shows "Pr" in the display) or immediately after getting my BPM.

My code (after scanning and connecting):

var onReadSuccess = function(data) {
    var a = new Uint8Array(data);
    console.log('onReadSuccess', data, a);
}

var onReadFail = function(error) {
    console.log('onReadFail', error);
}

ble.read('7C:66:9D:88:B2:B8', '1810', '2a35', onReadSuccess, onReadFail);

I saw other apps that they could get this data from my device, but I think they do it natively.

Can anyone helps me?

Thanks.

Scanning 2x crashes app

Scanning 2x crashes app

2014-09-22 17:43:38.398 SensorTag[1021:281302] Finished load of: file:///private/var/mobile/Containers/Bundle/Application/F63F7A60-8205-4249-A8FC-642219CDCCA1/SensorTag.app/www/index.html
2014-09-22 17:43:38.480 SensorTag[1021:281302] scan
2014-09-22 17:43:39.986 SensorTag[1021:281302] scan
2014-09-22 17:43:43.482 SensorTag[1021:281302] stopScanTimer
2014-09-22 17:43:44.987 SensorTag[1021:281302] stopScanTimer
2014-09-22 17:43:44.994 SensorTag[1021:281302] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]: nil argument'
*** First throw call stack:
(0x185e3a084 0x1964180e4 0x185e39fc4 0x186c7ae50 0x186c7ad24 0x1000e83e8 0x1000e8548 0x1000f0de0 0x186d07818 0x185df2210 0x185df1ec0 0x185def90c 0x185d1d664 0x18ee5f5a4 0x18a622984 0x1000edaa4 0x196a86a08)
libc++abi.dylib: terminating with uncaught exception of type NSException

Please remove tags 0.0.1 and 0.0.2

Hi Don,

Sorry for the somewhat silly request, but can you remove this and this tag from your repo?

Or rename them to something like alpha-1 and alpha-2?

The problem we're having is that this plugin is linked to from Telerik AppBuilder which doesn't like the fact that in those two tagged versions the plugin.xml file is not in the root of the repo. You changed that since.

Thanks in advance!
Eddy

ReferenceError: ble is not defined

I didn't see a relevant previous issue, so I'm opening one.

I have an ionic project, and installed the plugin with the command

$ cordova plugin add com.megster.cordova.ble

The plugin seems correctly installed, but upon attempting to call ble.scan, I get:

ReferenceError: ble is not defined

Is there an installation step after the CLI installation that I'm missing?

Thanks in advance

Android issues: disconnect with Android 4.4.2 and multiple device communication

Hi there,
I'm developing an app for controlling a BLE lamp. The plugin works fine with iOS (also allowing multiple devices being connected and controlled), but has some troubles with Android. In particular:

  • testing it with a Samsung S4 with Android 4.4.2, the app isn't able to safely disconnect from a peripheral (the app crashes when trying to disconnect);
  • testing it with a Sony Xperia L with Cyanogenmod12 unofficial (just because it was the only way to enable BLE on the Sony Xperia L), everything seems to work fine but writing to multiple connected device: as soon as the app tries to write to more than a single device, just one receives the message, and the others fall in a 'not-connected not-disconnected' state.

I'm trying to figure out which are the problems (maybe the Phonegap code itself is bugged), and I'm still in a preliminary stage of development, but just to be sure, are you aware of some kind of pitfalls that could explain this behavior?

Thanks for all the work you have done!
alessandro

PGB shows no plugin

Hi Don, Added the gap:plugin line to config.sys (and using the chat example for testing), but PGB shows no plugins. Is there something else I need to do here?
Thanks, John

PhoneGap Build

Hi Don, looks like you've been busy!
Will you be submitting this to PhoneGap Build?
-John

ios writeWithoutResponse not working

Hello,
I am trying to test application which is running in Android same one on ios 8. Here connect is working and read is working. But write is not working. It is not giving error and on hardware side nothing is getting recieved. is there any difference for write command in android and ios?
var configData = new Uint8Array(1);
configData[0] = Params.IValue;
ble.writeWithoutResponse(DeviceID, UUIDs.ServiceUUID, UUIDs.VUUID, configData.buffer, onParamWriteSuccess, failure);

I am not getting failure in ios. But getting success log. But on hardware side i checked from putty nothing is getting logged for write. Connect is working fine. And Read as well.

Regards,
Shraddha

ble.isEnabled

add ble.isEnabled(success, failure)

call success when enabled, failure when disabled

add another method to enable Bluetooth or send users to the preferences screen

StopNotification on Android

Does stopNotification work on Android? I called it and received an "invalid action." I looked quickly at the source and it seems that this action is not present in the .java source.

Much appreciated.

Advertising data is empty on Android + Fix

iOS works like a charm but on Android 5 the "advertising" field is empty.
Fix in ble.js, line 40

function convertToNativeJS(object) {
    Object.keys(object).forEach(function (key) {
        var value = massageMessageNativeToJs(object[key]);
        object[key] = value;
        if (typeof(value) === 'object') {
            convertToNativeJS(value);
        }
    });
}

Explanation

function convertToNativeJS(object) {
    Object.keys(object).forEach(function (key) {
        var value = object[key];
        object[key] = massageMessageNativeToJs(value);
        if (typeof(value) === 'object') {
            convertToNativeJS(value);
        }
    });
}
  1. var value = object[key];
  2. object[key] = massageMessageNativeToJs(value);
  3. if (typeof(value) === 'object')

The variable "value" gets never updated. So the "Base64 ArrayBuffer" is processed twice and is unusable after that.

BLE Connect on Samsung Galaxy S5

I am trying to connect to a BLE module (OLP 421) using my Samsung Galaxy S5.
While it can discover it, it is not able connect to it. It doesn't fail but doesn't call the success callback.

A bit of research has suggested this could be the issue: http://stackoverflow.com/questions/20839018/while-connecting-to-ble113-from-android-4-3-is-logging-client-registered-waiti

I am not skilled enough to work out if this is the issue so some help or suggestions are appreciated.

Here is the log file:

    12-02 12:07:09.683: D/BLEPlugin(20745): action = isEnabled
    12-02 12:07:09.683: D/BLEPlugin(20745): action = scan
    12-02 12:07:09.683: D/BluetoothAdapter(20745): startLeScan(): [Ljava.util.UUID;@42b02068
    12-02 12:07:09.973: D/BluetoothAdapter(20745): onClientRegistered() - status=0 clientIf=7
    12-02 12:07:09.983: W/PluginManager(20745): THREAD WARNING: exec() call to BLE.scan blocked the main thread for 295ms. Plugin should use CordovaInterface.getThreadPool().
    12-02 12:07:10.303: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:10.333: D/CordovaLog(20745): file:///android_asset/www/js/bluetooth.js: Line 20 : {"advertising":{},"id":"00:12:F3:23:96:F7","rssi":-53,"name":"Bluetooth Device"}
    12-02 12:07:10.333: I/chromium(20745): [INFO:CONSOLE(20)] "{"advertising":{},"id":"00:12:F3:23:96:F7","rssi":-53,"name":"Bluetooth Device"}", source: file:///android_asset/www/js/bluetooth.js (20)
    12-02 12:07:10.353: D/BLEPlugin(20745): action = connect
    12-02 12:07:10.363: D/BluetoothGatt(20745): connect() - device: 00:12:F3:23:96:F7, auto: false
    12-02 12:07:10.363: D/BluetoothGatt(20745): registerApp()
    12-02 12:07:10.363: D/BluetoothGatt(20745): registerApp() - UUID=28406036-b3d2-4efd-9f50-062e298c6a63
    12-02 12:07:10.363: I/BluetoothGatt(20745): Client registered, waiting for callback
    12-02 12:07:10.373: D/BluetoothGatt(20745): onClientRegistered() - status=0 clientIf=8
    12-02 12:07:11.313: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:13.333: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-56
    12-02 12:07:14.333: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-55
    12-02 12:07:15.333: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:16.333: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:17.333: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:17.383: E/ViewRootImpl(20745): sendUserActionEvent() mView == null
    12-02 12:07:18.343: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:20.353: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:21.343: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:22.353: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:25.373: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:26.363: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-51
    12-02 12:07:27.383: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:29.393: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-55
    12-02 12:07:30.403: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:31.393: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:32.403: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:33.423: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-53
    12-02 12:07:34.413: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-54
    12-02 12:07:35.423: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-52
    12-02 12:07:39.433: D/BluetoothAdapter(20745): onScanResult() - Device=00:12:F3:23:96:F7 RSSI=-51
    12-02 12:07:40.003: D/BLEPlugin(20745): Stopping Scan
    12-02 12:07:40.003: D/BluetoothAdapter(20745): stopLeScan()

rfDuino example not working with BLE Shield

Good Day,

I use the rfduino example for a BLE shield test: http://wiki.aprbrother.com/wiki/BLEShield
I change the service UUID, receiveCharacteristic and sendCharacteristic of the said example but after I uploaded or tested to my Note 5 it re forward me to the first screen after tapping the Disconnect/Connect Button.

Code Details:

var rfduino = {
serviceUUID: "0000FFF0-0000-1000-8000-00805F9B34FB",
receiveCharacteristic: "0000FFF1-0000-1000-8000-00805F9B34FB",
sendCharacteristic: "0000FFF2-0000-1000-8000-00805F9B34FB"
};

function parseAdvertisingData(bytes) {
var length, type, data, i = 0, advertisementData = {};

while (length !== 0) {

   length = bytes[i] & 0xFFF1;         
    i++;

    type = bytes[i] & 0xFFF2;
    i++;    

    data = bytes.slice(i, i + length - 2); // length includes type and length
    i += length - 2;  // move to end of data
    i++;

    advertisementData[type] = data;
}
return advertisementData;

}

// RFduino advertises the sketch its running in the Manufacturer field 0xFF
// RFduino provides a UART-like service so all sketchs look the same
var getRFduinoService = function(scanRecord) {
var ad = parseAdvertisingData(scanRecord),
mfgData = ad[0xFFF],
service;

if (mfgData) {
  // ignore 1st 2 bytes of mfg data
  service = bytesToString(mfgData.slice(2));
  return service;      
} else {
  return "";
}

};

Is there any other way to skip the parseAdvertisingData function or send any serial command to Arduino without the parseAdvertisingData?

Thanks in advance and respectfully,
Jc

Distance.

Is there a way to get the distance from the mobile device to the beacon?

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.