nativescript-community / Ble

Licence: mit
Connect to and interact with Bluetooth LE peripherals.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Ble

Esp32 Ble Mouse
Bluetooth LE Mouse library for the ESP32 (Arduino IDE compatible)
Stars: ✭ 180 (+15.38%)
Mutual labels:  ble, bluetooth-le, bluetooth
Easyble
Android BLE framework
Stars: ✭ 155 (-0.64%)
Mutual labels:  ble, bluetooth-le, bluetooth
Node Ble
Bluetooth Low Energy (BLE) library written with pure Node.js (no bindings) - baked by Bluez via DBus
Stars: ✭ 159 (+1.92%)
Mutual labels:  ble, bluetooth-le, bluetooth
Extendable
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.
Stars: ✭ 88 (-43.59%)
Mutual labels:  ble, bluetooth-le, bluetooth
IOS-DFU-Library
OTA DFU Library for Mac and iOS, compatible with nRF5x SoCs
Stars: ✭ 400 (+156.41%)
Mutual labels:  bluetooth, ble, bluetooth-le
py-bluetooth-utils
Python module containing bluetooth utility functions, in particular for easy BLE scanning and advertising
Stars: ✭ 60 (-61.54%)
Mutual labels:  bluetooth, ble, bluetooth-le
Ble.net
Cross-platform Bluetooth Low Energy (BLE) library for Android, iOS, and UWP
Stars: ✭ 137 (-12.18%)
Mutual labels:  ble, bluetooth-le, bluetooth
Esp32 Ble Keyboard
Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)
Stars: ✭ 533 (+241.67%)
Mutual labels:  ble, bluetooth-le, bluetooth
ruuvitag-demo
Demo of reading Bluetooth Low Energy sensor measurements of RuuviTag environmental sensors and feeding them to MQTT, a database and dashboards
Stars: ✭ 14 (-91.03%)
Mutual labels:  bluetooth, ble, bluetooth-le
bluetooth
Android Bluetooth examples
Stars: ✭ 80 (-48.72%)
Mutual labels:  bluetooth, ble, bluetooth-le
Ios Pods Dfu Library
OTA DFU Library for Mac and iOS, compatible with nRF5x SoCs
Stars: ✭ 349 (+123.72%)
Mutual labels:  ble, bluetooth-le, bluetooth
Nimble Arduino
A fork of the NimBLE library structured for compilation with Ardruino, designed for use with ESP32.
Stars: ✭ 108 (-30.77%)
Mutual labels:  ble, bluetooth-le, bluetooth
Easybluetoothframe
经典(传统)蓝牙快速开发框架,A fast develop frame of classic bluetooth
Stars: ✭ 79 (-49.36%)
Mutual labels:  ble, bluetooth
Ble Security Attack Defence
✨ Purpose only! The dangers of Bluetooth Low Energy(BLE)implementations: Unveiling zero day vulnerabilities and security flaws in modern Bluetooth LE stacks.
Stars: ✭ 88 (-43.59%)
Mutual labels:  ble, bluetooth-le
Konashi Ios Sdk
konashi iOS SDK
Stars: ✭ 90 (-42.31%)
Mutual labels:  ble, bluetooth
Rxbluetoothkit
iOS & OSX Bluetooth library for RxSwift
Stars: ✭ 1,213 (+677.56%)
Mutual labels:  ble, bluetooth
Ble Midi For Android
MIDI over Bluetooth LE driver for Android 4.3 or later
Stars: ✭ 90 (-42.31%)
Mutual labels:  ble, bluetooth
Pedalinomini
Same features of Pedalino™ in a compact form.
Stars: ✭ 139 (-10.9%)
Mutual labels:  ble, bluetooth
Ha Bt Proximity
Distributed Bluetooth Room Presence Sensor for Home Assistant
Stars: ✭ 77 (-50.64%)
Mutual labels:  bluetooth-le, bluetooth
Magicblue
💡 Unofficial Python API to control Magic Blue bulbs over Bluetooth
Stars: ✭ 92 (-41.03%)
Mutual labels:  ble, bluetooth

NativeScript Bluetooth plugin

NPM version Downloads Twitter Follow

Installation

From the command prompt go to your app's root folder and execute:

if using @nativescript

tns plugin add @nativescript-community/ble

And do yourself a favor by adding TypeScript support to your nativeScript app:

tns install typescript

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

hasLocationPermission

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.

On Android 6 you need to request permission to be able to interact with a Bluetooth peripheral (when the app is in the background) when targeting API level 23+. Even if the uses-permission tag for ACCESS_COARSE_LOCATION is present in AndroidManifest.xml.

Note that for BLUETOOTH and BLUETOOTH_ADMIN you don't require runtime permission; adding those to AndroidManifest.xml suffices (which the plugin does for you).

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 'requestCoarseLocationPermission' now
    console.log("Has Location Permission? " + granted);
  }
);

requestCoarseLocationPermission

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

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

setCharacteristicLogging

The app using bluetooth can generate many console.log messages - one for each characteristic read, write, change. This can be reduced by calling bluetooth.setCharacteristicLogging(false).

Troubleshooting

Get a merge issue in AndroidManifest.xml? Remove the platforms/android folder and rebuild.

Future work

  • Support interacting with multiple characteristics of the same peripheral at the same time.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].