Bluetooth
Use the experimental Bluetooth Low Energy GATT API to scan for, connect to, and exchange data with Bluetooth devices from a SPECS Lens.
- Snapchat: not supported
- SPECS: fully supported
- Camera Kit Web: not supported
- Camera Kit Mobile: not supported
- SnapchatNot supported
- SPECSFully supported
- Experimental API; a Lens that uses it needs Experimental APIs turned on and can't be published
- Camera Kit WebNot supported
- Camera Kit MobileNot supported
SPECS offers APIs for Bluetooth Low Energy (BLE) GATT (Generic Attribute Profile), so a Lens can scan for, connect to, and exchange data with devices such as heart-rate monitors, fitness trackers, and smart-home appliances. The API is BluetoothCentralModule and the classes in its Bluetooth namespace.
Bluetooth on SPECS is an experimental API
On SPECS, every Bluetooth GATT API is experimental. To use BluetoothCentralModule, turn on Experimental APIs in Project Settings. A Lens that uses an experimental API can be tested on your own SPECS but can't be published. The API may change in later releases.
You need Lens Studio 5.25 and a SPECS 27 device.
Transparent Permission treats BluetoothCentralModule as a connectivity module (descriptor Bluetooth Peripheral). On SPECS, a Lens that combines a connectivity module with sensitive data, such as the camera frame, location, or microphone audio, is publishable only when it also uses the internet module, and users see a permission prompt when it opens. Users who turn on Extended Permissions in the SPECS App skip that prompt. Because the Bluetooth API is still experimental, a Bluetooth Lens can't be published either way.
BluetoothCentralModule works with GATT devices. It doesn't connect to Bluetooth HID (input) devices the way the operating system does. To read a Bluetooth game controller paired with SPECS, use GameControllerModule.
Add the Bluetooth module to a SPECS Lens
To use the Bluetooth GATT API, add a BluetoothCentralModule asset to your project and assign it to the script input, as in the examples on this page.
Bluetooth doesn't work in the Lens Studio Preview. To test a Bluetooth Lens, send it to SPECS (see Send a Lens to SPECS).
A Lens works with a Bluetooth device in this order:
- Scan for the device with
startScan. - Connect to the device with
connectGatt. - Read and write characteristics and descriptors as needed.
- Disconnect from the device with
closewhen finished.
To check your BLE device's UUIDs, message format, and contents, use the nRF Connect app on your phone.
If your device is paired to your phone (for example, through a debugging tool such as the nRF Connect app), you may need to reset it before it pairs with SPECS. A device that connects to SPECS and disconnects immediately needs a reset.
Connect to a single Bluetooth device
The Bluetooth API can scan for and connect to one device or several. The following example scans for a single device named Hue color lamp. When the scan finds it, onFoundScanResult connects to the device, finds the characteristic of interest, then reads its value, writes a value, and listens for changes. It also listens for the device disconnecting with onDisconnectedEvent.
- TypeScript
- JavaScript
@component
export class BleTest_SingleDevice extends BaseScriptComponent {
@input
bluetoothModule: Bluetooth.BluetoothCentralModule;
@input
logToScreenText: Text;
private bluetoothGatt: Bluetooth.BluetoothGatt;
private onDisconnectedEventRegistration: EventRegistration;
private deviceName: string;
private serviceUUID: string;
private characteristicUUID: string;
private deviceAddress: Uint8Array;
onAwake() {
this.deviceName = 'Hue color lamp';
this.serviceUUID = '932C32BD-0000-47A2-835A-A8D455B859DD';
this.characteristicUUID = '932C32BD-0002-47A2-835A-A8D455B859DD';
if (!global.deviceInfoSystem.isEditor()) {
this.scanForGatt();
}
}
private logToScreen(msg: string) {
this.logToScreenText.text = msg;
print(msg);
}
private scanForGatt() {
this.logToScreen('----- Bluetooth Test: Single Device -----');
// To limit your scan results, set a property in the filter
let scanFilter = new Bluetooth.ScanFilter();
scanFilter.deviceName = this.deviceName; // Case-sensitive
let scanSettings = new Bluetooth.ScanSettings();
// Setting unique devices to true means you will only see scan results for
// unique devices in the predicate for the duration of this scan session.
scanSettings.uniqueDevices = true;
// The timeout is the length of time the scan could continue before stopping.
scanSettings.timeoutSeconds = 30;
scanSettings.scanMode = Bluetooth.ScanMode.LowPower;
this.logToScreen('Starting scan');
this.bluetoothModule
.startScan(
[scanFilter],
scanSettings,
// The predicate function will be invoked with each scan result:
// If this.predicate returns true, the scan will stop.
// If this.predicate returns false, the scan will continue until timeout.
(result) => this.predicate(result)
)
.then((result) => {
// This fires when the predicate returns true
this.logToScreen(
'The scan is over, we succeeded in finding the single result we were looking for in the predicate.'
);
this.onFoundScanResult(result);
})
.catch((error) => {
// This fires on calling bluetoothModule.stopScan() and on scan timing out
this.logToScreen(
'The scan is over. It either timed out, we called stopScan(), or an error occurred.'
);
this.reportError(error);
});
}
private predicate(result?: Bluetooth.ScanResult) {
// If you're only looking for one scan result, use the predicate to find it,
// and then return true and act on your scan result in ".then"
if (result.deviceName === this.deviceName) {
// The desired device was found, return true to stop the scan
return true;
} else {
// Returning "false" from the predicate continues the scan until true is
// returned or the scan times out
return false;
}
}
private onFoundScanResult(scanResult?: Bluetooth.ScanResult) {
this.bluetoothModule
.connectGatt(scanResult.deviceAddress)
.then((gattResult) => {
this.logToScreen(scanResult.deviceName + ' device is connected!');
this.bluetoothGatt = gattResult as Bluetooth.BluetoothGatt;
// Example #1: Iterate through UUIDs to confirm what they are
// Tip: when you type your variable at the declaration, intellisense will
// work thereafter.
let services: Bluetooth.BluetoothGattService[] =
this.bluetoothGatt.getServices();
services.forEach((service) => {
this.logToScreen(
this.deviceName +
'found service ' +
service +
', with uuid ' +
service.uuid
);
let characteristics: Bluetooth.BluetoothGattCharacteristic[] =
service.getCharacteristics();
characteristics.forEach((characteristic) => {
this.logToScreen(
this.deviceName +
' found characteristic ' +
characteristic +
', with uuid ' +
characteristic.uuid
);
});
});
// Example #2: Get the service/characteristic by known UUIDs
try {
// Note: this throws an error on fail, hence the try/catch
let service: Bluetooth.BluetoothGattService =
this.bluetoothGatt.getService(this.serviceUUID);
if (service !== undefined) {
try {
// Note: this throws an error on fail, hence the try/catch
let characteristic: Bluetooth.BluetoothGattCharacteristic =
service.getCharacteristic(this.characteristicUUID);
if (characteristic !== undefined) {
// Example #3: Read value
characteristic
.readValue()
.then((result) => {
let val: Uint8Array = result;
this.logToScreen('characteristic read .then val: ' + val);
})
.catch((error) => {
this.reportError(error);
});
// Example #4: write the value for power on: 1
let val = new Uint8Array([1]);
characteristic
.writeValue(val)
.then(() => {
// Note: we are not given the value that was written
this.logToScreen('characteristic write value fulfilled');
})
.catch((error) => {
this.reportError(error);
});
// Example #5: register for notifications
characteristic
.registerNotifications((arg) =>
this.characteristicNotification(arg)
)
.then(() => {
this.logToScreen(
'Characteristic is registered for notifications.'
);
})
.catch((error) => {
this.reportError(error);
});
// Example #6: Subscribe to the disconnection event
this.onDisconnectedEventRegistration =
this.bluetoothGatt.onDisconnectedEvent.add(() =>
this.onDisconnected()
);
}
} catch (error) {
this.reportError(error);
}
}
} catch (error) {
this.reportError(error);
}
})
.catch((error) => {
this.logToScreen(scanResult.deviceName + 'connection error');
this.reportError(error);
});
}
private characteristicNotification(val: Uint8Array) {
this.logToScreen('characteristicNotification ' + val);
}
private onDisconnected() {
// Fires when the connected device disconnects.
this.logToScreen('onDisconnected: ' + this.deviceName + ' disconnected');
this.bluetoothGatt.onDisconnectedEvent.remove(
this.onDisconnectedEventRegistration
);
}
private reportError(reason: unknown) {
if (reason instanceof Error) {
this.logToScreen(
`[reportError Error] ${reason.name}: ${reason.message}\n${reason.stack}`
);
} else if (typeof reason !== 'string') {
this.logToScreen(`[reportError !string] ${typeof reason}: ${reason}`);
} else {
this.logToScreen(`[reportError string] ${reason}`);
}
}
}
// @input Asset.BluetoothCentralModule bluetoothModule
// @input Component.Text logToScreenText
let bluetoothGatt;
let onDisconnectedEventRegistration;
const deviceName = 'Hue color lamp';
const serviceUUID = '932C32BD-0000-47A2-835A-A8D455B859DD';
const characteristicUUID = '932C32BD-0002-47A2-835A-A8D455B859DD';
function onAwake() {
if (!global.deviceInfoSystem.isEditor()) {
scanForGatt();
}
}
function logToScreen(msg) {
script.logToScreenText.text = msg;
print(msg);
}
function scanForGatt() {
logToScreen('----- Bluetooth Test: Single Device -----');
// To limit your scan results, set a property in the filter
var scanFilter = new Bluetooth.ScanFilter();
scanFilter.deviceName = deviceName; // Case-sensitive
const scanSettings = new Bluetooth.ScanSettings();
// Setting unique devices to true means you will only see scan results for
// unique devices in the predicate for the duration of this scan session.
scanSettings.uniqueDevices = true;
// The timeout is the length of time the scan could continue before stopping.
scanSettings.timeoutSeconds = 30;
scanSettings.scanMode = Bluetooth.ScanMode.LowPower;
logToScreen('Starting scan');
script.bluetoothModule
.startScan(
[scanFilter],
scanSettings,
// The predicate function will be invoked with each scan result:
// If predicate returns true, the scan will stop.
// If predicate returns false, the scan will continue until timeout.
function (result) {
return predicate(result);
}
)
.then(function (result) {
// This fires when the predicate returns true
logToScreen(
'The scan is over, we succeeded in finding the single result we were looking for in the predicate.'
);
onFoundScanResult(result);
})
.catch(function (error) {
// This fires on calling bluetoothModule.stopScan() and on scan timing out
logToScreen(
'The scan is over. It either timed out, we called stopScan(), or an error occurred.'
);
reportError(error);
});
}
function predicate(result) {
// If you're only looking for one scan result, use the predicate to find it,
// and then return true and act on your scan result in ".then"
if (result.deviceName === deviceName) {
// The desired device was found, return true to stop the scan
return true;
} else {
// Returning "false" from the predicate continues the scan until true is
// returned or the scan times out
return false;
}
}
function onFoundScanResult(scanResult) {
script.bluetoothModule
.connectGatt(scanResult.deviceAddress)
.then(function (gattResult) {
logToScreen(scanResult.deviceName + ' device is connected!');
bluetoothGatt = gattResult;
// Example #1: Iterate through UUIDs to confirm what they are
const services = bluetoothGatt.getServices();
services.forEach(function (service) {
logToScreen(
deviceName +
'found service ' +
service +
', with uuid ' +
service.uuid
);
const characteristics = service.getCharacteristics();
characteristics.forEach(function (characteristic) {
logToScreen(
deviceName +
' found characteristic ' +
characteristic +
', with uuid ' +
characteristic.uuid
);
});
});
// Example #2: Get the service/characteristic by known UUIDs
try {
// Note: this throws an error on fail, hence the try/catch
const service = bluetoothGatt.getService(serviceUUID);
if (service !== undefined) {
try {
// Note: this throws an error on fail, hence the try/catch
const characteristic =
service.getCharacteristic(characteristicUUID);
if (characteristic !== undefined) {
// Example #3: Read value
characteristic
.readValue()
.then(function (result) {
const val = result;
logToScreen('characteristic read .then val: ' + val);
})
.catch(function (error) {
reportError(error);
});
// Example #4: write the value for power on: 1
const val = new Uint8Array([1]);
characteristic
.writeValue(val)
.then(function () {
// Note: we are not given the value that was written
logToScreen('characteristic write value fulfilled');
})
.catch(function (error) {
reportError(error);
});
// Example #5: register for notifications
characteristic
.registerNotifications(function (arg) {
characteristicNotification(arg);
})
.then(function () {
logToScreen(
'Characteristic is registered for notifications.'
);
})
.catch(function (error) {
reportError(error);
});
// Example #6: Subscribe to the disconnection event
onDisconnectedEventRegistration =
bluetoothGatt.onDisconnectedEvent.add(function () {
onDisconnected();
});
}
} catch (error) {
reportError(error);
}
}
} catch (error) {
reportError(error);
}
})
.catch(function (error) {
logToScreen(scanResult.deviceName + 'connection error');
reportError(error);
});
}
function characteristicNotification(val) {
logToScreen('characteristicNotification ' + val);
}
function onDisconnected() {
// Fires when the connected device disconnects.
logToScreen('onDisconnected: ' + deviceName + ' disconnected');
bluetoothGatt.onDisconnectedEvent.remove(onDisconnectedEventRegistration);
}
function reportError(reason) {
if (reason instanceof Error) {
logToScreen(
'[reportError Error] ' +
reason.name +
': ' +
reason.message +
'\n' +
reason.stack
);
} else if (typeof reason !== 'string') {
logToScreen('[reportError !string] ' + typeof reason + ': ' + reason);
} else {
logToScreen('[reportError string] ' + reason);
}
}
// Initialize
onAwake();
The Bluetooth API also works with async/await. The following scanForGatt replaces the one in the single-device example:
- TypeScript
- JavaScript
private async scanForGatt() {
let scanFilter = new Bluetooth.ScanFilter();
let scanSettings = new Bluetooth.ScanSettings();
scanSettings.uniqueDevices = true;
scanSettings.timeoutSeconds = 30;
scanSettings.scanMode = Bluetooth.ScanMode.LowPower;
try {
const result = await this.bluetoothModule.startScan(
[scanFilter],
scanSettings,
(result) => this.predicate(result)
);
await this.onFoundScanResult(result);
} catch (error) {
this.reportError(error);
}
}
async function scanForGatt() {
const scanFilter = new Bluetooth.ScanFilter();
const scanSettings = new Bluetooth.ScanSettings();
scanSettings.uniqueDevices = true;
scanSettings.timeoutSeconds = 30;
scanSettings.scanMode = Bluetooth.ScanMode.LowPower;
try {
const result = await script.bluetoothModule.startScan(
[scanFilter],
scanSettings,
function (result) {
return predicate(result);
}
);
await onFoundScanResult(result);
} catch (error) {
reportError(error);
}
}
Connect to several Bluetooth devices
To connect to several devices found in one scan session, the scanning flow changes: the predicate stores each result and returns false, so the scan runs until it times out, and the Lens then connects to the stored devices one after another. The following example scans for devices named Hue color lamp and Thingy, then connects to each result in turn.
- TypeScript
- JavaScript
@component
export class BleTest_MultipleDevices extends BaseScriptComponent {
@input
bluetoothModule: Bluetooth.BluetoothCentralModule;
@input
logToScreenText: Text;
private scanResults: Bluetooth.ScanResult[];
private scanResultIndex: number;
onAwake() {
this.scanResults = [];
this.scanResultIndex = 0;
if (!global.deviceInfoSystem.isEditor()) {
this.scanForGatt();
}
}
private logToScreen(msg: string) {
this.logToScreenText.text = msg;
print(msg);
}
private scanForGatt() {
this.logToScreen('----- Bluetooth Test: Multiple Devices -----');
let scanFilter1 = new Bluetooth.ScanFilter();
scanFilter1.deviceName = 'Hue color lamp';
let scanFilter2 = new Bluetooth.ScanFilter();
scanFilter2.deviceName = 'Thingy';
let scanSetting = new Bluetooth.ScanSettings();
scanSetting.uniqueDevices = true;
scanSetting.timeoutSeconds = 30;
scanSetting.scanMode = Bluetooth.ScanMode.LowPower;
this.logToScreen(
'Starting scan for ' + scanSetting.timeoutSeconds + ' seconds.'
);
// When looking for multiple results, you must return false in order to keep
// scanning for new devices. The scan operation will not complete with a successful
// result ( .then ), but will instead complete with a timeout error handled in .catch.
// You can store the results you're interested in from within the predicate function,
// then sequentially connect to them after the scan has completed.
this.bluetoothModule
.startScan([scanFilter1, scanFilter2], scanSetting, (result) =>
this.predicate(result)
)
.then((result) => {
// As described above, in this multiple-device search example, the scan will
// resolve on timeout in .catch.
})
.catch((error) => {
// This fires on calling bluetoothModule.stopScan() and on scan timeout.
this.logToScreen(
'The scan is over. It either timed out, we called stopScan(), or an error occurred.'
);
// When looking for multiple scan results, connect to the results after the
// scan is over.
this.tryConnectToNextScanResult();
this.reportError(error);
});
}
private predicate(result?: Bluetooth.ScanResult) {
// When looking for multiple scan results, use the predicate to store results. Return
// false so the scan continues until timeout.
this.scanResults.push(result);
return false;
}
private tryConnectToNextScanResult() {
// Connect serially.
if (
this.scanResults.length > 0 &&
this.scanResultIndex < this.scanResults.length
) {
this.connectToScanResult(this.scanResults[this.scanResultIndex]);
this.scanResultIndex++;
}
}
private connectToScanResult(scanResult?: Bluetooth.ScanResult) {
this.logToScreen(
'connectToScanResult ' +
scanResult.deviceName +
' ' +
scanResult.deviceAddress
);
// Tip: Wait until the connection attempt succeeds or fails before moving on to connect
// the next device.
this.bluetoothModule
.connectGatt(scanResult.deviceAddress)
.then((gattResult) => {
this.logToScreen(scanResult.deviceName + ' device is connected!');
// Since you will have multiple connections to manage, here you would
// send your gattResult to an instanced class to handle this device's
// interrogation and callbacks.
// See class "ScanResult.ts" in the Playground example of the BLE Examples package.
this.tryConnectToNextScanResult();
})
.catch((error) => {
this.logToScreen(scanResult.deviceName + ' connection error');
this.reportError(error);
this.tryConnectToNextScanResult();
});
}
private reportError(reason: unknown) {
if (reason instanceof Error) {
this.logToScreen(
`[reportError Error] ${reason.name}: ${reason.message}\n${reason.stack}`
);
} else if (typeof reason !== 'string') {
this.logToScreen(`[reportError !string] ${typeof reason}: ${reason}`);
} else {
this.logToScreen(`[reportError string] ${reason}`);
}
}
}
// @input Asset.BluetoothCentralModule bluetoothModule
// @input Component.Text logToScreenText
const scanResults = [];
let scanResultIndex = 0;
function onAwake() {
if (!global.deviceInfoSystem.isEditor()) {
scanForGatt();
}
}
function logToScreen(msg) {
script.logToScreenText.text = msg;
print(msg);
}
function scanForGatt() {
logToScreen('----- Bluetooth Test: Multiple Devices -----');
const scanFilter1 = new Bluetooth.ScanFilter();
scanFilter1.deviceName = 'Hue color lamp';
const scanFilter2 = new Bluetooth.ScanFilter();
scanFilter2.deviceName = 'Thingy';
const scanSetting = new Bluetooth.ScanSettings();
scanSetting.uniqueDevices = true;
scanSetting.timeoutSeconds = 30;
scanSetting.scanMode = Bluetooth.ScanMode.LowPower;
logToScreen('Starting scan for ' + scanSetting.timeoutSeconds + ' seconds.');
// When looking for multiple results, you must return false in order to keep
// scanning for new devices. The scan operation will not complete with a successful
// result ( .then ), but will instead complete with a timeout error handled in .catch.
// You can store the results you're interested in from within the predicate function,
// then sequentially connect to them after the scan has completed.
script.bluetoothModule
.startScan([scanFilter1, scanFilter2], scanSetting, function (result) {
return predicate(result);
})
.then(function (result) {
// As described above, in this multiple-device search example, the scan will
// resolve on timeout in .catch.
})
.catch(function (error) {
// This fires on calling bluetoothModule.stopScan() and on scan timeout.
logToScreen(
'The scan is over. It either timed out, we called stopScan(), or an error occurred.'
);
// When looking for multiple scan results, connect to the results after the
// scan is over.
tryConnectToNextScanResult();
reportError(error);
});
}
function predicate(result) {
// When looking for multiple scan results, use the predicate to store results. Return
// false so the scan continues until timeout.
scanResults.push(result);
return false;
}
function tryConnectToNextScanResult() {
// Connect serially.
if (scanResults.length > 0 && scanResultIndex < scanResults.length) {
connectToScanResult(scanResults[scanResultIndex]);
scanResultIndex++;
}
}
function connectToScanResult(scanResult) {
logToScreen(
'connectToScanResult ' +
scanResult.deviceName +
' ' +
scanResult.deviceAddress
);
// Tip: Wait until the connection attempt succeeds or fails before moving on to connect
// the next device.
script.bluetoothModule
.connectGatt(scanResult.deviceAddress)
.then(function (gattResult) {
logToScreen(scanResult.deviceName + ' device is connected!');
// Since you will have multiple connections to manage, here you would
// send your gattResult to an instanced class to handle this device's
// interrogation and callbacks.
// See class "ScanResult.ts" in the Playground example of the BLE Examples package.
tryConnectToNextScanResult();
})
.catch(function (error) {
logToScreen(scanResult.deviceName + ' connection error');
reportError(error);
tryConnectToNextScanResult();
});
}
function reportError(reason) {
if (reason instanceof Error) {
logToScreen(
'[reportError Error] ' +
reason.name +
': ' +
reason.message +
'\n' +
reason.stack
);
} else if (typeof reason !== 'string') {
logToScreen('[reportError !string] ' + typeof reason + ': ' + reason);
} else {
logToScreen('[reportError string] ' + reason);
}
}
// Initialize
onAwake();
Known limitations of the Bluetooth API
The Bluetooth GATT API on SPECS is experimental. Parts of it may be constrained or change in later releases.
- The Bluetooth API matches UUIDs in both lower and upper case, so UUID case doesn't matter in your code.
BluetoothCentralModule limitations
BluetoothCentralModule.onBluetoothStatusChangedEventdoesn't fire.BluetoothCentralModule.statusis always0(Unknown).- The predicate works differently in the single-device and multi-device examples: return
trueto stop at the first match, or store results and returnfalseto keep scanning until the timeout. - To connect to several devices, connect one at a time, not in parallel.
BluetoothGattCharacteristic limitations
- The API only accepts
Uint8Arrayvalues, including for characteristics that expect anInt8Array. Writing negative values through aUint8Arrayhasn't been tested.