Need help upgrading to Ionic Framework 4.0? Get assistance with our Enterprise Migration Services EXPLORE NOW

BluetoothLE

Improve this doc

This plugin has the most complete implementation for interacting with Bluetooth LE devices on Android, iOS and partially Windows. It's a wrap around randdusing/cordova-plugin-bluetoothle cordova plugin for Ionic. It supports peripheral and central modes and covers most of the API methods available on Android and iOS.

Repo: https://github.com/randdusing/cordova-plugin-bluetoothle

Installation

  1. Install the Cordova and Ionic Native plugins:
    $ ionic cordova plugin add cordova-plugin-bluetoothle
    $ npm install --save @ionic-native/bluetooth-le@4
    
  2. Add this plugin to your app's module

Supported platforms

Usage

import { BluetoothLE } from '@ionic-native/bluetooth-le';


constructor(public bluetoothle: BluetoothLE, public plt: Platform) {

 this.plt.ready().then((readySource) => {

   console.log('Platform ready from', readySource);

   this.bluetoothle.initialize().then(ble => {
     console.log('ble', ble.status) // logs 'enabled'
   });

  });
}

Instance Members

initialize Initialize Bluetooth on the device(params)

Param Type Details
params InitParams

Optional

Returns: Promise.<{status: ('enabled'|'disabled')}> The callback that is passed initialize status (enabled/disabled)

enable (Android) Enable Bluetooth on the device. Android support only()

Returns: Promise<{ status: boolean }>

disable (Android) Disable Bluetooth on the device. Android support only()

Returns: void

<a class="anchor" name="getAdapterInfo (Android) Retrieve useful information such as the address, name, and various states (initialized, enabled, scanning, discoverable). This can be very useful when the general state of the adapter has been lost, and we would otherwise need to go through a series of callbacks to get the correct state (first initialized, then enabled, then isScanning, and so forth). The result of this method allows us to take business logic decisions while avoiding a large part of the callback hell. Currently the discoverable state does not have any relevance because there is no "setDiscoverable" functionality in place. That may change in the future." href="#getAdapterInfo (Android) Retrieve useful information such as the address, name, and various states (initialized, enabled, scanning, discoverable). This can be very useful when the general state of the adapter has been lost, and we would otherwise need to go through a series of callbacks to get the correct state (first initialized, then enabled, then isScanning, and so forth). The result of this method allows us to take business logic decisions while avoiding a large part of the callback hell. Currently the discoverable state does not have any relevance because there is no "setDiscoverable" functionality in place. That may change in the future."></a>getAdapterInfo (Android) Retrieve useful information such as the address, name, and various states (initialized, enabled, scanning, discoverable). This can be very useful when the general state of the adapter has been lost, and we would otherwise need to go through a series of callbacks to get the correct state (first initialized, then enabled, then isScanning, and so forth). The result of this method allows us to take business logic decisions while avoiding a large part of the callback hell. Currently the discoverable state does not have any relevance because there is no "setDiscoverable" functionality in place. That may change in the future.()

Returns: Promise<AdapterInfo>

startScan Scan for Bluetooth LE devices. Since scanning is expensive, stop as soon as possible. The Cordova app should use a timer to limit the scan interval. Android API >= 23 requires ACCESS_COARSE_LOCATION permissions to find unpaired devices. Permissions can be requested by using the hasPermission and requestPermission functions. Android API >= 23 also requires location services to be enabled. Use isLocationEnabled to determine whether location services are enabled. If not enabled, use requestLocation to prompt the location services settings page.(params)

Param Type Details
params ScanParams

Scan params

Returns: Observable.<{status: ScanStatus}>

stopScan Stop scan for Bluetooth LE devices. Since scanning is expensive, stop as soon as possible The app should use a timer to limit the scanning time.()

Returns: Promise<{status: 'scanStopped'}>

<a class="anchor" name="retrieveConnected Retrieved paired Bluetooth LE devices. In iOS, devices that are "paired" to will not return during a normal scan. Callback is "instant" compared to a scan." href="#retrieveConnected Retrieved paired Bluetooth LE devices. In iOS, devices that are "paired" to will not return during a normal scan. Callback is "instant" compared to a scan."></a>retrieveConnected Retrieved paired Bluetooth LE devices. In iOS, devices that are "paired" to will not return during a normal scan. Callback is "instant" compared to a scan.(An)

Param Type Details
An { services: string[] }

array of service IDs to filter the retrieval by. If no service IDs are specified, no devices will be returned.

Returns: Promise<{ devices: DeviceInfo[] }>

bond (Android) Bond with a device. The device doesn't need to be connected to initiate bonding. Android support only.(params)

Param Type Details
params { address: string }

The address/identifier provided by the scan's return object

Returns: Observable.<{status: DeviceInfo}> success: The first success callback should always return with status == bonding. If the bond is created, the callback will return again with status == bonded. If the bonding popup is canceled or the wrong code is entered, the callback will return again with status == unbonded. error: The callback that will be triggered when the bond operation fails

unbond (Android) Unbond with a device. The device doesn't need to be connected to initiate bonding. Android support only.(params)

Param Type Details
params {address: string}

The address/identifier

Returns: Promise<{ status: DeviceInfo }> success: The success callback should always return with status == unbonded, that is passed with device object error: The callback that will be triggered when the unbond operation fails

connect Connect to a Bluetooth LE device(connectSuccess, connectError, params, params)

Param Type Details
connectSuccess

The success callback that is passed with device object

connectError

The callback that will be triggered when the connect operation fails

params

The address/identifier

params {address: string, autoConnect: boolean}

Returns: Observable.<{status: DeviceInfo}> success: device object with status error: The callback that will be triggered when the unbond operation fails

reconnect Reconnect to a previously connected Bluetooth device(params)

Param Type Details
params {address: string}

The address/identifier

Returns: Observable.<{status: DeviceInfo}>

disconnect Disconnect from a Bluetooth LE device. Note: It's simpler to just call close(). Starting with iOS 10, disconnecting before closing seems required!(params)

Param Type Details
params {address: string}

The address/identifier

Returns: Promise<{ status: DeviceInfo }>

close Close/dispose a Bluetooth LE device. Prior to 2.7.0, you needed to disconnect to the device before closing, but this is no longer the case. Starting with iOS 10, disconnecting before closing seems required!(params)

Param Type Details
params { address: string }

The address/identifier

Returns: Promise<{ status: DeviceInfo }>

discover Discover all the devices services, characteristics and descriptors. Doesn't need to be called again after disconnecting and then reconnecting. If using iOS, you shouldn't use discover and services/characteristics/descriptors on the same device. There seems to be an issue with calling discover on iOS8 devices, so use with caution. On some Android versions, the discovered services may be cached for a device. Subsequent discover events will make use of this cache. If your device's services change, set the clearCache parameter to force Android to re-discover services.(params)

Param Type Details
params { address: string, clearCache: boolean }

The address/identifier

Returns: Promise<{ device: Device }> success: device object (contains array of service objects) error: The callback that will be triggered when the unbond operation fails

services (iOS) Discover the device's services. Not providing an array of services will return all services and take longer to discover. iOS support only.(params)

Param Type Details
params {address: string, services: string[]}

Returns: Promise<{ services: Services }>

characteristics (iOS) Discover the service's characteristics. Not providing an array of characteristics will return all characteristics and take longer to discover. iOS support only.(params)

Param Type Details
params CharacteristicParams

Characteristic params

Returns: Promise<{ characteristics: Characteristics }> The service id and an Array of characteristics

descriptors (iOS) Discover the characteristic's descriptors. iOS support only.(params)

Param Type Details
params DescriptorParams

Returns: Promise<{ descriptors: Descriptors }>

read Read a particular service's characteristic once(params)

Param Type Details
params DescriptorParams

Returns: Promise<OperationResult>

subscribe Subscribe to a particular service's characteristic. Once a subscription is no longer needed, execute unsubscribe in a similar fashion. The Client Configuration descriptor will automatically be written to enable notification/indication based on the characteristic's properties.(params)

Param Type Details
params DescriptorParams

Returns: Observable.<{result: OperationResult}>

unsubscribe Unsubscribe to a particular service's characteristic.(params)

Param Type Details
params DescriptorParams

Returns: Promise<UnsubscribeResult>

write (limitation on iOS, read below) Write a particular service's characteristic Note: no callback will occur on write without response on iOS.(params)

Param Type Details
params WriteCharacteristicParams

Returns: Promise<OperationResult>

write (limitation on iOS, read below) Write Quick / Queue, use this method to quickly execute write without response commands when writing more than 20 bytes at a time. Note: no callback will occur on write without response on iOS.(params)

Param Type Details
params WriteCharacteristicParams

Returns: Promise<OperationResult>

readDescriptor Read a particular characterist's descriptor(params)

Param Type Details
params OperationDescriptorParams

Returns: Promise<DescriptorResult>

writeDescriptor Write a particular characteristic's descriptor. Unable to write characteristic configuration directly to keep in line with iOS implementation. Instead use subscribe/unsubscribe, which will automatically enable/disable notification.(params)

Param Type Details
params WriteDescriptorParams

Returns: Promise<DescriptorResult>

rssi Read RSSI of a connected device. RSSI is also returned with scanning.(params)

Param Type Details
params { address: string }

Returns: Promise<{ rssi: RSSI }>

mtu (Android, Android 5+) Set MTU of a connected device. Android only.(params)

Param Type Details
params { address: string, mtu: number }

Returns: Promise<{ mtu: MTU }>

requestConnectionPriority (Android, Android 5+) Request a change in the connection priority to improve throughput when transfer large amounts of data via BLE. Android support only. iOS will return error.(params)

Param Type Details
params { address: string, connectionPriority: ConnectionPriority }

Returns: Promise<DeviceInfo>

isInitialized Determine whether the adapter is initialized. No error callback. Returns true or false()

Returns: Promise<{ isInitialized: boolean }>

isEnabled Determine whether the adapter is enabled. No error callback()

Returns: Promise<{ isEnabled: boolean }>

isScanning Determine whether the adapter is scanning. No error callback. Returns true or false()

Returns: Promise<{ isScanning: boolean }>

isBonded (Android) Determine whether the device is bonded or not, or error if not initialized. Android support only.(params)

Param Type Details
params { address: string }

Returns: Promise<BondedStatus>

wasConnected Determine whether the device was connected, or error if not initialized.(params)

Param Type Details
params { address: string }

Returns: Promise<PrevConnectionStatus>

isConnected Determine whether the device is connected, or error if not initialized or never connected to device(params)

Param Type Details
params { address: string }

Returns: Promise<CurrConnectionStatus>

isDiscovered Determine whether the device's characteristics and descriptors have been discovered, or error if not initialized or not connected to device.(params)

Param Type Details
params { address: string }

Returns: Promise<DiscoverStatus>

hasPermission (useful only for Android 6+ / API 23) Determine whether coarse location privileges are granted since scanning for unpaired devices requires it in Android API 23()

Returns: Promise<{ hasPermission: boolean }>

requestPermission (useful only for Android 6+ / API 23) Request coarse location privileges since scanning for unpaired devices requires it in Android API 23. Will return an error if called on iOS or Android versions prior to 6.0.()

Returns: Promise<{ requestPermission: boolean }>

isLocationEnabled (useful only for Android 6+ / API 23) Determine if location services are enabled or not. Location Services are required to find devices in Android API 23()

Returns: Promise<{ isLocationEnabled: boolean }>

requestLocation (useful only for Android 6+ / API 23) Prompt location services settings pages. requestLocation property returns whether location services are enabled or disabled. Location Services are required to find devices in Android API 23.()

Returns: Promise<{ requestLocation: boolean }>

initializePeripheral Initialize Bluetooth on the device. Must be called before anything else. Callback will continuously be used whenever Bluetooth is enabled or disabled.(params)

Param Type Details
params InitPeripheralParams

Optional

Returns: Observable<InitializeResult>

addService Add a service with characteristics and descriptors. If more than one service is added, add them sequentially(params)

Param Type Details
params { service: string, characteristics: Characteristic[] }

Returns: Promise<{ service: string, status: Status }>

removeService Remove a service(params)

Param Type Details
params { service: string }

Returns: Promise<{ service: string, status: Status }>

removeAllServices Remove all services()

Returns: Promise<{ status: Status }>

startAdvertising (different behavior on Android/iOS, read below) Start advertising as a BLE device. Note: This needs to be improved so services can be used for both Android and iOS. On iOS, the advertising devices likes to rename itself back to the name of the device, i.e. Rand' iPhone(params)

Param Type Details
params AdvertisingParams

Returns: Promise<{ status: Status }>

stopAdvertising Stop advertising()

Returns: Promise<{ status: Status }>

isAdvertising Determine if app is advertising or not.()

Returns: Promise<{ status: boolean }>

respond Respond to a read or write request(params)

Param Type Details
params RespondParams

Returns: Promise<{ status: Status }>

notify Update a value for a subscription. Currently all subscribed devices will receive update. Device specific updates will be added in the future. If sent equals false in the return value, you must wait for the peripheralManagerIsReadyToUpdateSubscribers event before sending more updates.(params)

Param Type Details
params NotifyParams

Returns: Promise<{ status: Status, sent: boolean }>

encodedStringToBytes Helper function to convert a base64 encoded string from a characteristic or descriptor value into a uint8Array object(str)

Param Type Details
str string

Returns: Uint8Array

bytesToEncodedString Helper function to convert a unit8Array to a base64 encoded string for a characteric or descriptor write(bytes)

Param Type Details
bytes Uint8Array

Returns: string

stringToBytes Helper function to convert a string to bytes(value)

Param Type Details
value string

Returns: Uint8Array

bytesToString Helper function to convert bytes to a string.(value)

Param Type Details
value Uint8Array

Returns: string

SCAN_MODE_OPPORTUNISTIC

SCAN_MODE_LOW_POWER

SCAN_MODE_BALANCED

SCAN_MODE_LOW_LATENCY

MATCH_MODE_AGRESSIVE

MATCH_MODE_STICKY

MATCH_NUM_ONE_ADVERTISEMENT

MATCH_NUM_FEW_ADVERTISEMENT

MATCH_NUM_MAX_ADVERTISEMENT

CALLBACK_TYPE_ALL_MATCHES

CALLBACK_TYPE_FIRST_MATCH

CALLBACK_TYPE_MATCH_LOST

API

Native

General