Per iniziare
Copia un prompt di configurazione con i passaggi di installazione e la guida markdown completa per questo 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.
Puoi usare il nostro setup assistito dall'IA per installare il plugin. Aggiungi le skill Capgo al tuo strumento di IA usando il seguente comando:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsPoi usa il seguente prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-bluetooth-low-energy` plugin in my project.Se preferisci la configurazione manuale, installa il plugin eseguendo questi comandi e segui le istruzioni specifiche per piattaforma qui sotto:
bun add @capgo/capacitor-bluetooth-low-energynpx cap syncImporta
Sezione intitolata “Import”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';Avvio rapido
Sezione intitolata “Quick start”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });Esempio: shimWebBluetooth
Sezione intitolata “Esempio: shimWebBluetooth”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();Esempio: isAvailable
Sezione intitolata “Esempio: isAvailable”import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();Errori comuni
Sezione intitolata “Errori comuni”- Permessi: chiamata
checkPermissions()poirequestPermissions()quando necessario. - Listener: rimuovi gli handle quando gli schermi vengono smontati.
- Inizializza una volta: esegui il setup durante il bootstrap dell'app.
Panoramica API
Sezione intitolata “Panoramica API”initialize
Sezione intitolata “initialize”Inizializza il plugin BLE.
Deve essere chiamato prima di qualsiasi altro metodo, tranne addListener(). Registra adapterStateChanged prima di chiamare initialize() in modo da non perdere l'evento di stato iniziale di iOS.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });shimWebBluetooth
Sezione intitolata “shimWebBluetooth”Installa lo shim Web Bluetooth di Capacitor su navigator.bluetooth.
Chiamalo manualmente prima di usare il API Web Bluetooth da un'app nativa Capacitor.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();isAvailable
Sezione intitolata “isAvailable”Verifica se il Bluetooth è disponibile sul dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();isEnabled
Sezione intitolata “isEnabled”Verifica se il Bluetooth è abilitato sul dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isEnabled();isLocationEnabled
Sezione intitolata “isLocationEnabled”Verifica se i servizi di localizzazione sono attivi (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isLocationEnabled();openAppSettings
Sezione intitolata “openAppSettings”Apri la pagina delle impostazioni dell'app.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openAppSettings();openBluetoothSettings
Sezione intitolata “openBluetoothSettings”Apri la pagina delle impostazioni Bluetooth (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openBluetoothSettings();openLocationSettings
Sezione intitolata “openLocationSettings”Apri la pagina delle impostazioni di posizione (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openLocationSettings();checkPermissions
Sezione intitolata “checkPermissions”Controlla lo stato attuale dei permessi.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.checkPermissions();requestPermissions
Sezione intitolata “requestPermissions”Richiedi i permessi Bluetooth.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.requestPermissions();startScan
Sezione intitolata “startScan”Avvia la scansione dei dispositivi BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startScan({ services: ['180D'], // Heart Rate Service timeout: 10000});stopScan
Sezione intitolata “stopScan”Interrompi la scansione dei dispositivi BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopScan();connect
Sezione intitolata “connect”Connettiti a un dispositivo BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' });disconnect
Sezione intitolata “disconnect”Disconnettiti da un dispositivo BLE.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.disconnect({ deviceId: 'AA:BB:CC:DD:EE:FF' });createBond
Sezione intitolata “createBond”Crea un accoppiamento 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
Sezione intitolata “isBonded”Controlla se un dispositivo è accoppiato (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bonded } = await BluetoothLowEnergy.isBonded({ deviceId: 'AA:BB:CC:DD:EE:FF' });discoverServices
Sezione intitolata “discoverServices”Rileva i servizi su un dispositivo connesso.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.discoverServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getServices
Sezione intitolata “getServices”Ottieni i servizi scoperti per un dispositivo.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { services } = await BluetoothLowEnergy.getServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getConnectedDevices
Sezione intitolata “getConnectedDevices”Ottieni l'elenco dei dispositivi connessi.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { devices } = await BluetoothLowEnergy.getConnectedDevices();readCharacteristic
Sezione intitolata “readCharacteristic”Leggi il valore di una caratteristica.
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
Sezione intitolata “writeCharacteristic”Scrivi un valore in una caratteristica.
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
Sezione intitolata “startCharacteristicNotifications”Avvia le notifiche per una caratteristica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});stopCharacteristicNotifications
Sezione intitolata “stopCharacteristicNotifications”Interrompe le notifiche per una caratteristica.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});readDescriptor
Sezione intitolata “readDescriptor”Legge il valore di un descrittore.
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
Sezione intitolata “writeDescriptor”Scrive un valore in un descrittore.
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
Sezione intitolata “readRssi”Legge l'RSSI (intensità del segnale) di un dispositivo connesso.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { rssi } = await BluetoothLowEnergy.readRssi({ deviceId: 'AA:BB:CC:DD:EE:FF' });requestMtu
Sezione intitolata “requestMtu”Richiede la modifica della dimensione 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
Sezione intitolata “requestConnectionPriority”Richiede la priorità di connessione (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.requestConnectionPriority({ deviceId: 'AA:BB:CC:DD:EE:FF', priority: 'high'});startAdvertising
Sezione intitolata “startAdvertising”Avvia l'advertising come periferica (BLE server).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startAdvertising({ name: 'MyDevice', services: ['180D']});stopAdvertising
Sezione intitolata “stopAdvertising”Interrompi l'advertising.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopAdvertising();startForegroundService
Sezione intitolata “startForegroundService”Avvia un foreground service per mantenere le connessioni BLE in background (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startForegroundService({ title: 'BLE Connection', body: 'Maintaining connection...'});stopForegroundService
Sezione intitolata “stopForegroundService”Arresta il foreground service (solo Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopForegroundService();addListener('adapterStateChanged')
Sezione intitolata “addListener('adapterStateChanged')”Ascolta le variazioni di alimentazione dell'adattatore Bluetooth. Questo evento viene emesso su iOS e Android. Non viene emesso su web. Disponibile dalla versione 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();Il payload è { enabled: boolean } soltanto. enabled è true quando l'adattatore è acceso, e false quando non lo è. Il plugin non aggiunge altri campi.
Quando viene emesso:
- Android: quando il sistema riporta
BluetoothAdapter.STATE_OFF(enabled: false) oSTATE_ON(enabled: true). Gli stati intermedi di accensione e spegnimento non emettono questo evento. Lo stato corrente non viene inviato alinitialize()tempo, solo quando l'adattatore passa successivamente a off o on. - iOS: quando il Core Bluetooth manager per la modalità corrente riporta un nuovo stato, e solo se
enabledè cambiato dall'ultima emissione.enabledètruesolo quando lo stato di quel manager è.poweredOn. Gli altri stati (powered off, resetting, unauthorized, e simili) vengono riportati comeenabled: false. Incentralin modalità central, la sorgente è il central manager. Inperipheralmodalità peripheral, la sorgente è il peripheral manager (il callback del central manager non emette). La creazione del manager duranteinitialize()riporta anche lo stato corrente. Quel callback di stato iniziale può scattare prima cheinitialize()si risolva, e il plugin non conserva l'evento, quindi un listener registrato successivamente potrebbe perderlo e ricevere solo le modifiche successive. Registra il listener prima di chiamareinitialize(). iOS può emettereenabled: falsee poienabled: truese il manager parte in uno stato diverso da.poweredOne diventa successivamente powered on. Dopo cheinitialize()si è risolto, chiamaisEnabled()per leggere lo stato corrente dell'adattatore.
Quando il Bluetooth si spegne, il plugin elimina anche i record locali dei servizi e delle caratteristiche GATT che stava mantenendo, ed emette centralDisconnected per ogni central tracciato, prima di adapterStateChanged con enabled: false. Su Android chiude anche il server GATT e rimuove il callback di advertising. Il plugin non ripristina da solo i servizi né l'advertising.
Se la tua app è un periferico, attendi adapterStateChanged con enabled: true, quindi chiama addGattService di nuovo per ogni servizio e startAdvertising di nuovo. Poiché il plugin ha cancellato i suoi record locali, l'aggiunta dello stesso UUID di servizio viene accettata invece di essere rifiutata con “Service already exists”. Su Android, uno scanner (modalità centrale) o un advertiser (modalità periferica) mancante viene riacquisito quando l'adattatore torna disponibile. Devi comunque aggiungere i servizi e avviare l'advertising tu stesso.
Riferimento ai tipi
Sezione: “Type Reference”InitializeOptions
Sezione intitolata “InitializeOptions”Opzioni di inizializzazione 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
Sezione intitolata “IsAvailableResult”Risultato del metodo isAvailable.
export interface IsAvailableResult { /** * Whether Bluetooth is available on the device. * * @since 1.0.0 */ available: boolean;}IsEnabledResult
Sezione intitolata “IsEnabledResult”Risultato del metodo isEnabled.
export interface IsEnabledResult { /** * Whether Bluetooth is enabled on the device. * * @since 1.0.0 */ enabled: boolean;}IsLocationEnabledResult
Sezione intitolata “IsLocationEnabledResult”Risultato del metodo isLocationEnabled.
export interface IsLocationEnabledResult { /** * Whether location services are enabled on the device. * * @since 1.0.0 */ enabled: boolean;}PermissionStatus
Sezione intitolata “PermissionStatus”Stato dei permessi per Bluetooth e posizione.
export interface PermissionStatus { /** * Bluetooth permission status. * * @since 1.0.0 */ bluetooth: PermissionState;
/** * Location permission status (Android only). * * @since 1.0.0 */ location: PermissionState;}StartScanOptions
Sezione intitolata “StartScanOptions”Opzioni per avviare una scansione.
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
Sezione intitolata “ConnectOptions”Opzioni per connettersi 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
Sezione intitolata “DisconnectOptions”Opzioni per disconnettersi da un dispositivo.
export interface DisconnectOptions { /** * The device ID to disconnect from. * * @since 1.0.0 */ deviceId: string;}CreateBondOptions
Sezione intitolata “CreateBondOptions”Opzioni per creare un bond.
export interface CreateBondOptions { /** * The device ID to bond with. * * @since 1.0.0 */ deviceId: string;}IsBondedOptions
Sezione intitolata “IsBondedOptions”Opzioni per verificare lo stato del bond.
export interface IsBondedOptions { /** * The device ID to check. * * @since 1.0.0 */ deviceId: string;}IsBondedResult
Sezione intitolata “IsBondedResult”Risultato del metodo isBonded.
export interface IsBondedResult { /** * Whether the device is bonded. * * @since 1.0.0 */ bonded: boolean;}DiscoverServicesOptions
Sezione intitolata “DiscoverServicesOptions”Opzioni per la scoperta dei servizi.
export interface DiscoverServicesOptions { /** * The device ID to discover services on. * * @since 1.0.0 */ deviceId: string;}AdapterStateChangedEvent
Sezione intitolata “AdapterStateChangedEvent”Evento emesso quando l'adattatore Bluetooth viene acceso o spento. Da 8.2.11.
export interface AdapterStateChangedEvent { /** * Whether Bluetooth is enabled (adapter powered on). * * @since 8.2.11 */ enabled: boolean;}Fonte di verità
Sezione intitolata “Fonte di verità”Questa pagina è generata dal src/definitions.ts. Riesegui la sync quando il API pubblico cambia upstream.
Continua da Getting Started
Sezione intitolata “Continua da Getting Started”Se stai usando Per iniziare per pianificare le operazioni della dashboard e di API, collegalo a Utilizzo di @capgo/capacitor-bluetooth-low-energy per la funzionalità nativa nella guida Usare @capgo/capacitor-bluetooth-low-energy, Panoramica API per i dettagli di implementazione in Panoramica di API, Introduzione per i dettagli di implementazione in Introduzione, Chiavi API per i dettagli di implementazione in Chiavi API, e Dispositivi per i dettagli di implementazione in Dispositivi.