Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@nativescript-community/ble

Connect to and interact with Bluetooth LE peripherals.

ecosystem:NativeScript, NativeScript, iOS, Android, BLE, Bluetooth, Bluetooth LE, Bluetooth Smart, Bluetooth Low Energy, Angular

readme

@nativescript-community/ble

Downloads per month NPM Version

Connect to and interact with Bluetooth LE peripherals.


Table of Contents

Installation

Run the following command from the root of your project:

ns plugin add @nativescript-community/ble

API

Want to dive in quickly? Check out the demo app! Otherwise, mix and match these functions as you see fit:

Prerequisites

Discovery

Connectivity

Interaction

Debugging

isBluetoothEnabled

Reports if bluetooth is enabled.

// require the plugin
import { Bluetooth } from '@nativescript-community/ble';
var bluetooth = new Bluetooth();

bluetooth.isBluetoothEnabled().then(
  function(enabled) {
    console.log("Enabled? " + enabled);
  }
);

Permissions (Android)

On Android >= 6 and < 12 you need to request permissions to be able to interact with a Bluetooth peripheral (when the app is in the background) when targeting API level 23+. You need BLUETOOTH and ACCESS_FINE_LOCATION. You should read the doc here

On android >= 12 you need new permissions. You should read the doc here Note that for BLUETOOTH and BLUETOOTH_ADMIN you don't require runtime permission; adding those to AndroidManifest.xml suffices.

Note that hasLocationPermission will return true when:

  • You're running this on iOS, or
  • You're targeting an API level lower than 23, or
  • You're using a device running Android < 6, or
  • You've already granted permission.
bluetooth.hasLocationPermission().then(
  function(granted) {
    // if this is 'false' you probably want to call 'requestLocationPermission' now
    console.log("Has Location Permission? " + granted);
  }
);

requestLocationPermission

Since plugin version 1.2.0 the startScanning function will handle this internally so it's no longer mandatory to add permission checks to your code.

// if no permission was granted previously this will open a user consent screen
bluetooth.requestLocationPermission().then(
  function(granted) {
    console.log("Location permission requested, user granted? " + granted);
  }
);

enable (Android only)

The promise will be rejected on iOS

// This turns bluetooth on, will return false if the user denied the request.
bluetooth.enable().then(
  function(enabled) {
    // use Bluetooth features if enabled is true 
  }
);

startScanning

A few of the optional params require a bit of explanation:

seconds

Scanning for peripherals drains the battery quickly, so you better not scan any longer than necessary. If a peripheral is in range and not engaged in another connection it usually pops up in under a second. If you don't pass in a number of seconds you will need to manually call stopScanning.

avoidDuplicates

Set this to true if you don't want duplicates with the same serviceUUID reported in "onDiscovered" callback. If true, only the first discovered peripheral with the same serviceUUID will be reported.

skipPermissionCheck

Set this to true if you don't want the plugin to check (and request) the required Bluetooth permissions. Particularly useful if you're running this function on a non-UI thread (ie. a Worker). Relevant on Android only.

filters

It's inefficient to scan for all available Bluetooth peripherals and have them report all services they offer. Moreover on Android if we don't use filters we must have location permissions and have GPS enabled

If you're only interested in finding a heartrate peripheral for instance, pass in service UUID '180d' like this: filters: [{serviceUUID:'180d'}]. If you add 2 or more (comma separated) services then only peripherals supporting ALL those services will match.

Note that UUID's are ALWAYS strings; don't pass integers.

onDiscovered

While scanning the plugin will immediately report back uniquely discovered peripherals.

This function will receive an object representing the peripheral which contains these properties (and types):

  • UUID: string
  • name: string
  • RSSI: number (relative signal strength, can be used for distance measurement)
  • services?: (optional - this is set once connected to the peripheral)
  • manufacturerId?: number (optional)
  • advertismentData?: { localName?:string manufacturerData?: ArrayBuffer; serviceUUIDs?: string[]; txPowerLevel?:number, flags?:number } (optional)
bluetooth.startScanning({
  filters: [{serviceUUID:'180d'}],
  seconds: 4,
  onDiscovered: function (peripheral) {
      console.log("Periperhal found with UUID: " + peripheral.UUID);
  }
}).then(function() {
  console.log("scanning complete");
}, function (err) {
  console.log("error while scanning: " + err);
});

stopScanning

At any time during a scan, being one where you passed in a number or seconds or not, you can stop the scan by calling this function.

You may for instance want to stop scanning when the peripheral you found in startScanning's onDiscovered callback matches your criteria.

bluetooth.stopScanning().then(function() {
  console.log("scanning stopped");
});

connect

Pass in the UUID of the peripheral you want to connect to and once a connection has been established the onConnected callback function will be invoked. This callback will received the peripheral object as before, but it's now enriched with a services property. An example of the returned peripheral object could be:

  peripheral: {
    UUID: '3424-542-4534-53454',
    name: 'Polar P7 Heartrate Monitor',
    RSSI: '-57',
    services: [{    
      UUID: '180d',
      name: 'Heartrate service',
      characteristics: [{
        UUID: '34534-54353-234324-343',
        name: 'Heartrate characteristic',
        properties: {
          read: true,
          write: false,
          writeWithoutResponse: false,
          notify: true
        }
      }]
    }]
  }

Here's the connect function in action with an implementation of onConnected that simply dumps the entire peripheral object to the console:

bluetooth.connect({
  UUID: '04343-23445-45243-423434',
  onConnected: function (peripheral) {
      console.log("Periperhal connected with UUID: " + peripheral.UUID);

      // the peripheral object now has a list of available services:
      peripheral.services.forEach(function(service) {
        console.log("service found: " + JSON.stringify(service));
   });
  },
  onDisconnected: function (peripheral) {
      console.log("Periperhal disconnected with UUID: " + peripheral.UUID);
  }
});

Also note that onDisconnected function: if you try to interact with the peripheral after this event you risk crashing your app.

disconnect

Once done interacting with the peripheral be a good citizen and disconnect. This will allow other applications establishing a connection.

bluetooth.disconnect({
  UUID: '34234-5453-4453-54545'
}).then(function() {
  console.log("disconnected successfully");
}, function (err) {
  // in this case you're probably best off treating this as a disconnected peripheral though
  console.log("disconnection error: " + err);
});

read

If a peripheral has a service that has a characteristic where properties.read is true then you can call the read function to retrieve the current state (value) of the characteristic.

The promise will receive an object like this:

{
  value: <ArrayBuffer>, // an ArrayBuffer which you can use to decode (see example below)
  ios: <72>, // the platform-specific binary value of the characteristic: NSData (iOS), byte[] (Android)
  android: <72>, // the platform-specific binary value of the characteristic: NSData (iOS), byte[] (Android)
  characteristicUUID: '434234-234234-234234-434'
}

Armed with this knowledge, let's invoke the read function:

bluetooth.read({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343'
}).then(function(result) {
  // fi. a heartrate monitor value (Uint8) can be retrieved like this:
  var data = new Uint8Array(result.value);
  console.log("Your heartrate is: " + data[1] + " bpm");  
}, function (err) {
  console.log("read error: " + err);
});

write

If a peripheral has a service that has a characteristic where properties.write is true then you can call the write function to update the current state (value) of the characteristic.

The value may be a string or any array type value. If you pass a string you should pass the encoding too

bluetooth.write({
  peripheralUUID: '34134-5453-4453-54545',
  serviceUUID: '180e',
  characteristicUUID: '3424-45234-34324-2343',
  value: [1]
}).then(function(result) {
  console.log("value written");
}, function (err) {
  console.log("write error: " + err);
});

writeWithoutResponse

Same API as write, except that when the promise is invoked the value has not been written yet; it has only been requested to be written an no response will be received when it has.

startNotifying

If a peripheral has a service that has a characteristic where properties.notify is true then you can call the startNotifying function to retrieve the value changes of the characteristic.

Usage is very much like read, but the result won't be sent to the promise, but to the onNotify callback function you pass in. This is because multiple notifications can be received and a promise can only resolve once. The value of the object sent to onNotify is the same as the one you get in the promise of read.

bluetooth.startNotifying({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343',
  onNotify: function (result) {
    // see the read example for how to decode ArrayBuffers
    console.log("read: " + JSON.stringify(result));
  }  
}).then(function() {
  console.log("subscribed for notifications");
});

stopNotifying

Enough is enough. When you're no longer interested in the values the peripheral is sending you do this:

bluetooth.stopNotifying({
  peripheralUUID: '34234-5453-4453-54545',
  serviceUUID: '180d',
  characteristicUUID: '3434-45234-34324-2343'
}).then(function() {
  console.log("unsubscribed for notifications");
}, function (err) {
  console.log("unsubscribe error: " + err);
});

Examples:

  • Basic
    • A basic example showing that overriding N gestures works, even in modals

Demos and Development

Repo Setup

The repo uses submodules. If you did not clone with --recursive then you need to call

git submodule update --init

The package manager used to install and link dependencies must be pnpm or yarn. npm wont work.

To develop and test: if you use yarn then run yarn if you use pnpm then run pnpm i

Interactive Menu:

To start the interactive menu, run npm start (or yarn start or pnpm start). This will list all of the commonly used scripts.

Build

npm run build.all

WARNING: it seems yarn build.all wont always work (not finding binaries in node_modules/.bin) which is why the doc explicitly uses npm run

Demos

npm run demo.[ng|react|svelte|vue].[ios|android]

npm run demo.svelte.ios # Example

Demo setup is a bit special in the sense that if you want to modify/add demos you dont work directly in demo-[ng|react|svelte|vue] Instead you work in demo-snippets/[ng|react|svelte|vue] You can start from the install.ts of each flavor to see how to register new demos

Contributing

Update repo

You can update the repo files quite easily

First update the submodules

npm run update

Then commit the changes Then update common files

npm run sync

Then you can run yarn|pnpm, commit changed files if any

Update readme

npm run readme

Update doc

npm run doc

Publish

The publishing is completely handled by lerna (you can add -- --bump major to force a major release) Simply run

npm run publish

modifying submodules

The repo uses https:// for submodules which means you won't be able to push directly into the submodules. One easy solution is t modify ~/.gitconfig and add

[url "ssh://git@github.com/"]
    pushInsteadOf = https://github.com/

Questions

If you have any questions/issues/comments please feel free to create an issue or start a conversation in the NativeScript Community Discord.

Demos and Development

Repo Setup

The repo uses submodules. If you did not clone with --recursive then you need to call

git submodule update --init

The package manager used to install and link dependencies must be pnpm or yarn. npm wont work.

To develop and test: if you use yarn then run yarn if you use pnpm then run pnpm i

Interactive Menu:

To start the interactive menu, run npm start (or yarn start or pnpm start). This will list all of the commonly used scripts.

Build

npm run build.all

WARNING: it seems yarn build.all wont always work (not finding binaries in node_modules/.bin) which is why the doc explicitly uses npm run

Demos

npm run demo.[ng|react|svelte|vue].[ios|android]

npm run demo.svelte.ios # Example

Demo setup is a bit special in the sense that if you want to modify/add demos you dont work directly in demo-[ng|react|svelte|vue] Instead you work in demo-snippets/[ng|react|svelte|vue] You can start from the install.ts of each flavor to see how to register new demos

Contributing

Update repo

You can update the repo files quite easily

First update the submodules

npm run update

Then commit the changes Then update common files

npm run sync

Then you can run yarn|pnpm, commit changed files if any

Update readme

npm run readme

Update doc

npm run doc

Publish

The publishing is completely handled by lerna (you can add -- --bump major to force a major release) Simply run

npm run publish

modifying submodules

The repo uses https:// for submodules which means you won't be able to push directly into the submodules. One easy solution is t modify ~/.gitconfig and add

[url "ssh://git@github.com/"]
    pushInsteadOf = https://github.com/

Questions

If you have any questions/issues/comments please feel free to create an issue or start a conversation in the NativeScript Community Discord.

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

3.1.22 (2025-02-07)

Bug Fixes

  • autoDiscoverAll default was not handled correctly. Now default to true (9b49888)

3.1.21 (2025-01-17)

Bug Fixes

3.1.20 (2025-01-17)

Bug Fixes

  • autoDiscoverAll is not true by default (ec56527)

3.1.19 (2024-02-06)

Bug Fixes

  • android: set default encoding to prevent errors (4ee622f)

3.1.18 (2024-01-11)

Bug Fixes

  • android: location permission was always returned granted (e3625f5)
  • android: make it clearer how to use permissions in the doc. Also code changed a bit to reflect that. NOW YOU NEED TO DEFINE PERMISSIONS IN YOUR MANIFEST. The plugin wont do it anymore to not add unecessary permissions (63b8750)

3.1.17 (2023-11-17)

Bug Fixes

  • android: error wile sending array to char (6ffa83f)

3.1.16 (2023-11-08)

Bug Fixes

  • export BluetoothError and improve BluetoothError logging (adff148)
  • user @nativescript-community/perms (6a66786)

3.1.15 (2023-02-07)

Bug Fixes

  • ensure we always work with lowercase UUIDs so that callbacks always work correctly (313d3c0)

3.1.14 (2023-01-24)

Bug Fixes

  • android: native-api-usage fix (c3d5f07)

3.1.13 (2023-01-23)

Bug Fixes

  • android: improved native-api-usage (df7431d)
  • android: more native-api-usage fixes (6c48bb6)
  • android: more native-api-usage improvements (c1f6519)

3.1.12 (2023-01-08)

Bug Fixes

  • android: onCharacteristicRead deprecated (9acfe2a)
  • refactoring to handle deprecated methods on android 13 (10bb8ec)

3.1.11 (2022-11-27)

Bug Fixes

  • android: prevent errors (fdf6355)

3.1.10 (2022-10-24)

Note: Version bump only for package @nativescript-community/ble

3.1.9 (2022-10-24)

Bug Fixes

  • android: crash in onConnectionStateChange (0310f00)

3.1.8 (2022-05-15)

Bug Fixes

  • android: refactoring using @nativescript-community/arraybuffers (ae5683b)

3.1.7 (2022-05-10)

Features

  • android: android priority connect parameter (16fdcc2)

3.1.6 (2022-02-18)

Features

  • avoidDuplicates option on startScanning method (25dba13)

3.1.5 (2022-01-20)

Bug Fixes

  • ios: trying to fix serviceUUIDs (84cbf7f)

3.1.4 (2022-01-20)

Bug Fixes

  • ios: connect serviceUUIDs fix (b467e7d)

3.1.3 (2022-01-20)

Note: Version bump only for package @nativescript-community/ble

3.1.2 (2022-01-18)

Features

3.1.1 (2022-01-15)

Bug Fixes

  • android: missing native-api-usage (d417bbb)

3.1.0 (2022-01-15)

Bug Fixes

  • isConnected should not throw if device is not connected but return false (49fe431)

Features

  • android: native-api-usage (41911d0)
  • alternative to discoverAll: serviceUUIDs. Will discover only those services and no chars(faster) (c39dd3b)

3.0.34 (2022-01-15)

Bug Fixes

  • export BleTraceCategory (cb5c7d7)

3.0.33 (2021-12-10)

Bug Fixes

3.0.32 (2021-12-09)

Bug Fixes

  • revert 1028c15c707cb0409eac64e15ccc2b84cb0c4f42 as it broken users workflow (513953d)

3.0.31 (2021-12-01)

Bug Fixes

  • android: correctly update device state on disconnect (8c67892)

3.0.30 (2021-11-30)

Bug Fixes

  • android: isConnected wrong state after disconnection (a038f1b)
  • android: Notification streams are now properly disabled when stop requested. (b4afb5a)
  • ios: Ensure the Central Manager is created prior to waiting for the bluetooth_status_event. (999616f)

Features

  • android: corrects Promise handling and introduces the ability to disable the plugin queue. (1028c15)
  • ios: explicitly allow restoreIdentifer = null to disable restoring. (9beb319)

3.0.29 (2021-07-09)

Bug Fixes

  • android: default transport revert to TRANSPORT_LE (0087a8d)

3.0.28 (2021-07-09)

Bug Fixes

  • android: connect transport set to TRANSPORT_AUTO. Allow to pass custom one (2285aa1)

3.0.27 (2021-07-09)

Bug Fixes

  • android: refreshDeviceCache fix (7ece4ff)

3.0.26 (2021-07-04)

Bug Fixes

  • android: register notifyCallback earlier and optimistically (b79f475)

Features

  • android: new clearCache option for discoverServices (2a1066d)

3.0.25 (2021-06-03)

Bug Fixes

  • ios: try to fix build errors on iOS (caused by exported native class) (63f8fb3)

3.0.24 (2021-05-27)

Note: Version bump only for package @nativescript-community/ble

3.0.23 (2021-05-27)

Note: Version bump only for package @nativescript-community/ble

3.0.22 (2021-05-27)

Features

  • timeout for read / write (ff3bbc8)

3.0.21 (2021-05-18)

Bug Fixes

3.0.20 (2021-05-12)

Bug Fixes

  • rollback p-queue version to fix build (ee5bdb0)

3.0.19 (2021-05-06)

Bug Fixes

3.0.18 (2021-05-06)

Bug Fixes

  • ios: fix for wrong first isEnabled state (7076cc0)

3.0.17 (2021-05-04)

Features

  • add acces to native device (58b92cf)

3.0.16 (2021-03-24)

Bug Fixes

  • typings fix (0a3afc0)
  • android: 2m phy selection is now only attempted if isLe2MPhySupported is true. (8124923)

3.0.15 (2021-02-18)

Bug Fixes

  • android: autoDiscoverAll was broken in last version (dda3876)
  • ios: correctly query mtu on connection (6b1a8f8)

3.0.14 (2021-02-12)

Bug Fixes

  • android: Disconnect listeners now only accept disconnect events from matching devices. (213e7e4)

Features

  • android: Connections can now be made with 2M PHY and Max MTU. Also removes code duplication by introducing attachSubDelegate. (e7dee52)

3.0.13 (2020-12-14)

Bug Fixes

  • android: fix ble not working after disconnexion during write (f038cb0)

3.0.12 (2020-11-23)

Note: Version bump only for package @nativescript-community/ble

3.0.11 (2020-11-23)

Note: Version bump only for package @nativescript-community/ble

3.0.10 (2020-11-22)

Note: Version bump only for package @nativescript-community/ble

3.0.9 (2020-11-17)

Bug Fixes

  • ios fix serviceUUIDs not reported correctly (6a55b6d)

3.0.8 (2020-11-06)

Bug Fixes

3.0.7 (2020-11-05)

Note: Version bump only for package @nativescript-community/ble

3.0.6 (2020-11-02)

Note: Version bump only for package @nativescript-community/ble

3.0.5 (2020-11-02)

Bug Fixes

  • android fix for null owner (44d0c03)

3.0.4 (2020-10-07)

Bug Fixes

  • android fixed advertisment serviceUuids reading (3268e11)
  • Bluetooth GIF path was wrong. (8f553b4)

3.0.3 (2020-09-16)

Bug Fixes

  • Scan not working in API < 21 as reported in #165 (070c06f)

3.0.2 (2020-09-10)

Note: Version bump only for package @nativescript-community/ble

3.0.1 (2020-09-01)

Bug Fixes

  • android: correctly check for ermission (af963e3)
  • ios: manufacturerData fixes (cdc5cd8)

3.0.0 (2020-08-27)

Bug Fixes

  • ios: fixed wrong format for valueToString (d4b3004)
  • ios: read was not working for notifying chars (e3fc4f0)
  • any gatt queue promise need to reject on device disconnection (d7c6834)
  • call device.disconnect to get the status change event (658907d)
  • crash on pre lollipop (dd2623c)
  • dont clear adv data automatically, will create side errors (65d3fe6)
  • fixed edge cases for android. needs more refactoring (aa0b152)
  • fixed ios requestMtu (05209d6)
  • ios disconnect method was deleted onDisconnected callback from connect (9427be6)
  • missing export (fd96ff9)
  • missing localName and manufacturerId from connect event (a3eeb4d)
  • throw Error and not a string (77b2e75)

Features

1.2.4 (2018-12-07)

1.3.0 (2017-10-27)

1.2.0 (2017-08-13)

1.1.6 (2017-05-01)

1.1.5 (2017-03-29)

Bug Fixes

  • update package.json to allow webpack bundling (ef9ec29)

1.1.4 (2016-11-22)

1.1.3 (2016-10-05)

1.1.2 (2016-05-11)

1.1.1 (2016-03-15)

1.1.0 (2016-03-08)

1.0.0 (2016-03-05)