Primeros pasos
Copia un prompt de configuración con los pasos de instalación y la guía completa en markdown para este plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-bluetooth-low-energy`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/bluetooth-low-energy/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
Instalar
Sección titulada “Instalación”Puedes usar nuestro setup asistido por IA para instalar el plugin. Añade las skills de Capgo a tu herramienta de IA con el siguiente comando:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsLuego usa el siguiente prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-bluetooth-low-energy` plugin in my project.Si prefieres la configuración manual, instala el plugin ejecutando estos comandos y sigue las instrucciones de cada plataforma:
bun add @capgo/capacitor-bluetooth-low-energynpx cap syncImportar
Sección titulada “Importar”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';Inicio rápido
Sección titulada “Inicio rápido”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });Ejemplo: shimWebBluetooth
Sección titulada “Ejemplo: shimWebBluetooth”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();Ejemplo: isAvailable
Sección titulada “Ejemplo: isAvailable”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();Errores comunes
Sección titulada “Errores comunes”- Permisos: llama a
checkPermissions()luegorequestPermissions()cuando sea necesario. - Listeners: elimina los handles cuando se desmonten las pantallas.
- Inicializa una vez: ejecuta setup durante el bootstrap de la app.
Resumen de API
Sección titulada “Resumen de API”initialize
Sección titulada “initialize”Inicializa el plugin de BLE.
Debe llamarse antes que cualquier otro método, excepto addListener(). Registra adapterStateChanged antes de llamar a initialize() para no perder el evento de estado inicial de iOS.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });shimWebBluetooth
Sección titulada “shimWebBluetooth”Instala el shim Web Bluetooth de Capacitor en navigator.bluetooth.
Llama a esto manualmente antes de usar Web Bluetooth API desde una app nativa de Capacitor.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();isAvailable
Sección titulada “isAvailable”Comprueba si Bluetooth está disponible en el dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();isEnabled
Sección titulada “isEnabled”Comprueba si Bluetooth está activado en el dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isEnabled();isLocationEnabled
Sección titulada “isLocationEnabled”Comprueba si los servicios de ubicación están activados (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isLocationEnabled();openAppSettings
Sección titulada “openAppSettings”Abre la página de ajustes de la app.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openAppSettings();openBluetoothSettings
Sección titulada “openBluetoothSettings”Abre la página de ajustes de Bluetooth (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openBluetoothSettings();openLocationSettings
Sección titulada “openLocationSettings”Abre la página de ajustes de ubicación (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openLocationSettings();checkPermissions
Sección titulada “checkPermissions”Comprueba el estado actual de los permisos.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.checkPermissions();requestPermissions
Sección titulada “requestPermissions”Solicita permisos de Bluetooth.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.requestPermissions();startScan
Sección titulada “startScan”Empieza a escanear dispositivos BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startScan({ services: ['180D'], // Heart Rate Service timeout: 10000});stopScan
Sección titulada “stopScan”Detén el escaneo de dispositivos BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopScan();connect
Sección titulada “connect”Conéctate a un dispositivo BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' });disconnect
Sección titulada “disconnect”Desconéctate de un dispositivo BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.disconnect({ deviceId: 'AA:BB:CC:DD:EE:FF' });createBond
Sección titulada “createBond”Crea un emparejamiento con un dispositivo BLE (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.createBond({ deviceId: 'AA:BB:CC:DD:EE:FF' });isBonded
Sección titulada “isBonded”Comprueba si un dispositivo está emparejado (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bonded } = await BluetoothLowEnergy.isBonded({ deviceId: 'AA:BB:CC:DD:EE:FF' });discoverServices
Sección titulada “discoverServices”Descubre los servicios de un dispositivo conectado.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.discoverServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getServices
Sección titulada “getServices”Obtén los servicios descubiertos de un dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { services } = await BluetoothLowEnergy.getServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getConnectedDevices
Sección titulada “getConnectedDevices”Obtén una lista de dispositivos conectados.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { devices } = await BluetoothLowEnergy.getConnectedDevices();readCharacteristic
Sección titulada “readCharacteristic”Lee el valor de una característica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { value } = await BluetoothLowEnergy.readCharacteristic({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});writeCharacteristic
Sección titulada “writeCharacteristic”Escribe un valor en una característica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.writeCharacteristic({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A39', value: [0x01]});startCharacteristicNotifications
Sección titulada “startCharacteristicNotifications”Activa las notificaciones de una característica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});stopCharacteristicNotifications
Sección titulada “stopCharacteristicNotifications”Desactiva las notificaciones de una característica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});readDescriptor
Sección titulada “readDescriptor”Lee el valor de un descriptor.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { value } = await BluetoothLowEnergy.readDescriptor({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37', descriptor: '2902'});writeDescriptor
Sección titulada “writeDescriptor”Escribe un valor en un descriptor.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.writeDescriptor({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37', descriptor: '2902', value: [0x01, 0x00]});readRssi
Sección titulada “readRssi”Lee el RSSI (fuerza de señal) de un dispositivo conectado.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { rssi } = await BluetoothLowEnergy.readRssi({ deviceId: 'AA:BB:CC:DD:EE:FF' });requestMtu
Sección titulada “requestMtu”Solicita un cambio de tamaño de MTU (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { mtu } = await BluetoothLowEnergy.requestMtu({ deviceId: 'AA:BB:CC:DD:EE:FF', mtu: 512});requestConnectionPriority
Sección titulada “requestConnectionPriority”Solicita prioridad de conexión (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.requestConnectionPriority({ deviceId: 'AA:BB:CC:DD:EE:FF', priority: 'high'});startAdvertising
Sección titulada “startAdvertising”Comienza a anunciar como periférico (servidor BLE).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startAdvertising({ name: 'MyDevice', services: ['180D']});stopAdvertising
Sección titulada “stopAdvertising”Detener el advertising.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopAdvertising();startForegroundService
Sección titulada “startForegroundService”Inicia un servicio de primer plano para mantener las conexiones BLE en segundo plano (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startForegroundService({ title: 'BLE Connection', body: 'Maintaining connection...'});stopForegroundService
Sección titulada “stopForegroundService”Detener el servicio en primer plano (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopForegroundService();addListener('adapterStateChanged')
Sección titulada “addListener('adapterStateChanged')”Escucha los cambios de estado de energía del adaptador Bluetooth. Este evento se emite en iOS y Android. No se emite en web. Disponible desde la versión 8.2.11.
import { BluetoothLowEnergy, AdapterStateChangedEvent } from '@capgo/capacitor-bluetooth-low-energy';
const handle = await BluetoothLowEnergy.addListener( 'adapterStateChanged', (event: AdapterStateChangedEvent) => { console.log('Bluetooth enabled:', event.enabled); },);
// later:await handle.remove();El payload es { enabled: boolean } únicamente. enabled es true cuando el adaptador está encendido, y false cuando no lo está. El plugin no añade otros campos.
Cuándo se dispara:
- Android: cuando el sistema informa
BluetoothAdapter.STATE_OFF(enabled: false) oSTATE_ON(enabled: true). Los estados intermedios de encendido y apagado no emiten este evento. El estado actual no se envía en elinitialize()momento, solo cuando el adaptador alcanza posteriormente el estado off o on. - iOS: cuando el Core Bluetooth manager del modo actual informa de un nuevo estado, y solo si
enabledcambió desde la última emisión.enabledestruesolo cuando el estado de ese manager es.poweredOn. Otros estados (apagado, reiniciando, no autorizado, etc.) se informan comoenabled: false. Encentralmodo, la fuente es el central manager. Enperipheralmodo, la fuente es el peripheral manager (el callback del central manager no emite). Crear el manager duranteinitialize()también informa del estado actual. Ese callback de estado inicial puede dispararse antes de queinitialize()se resuelva, y el plugin no retiene el evento, por lo que un listener registrado después podría perderlo y solo escuchar cambios posteriores. Registra el listener antes de llamar ainitialize(). iOS puede emitirenabled: falsey luegoenabled: truesi el manager inicia en un estado diferente a.poweredOny luego se enciende. Después de queinitialize()se resuelva, llama aisEnabled()para leer el estado actual del adaptador.
Cuando el Bluetooth se apaga, el plugin también descarta los registros locales de servicios y características GATT que estaba manteniendo, y emite centralDisconnected para cada central rastreado, antes de adapterStateChanged con enabled: false. En Android también cierra el servidor GATT y limpia el callback de advertise. El plugin no restaura los servicios ni la publicidad por sí solo.
Si tu app es un peripheral, espera a adapterStateChanged con enabled: true, luego llama a addGattService de nuevo para cada servicio y startAdvertising de nuevo. Como el plugin limpió sus registros locales, añadir el mismo UUID de servicio se acepta en lugar de rechazarse con “Service already exists”. En Android, un scanner (modo central) o advertiser (modo peripheral) ausente se vuelve a adquirir cuando el adaptador vuelve. Aun así, debes añadir los servicios e iniciar la publicidad tú mismo.
Referencia de tipos
Sección titulada “Referencia de tipos”InitializeOptions
Sección titulada “InitializeOptions”Opciones de inicialización del plugin.
export interface InitializeOptions { /** * The mode to initialize the plugin in. * - 'central': Act as a BLE central (client) * - 'peripheral': Act as a BLE peripheral (server) * * @default 'central' * @since 1.0.0 */ mode?: 'central' | 'peripheral';}IsAvailableResult
Sección titulada “IsAvailableResult”Resultado del método isAvailable.
export interface IsAvailableResult { /** * Whether Bluetooth is available on the device. * * @since 1.0.0 */ available: boolean;}IsEnabledResult
Sección titulada “IsEnabledResult”Resultado del método isEnabled.
export interface IsEnabledResult { /** * Whether Bluetooth is enabled on the device. * * @since 1.0.0 */ enabled: boolean;}IsLocationEnabledResult
Sección titulada “IsLocationEnabledResult”Resultado del método isLocationEnabled.
export interface IsLocationEnabledResult { /** * Whether location services are enabled on the device. * * @since 1.0.0 */ enabled: boolean;}PermissionStatus
Sección titulada “PermissionStatus”Estado de permisos para Bluetooth y ubicación.
export interface PermissionStatus { /** * Bluetooth permission status. * * @since 1.0.0 */ bluetooth: PermissionState;
/** * Location permission status (Android only). * * @since 1.0.0 */ location: PermissionState;}StartScanOptions
Sección titulada “StartScanOptions”Opciones para iniciar un escaneo.
export interface StartScanOptions { /** * List of service UUIDs to filter by. * Only devices advertising these services will be returned. * * @since 1.0.0 */ services?: string[];
/** * Scan timeout in milliseconds. * Set to 0 for no timeout. * * @default 0 * @since 1.0.0 */ timeout?: number;
/** * Whether to allow duplicate scan results. * * @default false * @since 1.0.0 */ allowDuplicates?: boolean;}ConnectOptions
Sección titulada “ConnectOptions”Opciones para conectar a un dispositivo.
export interface ConnectOptions { /** * The device ID (MAC address on Android, UUID on iOS). * * @since 1.0.0 */ deviceId: string;
/** * Whether to automatically connect when the device becomes available. * * @default false * @since 1.0.0 */ autoConnect?: boolean;}DisconnectOptions
Sección titulada “DisconnectOptions”Opciones para desconectar de un dispositivo.
export interface DisconnectOptions { /** * The device ID to disconnect from. * * @since 1.0.0 */ deviceId: string;}CreateBondOptions
Sección titulada “CreateBondOptions”Opciones para crear un vínculo.
export interface CreateBondOptions { /** * The device ID to bond with. * * @since 1.0.0 */ deviceId: string;}IsBondedOptions
Sección titulada “IsBondedOptions”Opciones para verificar el estado del vínculo.
export interface IsBondedOptions { /** * The device ID to check. * * @since 1.0.0 */ deviceId: string;}IsBondedResult
Sección titulada “IsBondedResult”Resultado del método isBonded.
export interface IsBondedResult { /** * Whether the device is bonded. * * @since 1.0.0 */ bonded: boolean;}DiscoverServicesOptions
Sección titulada “DiscoverServicesOptions”Opciones para descubrir servicios.
export interface DiscoverServicesOptions { /** * The device ID to discover services on. * * @since 1.0.0 */ deviceId: string;}AdapterStateChangedEvent
Sección titulada “AdapterStateChangedEvent”Evento emitido cuando el adaptador Bluetooth se enciende o se apaga. Desde la versión 8.2.11.
export interface AdapterStateChangedEvent { /** * Whether Bluetooth is enabled (adapter powered on). * * @since 8.2.11 */ enabled: boolean;}Fuente de verdad
Sección titulada “Fuente de verdad”Esta página se genera a partir del plugin src/definitions.ts. Vuelve a ejecutar el sync cuando el API público cambie en upstream.
Continúa desde Getting Started
Sección titulada “Continúa desde Primeros pasos”Si estás usando Primeros pasos para planificar las operaciones del dashboard y de API, conéctalo con Usando @capgo/capacitor-bluetooth-low-energy para la capacidad nativa en Uso de @capgo/capacitor-bluetooth-low-energy Resumen de API para los detalles de implementación en API Overview, Introducción para los detalles de implementación en la Introducción, Claves de API para los detalles de implementación en las claves de API, y Dispositivos para el detalle de implementación en Devices.