@blunt-ly/ble-advertiser
v0.1.0
Published
Minimal BLE advertiser for React-Native, optimized for background processing.
Maintainers
Readme
BLE Advertiser Module
A cross-platform BLE (Bluetooth Low Energy) advertiser module for React Native using Expo Modules API. This module allows you to advertise service UUIDs over BLE on both Android and iOS platforms, using minimal platform features to support background processing.
Installation
npm install @blunt-ly/ble-advertiserAPI
Methods
broadcast(uuids: string[]): Promise<string>
Start BLE advertising with the specified service UUIDs.
import * as BleAdvertiser from '@blunt-ly/ble-advertiser';
const serviceUUIDs = [
'6ba7b810-9dad-11d1-80b4-00c04fd430c8',
'180D' // 16-bit UUIDs are also supported
];
try {
const result = await BleAdvertiser.broadcast(serviceUUIDs);
console.log('Advertising started:', result);
} catch (error) {
console.error('Failed to start advertising:', error);
}[!NOTE] When an iOS app advertises in the background, CoreBluetooth moves its service UUIDs out of the standard advertisement field and into an "overflow area" that is only visible to scanners which already know the UUIDs in advance. To work around this, the module exposes a GATT characteristic that holds the device-specific UUIDs, so a scanner that recognizes a shared "network" UUID in the overflow area can connect via GATT to retrieve them. See Scanning in iOS background mode for the consumer-side pattern.
stopBroadcast(): Promise<{stopped: boolean, stoppedAdvertisers?: number}>
Stop all BLE advertising.
try {
const result = await BleAdvertiser.stopBroadcast();
console.log('Advertising stopped:', result);
} catch (error) {
console.error('Failed to stop advertising:', error);
}isSupported(): Promise<boolean>
Check if BLE advertising is supported on the current device.
const supported = await BleAdvertiser.isSupported();
console.log('BLE advertising supported:', supported);isEnabled(): Promise<boolean>
Check if Bluetooth is currently enabled.
const enabled = await BleAdvertiser.isEnabled();
console.log('Bluetooth enabled:', enabled);Events
onAdvertisingStarted
Fired when advertising starts successfully.
import { addAdvertisingStartedListener } from '@blunt-ly/ble-advertiser';
const subscription = addAdvertisingStartedListener((event) => {
console.log('Advertising started with UUIDs:', event.uuids);
});
// Don't forget to remove the listener
subscription.remove();onAdvertisingFailed
Fired when advertising fails to start.
import { addAdvertisingFailedListener } from '@blunt-ly/ble-advertiser';
const subscription = addAdvertisingFailedListener((event) => {
console.log('Advertising failed:', event.error);
if (event.errorCode) {
console.log('Error code:', event.errorCode);
}
});onAdvertisingStopped
Fired when advertising is stopped.
import { addAdvertisingStoppedListener } from '@blunt-ly/ble-advertiser';
const subscription = addAdvertisingStoppedListener((event) => {
console.log('Advertising stopped');
if (event.uuids) {
console.log('UUIDs that were being advertised:', event.uuids);
}
});Error Handling
The module provides comprehensive error handling with specific error codes and messages:
BLUETOOTH_NOT_AVAILABLE- Bluetooth adapter not availableBLUETOOTH_DISABLED- Bluetooth is turned offADVERTISER_NOT_AVAILABLE- BLE advertiser not supportedINVALID_UUID- Invalid UUID format providedNO_UUIDS- No service UUIDs providedADVERTISING_FAILED- Platform-specific advertising failure
Example Usage
import React, { useEffect, useState } from 'react';
import { View, Button, Text, Alert } from 'react-native';
import * as BleAdvertiser from '@blunt-ly/ble-advertiser';
export default function BleAdvertiserExample() {
const [isAdvertising, setIsAdvertising] = useState(false);
const [isSupported, setIsSupported] = useState(false);
useEffect(() => {
// Check if BLE advertising is supported
BleAdvertiser.isSupported().then(setIsSupported);
// Set up event listeners
const startedSubscription = BleAdvertiser.addAdvertisingStartedListener((event) => {
setIsAdvertising(true);
Alert.alert('Advertising Started', `UUIDs: ${event.uuids.join(', ')}`);
});
const failedSubscription = BleAdvertiser.addAdvertisingFailedListener((event) => {
setIsAdvertising(false);
Alert.alert('Advertising Failed', event.error);
});
const stoppedSubscription = BleAdvertiser.addAdvertisingStoppedListener(() => {
setIsAdvertising(false);
Alert.alert('Advertising Stopped');
});
return () => {
startedSubscription.remove();
failedSubscription.remove();
stoppedSubscription.remove();
};
}, []);
const startAdvertising = async () => {
try {
const serviceUUIDs = ['6ba7b810-9dad-11d1-80b4-00c04fd430c8'];
await BleAdvertiser.broadcast(serviceUUIDs);
} catch (error) {
Alert.alert('Error', error.message);
}
};
const stopAdvertising = async () => {
try {
await BleAdvertiser.stopBroadcast();
} catch (error) {
Alert.alert('Error', error.message);
}
};
if (!isSupported) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>BLE Advertising is not supported on this device</Text>
</View>
);
}
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>BLE Advertising Status: {isAdvertising ? 'Active' : 'Inactive'}</Text>
<Button
title={isAdvertising ? 'Stop Advertising' : 'Start Advertising'}
onPress={isAdvertising ? stopAdvertising : startAdvertising}
/>
</View>
);
}Scanning in iOS background mode
When the advertising app is backgrounded on iOS, its device-specific service UUIDs only surface in the scanner's overflowServiceUUIDs field — and only if the scanner is already scanning for a known "network" UUID that the advertiser also broadcasts. The pattern is:
- The advertiser broadcasts a shared
networkIdUUID plus a device-specific UUID. - The scanner filters on
networkId. - In the foreground both UUIDs are visible in
advertising.serviceUUIDs. - In the background only
networkIdis visible (viaoverflowServiceUUIDs); the scanner then connects via GATT to read the device-specific UUID from the characteristic exposed by this module.
const NETWORK_ID = '<your-shared-network-uuid>';
const inFlightConnections = new Set<string>();
await scanner.start(async (peripheral) => {
let targetBroadcastId: string | undefined | null;
// Normal path: both service UUIDs are visible in the advertisement
if (peripheral.advertising.serviceUUIDs?.length === 2) {
targetBroadcastId = peripheral.advertising.serviceUUIDs.find(
(uuid) => uuid.toLowerCase() !== NETWORK_ID.toLowerCase()
);
}
// Overflow path: only the known network UUID is visible via the overflow area.
// Connect via GATT to read the device-specific broadcast ID.
if (!targetBroadcastId) {
const overflowUUIDs = peripheral.advertising.overflowServiceUUIDs as string[] | undefined;
const hasNetworkInOverflow = overflowUUIDs?.some(
(uuid) => uuid.toLowerCase() === NETWORK_ID.toLowerCase()
);
if (!hasNetworkInOverflow) return;
if (inFlightConnections.has(peripheral.id)) return;
inFlightConnections.add(peripheral.id);
targetBroadcastId = await readBroadcastIdViaGatt(peripheral.id, NETWORK_ID);
// Allow re-connection after a cooldown
setTimeout(() => inFlightConnections.delete(peripheral.id), 60_000);
}
if (!targetBroadcastId) return;
// Handle the resolved broadcast ID...
}, [NETWORK_ID]);