Saltar al contenido

Primeros pasos

GitHub

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:

Ventana de terminal
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Luego 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:

Ventana de terminal
bun add @capgo/capacitor-bluetooth-low-energy
npx cap sync
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();
  • Permisos: llama a checkPermissions() luego requestPermissions() cuando sea necesario.
  • Listeners: elimina los handles cuando se desmonten las pantallas.
  • Inicializa una vez: ejecuta setup durante el bootstrap de la app.

Inicializa el plugin de BLE. Debe llamarse antes de cualquier otro método.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });

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

Comprueba si Bluetooth está disponible en el dispositivo.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();

Comprueba si Bluetooth está activado en el dispositivo.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isEnabled();

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

Abre la página de ajustes de la app.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openAppSettings();

Abre la página de ajustes de Bluetooth (solo Android).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openBluetoothSettings();

Abre la página de ajustes de ubicación (solo Android).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openLocationSettings();

Comprueba el estado actual de los permisos.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.checkPermissions();

Solicita permisos de Bluetooth.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.requestPermissions();

Empieza a escanear dispositivos BLE.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startScan({
services: ['180D'], // Heart Rate Service
timeout: 10000
});

Detén el escaneo de dispositivos BLE.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopScan();

Conéctate a un dispositivo BLE.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' });

Desconéctate de un dispositivo BLE.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.disconnect({ deviceId: 'AA:BB:CC:DD:EE:FF' });

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

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

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

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

Obtén una lista de dispositivos conectados.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { devices } = await BluetoothLowEnergy.getConnectedDevices();

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

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

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

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

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

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

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

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

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

Comienza a anunciar como periférico (servidor BLE).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startAdvertising({
name: 'MyDevice',
services: ['180D']
});

Detener el advertising.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopAdvertising();

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

Detener el servicio en primer plano (solo Android).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopForegroundService();

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

Resultado del método isAvailable.

export interface IsAvailableResult {
/**
* Whether Bluetooth is available on the device.
*
* @since 1.0.0
*/
available: boolean;
}

Resultado del método isEnabled.

export interface IsEnabledResult {
/**
* Whether Bluetooth is enabled on the device.
*
* @since 1.0.0
*/
enabled: boolean;
}

Resultado del método isLocationEnabled.

export interface IsLocationEnabledResult {
/**
* Whether location services are enabled on the device.
*
* @since 1.0.0
*/
enabled: boolean;
}

Estado de los permisos de 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;
}

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

Opciones para conectarse 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;
}

Opciones para desconectarse de un dispositivo.

export interface DisconnectOptions {
/**
* The device ID to disconnect from.
*
* @since 1.0.0
*/
deviceId: string;
}

Opciones para crear un vínculo.

export interface CreateBondOptions {
/**
* The device ID to bond with.
*
* @since 1.0.0
*/
deviceId: string;
}

Opciones para verificar el estado del vínculo.

export interface IsBondedOptions {
/**
* The device ID to check.
*
* @since 1.0.0
*/
deviceId: string;
}

Resultado del método isBonded.

export interface IsBondedResult {
/**
* Whether the device is bonded.
*
* @since 1.0.0
*/
bonded: boolean;
}

Opciones para descubrir servicios.

export interface DiscoverServicesOptions {
/**
* The device ID to discover services on.
*
* @since 1.0.0
*/
deviceId: string;
}

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.

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.