Announcing the Capacitor Bluetooth Low Energy Plugin¶
Today we are excited to announce our brand new Capacitor Bluetooth Low Energy plugin. This plugin enables interaction with Bluetooth Low Energy (BLE) devices in the central and peripheral role and provides cross-platform support for Android and iOS. The project is now available for all Capawesome Insiders.
Let's take a quick look at the API and how you can use the pugin to communicate with BLE devices.
Installation¶
See Getting started with Insiders and follow the instructions to install the plugin.
After that, follow the platform-specific instructions in the sections Android and iOS.
Usage¶
Let's take a look at the basic usage of the plugin. The plugin supports two roles:
- Central role: The app acts as a central device that can connect to and communicate with peripheral devices.
- Peripheral role: The app acts as a peripheral device that can advertise its services and accept connections from central devices.
The plugin supports both roles on Android and iOS. The following sections will show you how to use the plugin in both roles.
Central role¶
The central role allows you to connect to and communicate with BLE devices.
Initialize the plugin¶
First, you need to initialize the plugin and request the necessary permissions:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
import { Capacitor } from "@capacitor/core";
const initialize = async () => {
if (Capacitor.getPlatform() === "ios") {
await BluetoothLowEnergy.initialize({
mode: 'central'
});
} else {
await BluetoothLowEnergy.requestPermissions();
}
};
In this context, there are differences between Android and iOS.
On iOS, you need to call the initialize
method to initialize the plugin every time the app starts.
On Android, you need to call the requestPermissions
method to request the necessary permissions.
Scan for devices¶
Before you can connect to a device for the first time, you need to scan for devices.
For this, you can use the startScan
:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const startScan = async () => {
await BluetoothLowEnergy.addListener("deviceScanned", (event) => {
console.log("Device scanned", event.device);
});
await BluetoothLowEnergy.startScan();
};
const stopScan = async () => {
await BluetoothLowEnergy.stopScan();
};
Every time a device is found, the deviceScanned
event is emitted.
You can now display the found devices to your users and let them select the device they want to connect to.
As soon as the user has selected a device, you should stop the scan with stopScan
.
Connect to a device¶
To connect to a device, you can use the connect
method:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const connect = async (deviceId: string) => {
await BluetoothLowEnergy.connect({ deviceId });
};
You just need to pass the deviceId
of the device you want to connect to.
The deviceId
is the address of the device (e.g. 00:11:22:33:AA:BB
) and is usually provided by the deviceScanned
event.
Reconnect to a device
You don't need to scan for devices every time you want to connect to a device.
You can simply save the deviceId
of the device and use it to reconnect to the device later.
Communicate with a device¶
Before you can communicate with a device, you need to discover the services and characteristics of the device.
For this, you can use the discoverServices
method:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const discoverServices = async () => {
await BluetoothLowEnergy.discoverServices();
};
Use the getServices
method to get a list of all services, characteristics, and descriptors of the device:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const getServices = async () => {
const { services } = await BluetoothLowEnergy.getServices();
console.log("Services: ", services);
};
Now you can read, write, and subscribe to characteristics and descriptors using the following methods:
readCharacteristic
writeCharacteristic
startCharacteristicNotifications
stopCharacteristicNotifications
readDescriptor
writeDescriptor
This is an example of how to read a characteristic value:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const readCharacteristic = async (characteristicId: string) => {
const { value } = await BluetoothLowEnergy.readCharacteristic({ characteristicId });
console.log("Value: ", value); // e.g. [1, 2, 3, 4]
};
Values are exchanged as byte arrays. You can convert them to a hex string using the convertBytesToHex
method:
import { BluetoothLowEnergyUtils } from "@capawesome-team/capacitor-bluetooth-low-energy";
const convertBytesToHex = async (bytes: number[]) => {
const { hex } = await BluetoothLowEnergyUtils.convertBytesToHex({ bytes });
console.log("Hex: ", hex); // e.g. "01020304"
};
Disconnect from a device¶
To disconnect from a device, you simply need to call the disconnect
method:
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const disconnect = async () => {
await BluetoothLowEnergy.disconnect();
};
Peripheral role¶
The peripheral role allows you to advertise your app as a BLE device and accept connections from central devices.
Initialize the plugin¶
The initialization process is the same as in the central role.
You need to call the initialize
method on iOS and the requestPermissions
method on Android.
import { BluetoothLowEnergy } from "@capawesome-team/capacitor-bluetooth-low-energy";
const initialize = async () => {
if (Capacitor.getPlatform() === "ios") {
await BluetoothLowEnergy.initialize({
mode: 'peripheral'
});
} else {
await BluetoothLowEnergy.requestPermissions();
}
};
Start advertising¶
To start advertising your app as a BLE device, you can use the startAdvertising
method:
import { BluetoothLowEnergy } from '@capawesome-team/capacitor-bluetooth-low-energy';
const startAdvertising = async () => {
await BluetoothLowEnergy.startAdvertising({
name: 'CapBLE',
services: [
{
id: '12345678-1234-1234-1234-1234567890AB',
characteristics: [
{
id: '87654321-4321-4321-4321-BA0987654321',
descriptors: [],
permissions: {
read: true,
write: true,
},
properties: {
indicate: true,
notify: true,
read: true,
write: true,
},
},
],
},
],
});
};
The startAdvertising
method allows you to specify the name of the peripheral and the services it provides.
The services can include characteristics with various properties and permissions.
Communicate with a device¶
After starting advertising, devices can connect to your app.
You can listen to the deviceConnected
event to get notified when a device connects to your app:
import { BluetoothLowEnergy } from '@capawesome-team/capacitor-bluetooth-low-energy';
const addListener = async () => {
await BluetoothLowEnergy.addListener('deviceConnected', (event) => {
console.log('Device connected', event.deviceId);
});
};
You can also listen to the deviceDisconnected
event to get notified when a device disconnects from your app:
import { BluetoothLowEnergy } from '@capawesome-team/capacitor-bluetooth-low-energy';
const addListener = async () => {
await BluetoothLowEnergy.addListener('deviceDisconnected', (event) => {
console.log('Device disconnected', event.deviceId);
});
};
Read requests from devices are handled automatically by the plugin.
You can use the setCharacteristicValue
method to set or update the value of a characteristic:
import { BluetoothLowEnergy } from '@capawesome-team/capacitor-bluetooth-low-energy';
const setCharacteristicValue = async () => {
await BluetoothLowEnergy.setCharacteristicValue({
characteristicId: '87654321-4321-4321-4321-BA0987654321',
serviceId: '12345678-1234-1234-1234-1234567890AB',
value: [1, 2, 3, 4], // Value byte array
});
};
If a device wants to write a value to a characteristic, the plugin will emit the characteristicWriteRequest
event.
You can listen to this event and respond to the write request using the setCharacteristicValue
method:
import { BluetoothLowEnergy } from '@capawesome-team/capacitor-bluetooth-low-energy';
const addListener = async () => {
await BluetoothLowEnergy.addListener('characteristicWriteRequest', (event) => {
console.log('Characteristic write request', event);
// Respond to the write request
void BluetoothLowEnergy.setCharacteristicValue({
characteristicId: event.characteristicId,
serviceId: event.serviceId,
value: event.value,
});
});
};
Closing Thoughts¶
We hope you are as excited as we are about the new Capacitor Bluetooth Low Energy plugin. Be sure to check out the API Reference to see what else you can do with this plugin. If you are missing any features, just create a feature request in the GitHub repository. Make sure you follow us on X so you don't miss any future updates.