Aller au contenu

Prise en main

GitHub

Vous pouvez utiliser notre configuration assistée par IA pour installer le plugin. Ajoutez les skills Capgo à votre outil d'IA avec la commande suivante :

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

Utilisez ensuite le prompt suivant :

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-bluetooth-low-energy` plugin in my project.

Si vous préférez une installation manuelle, installez le plugin en exécutant les commandes suivantes et suivez les instructions spécifiques à chaque plateforme ci-dessous :

Fenêtre 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();
  • Autorisations: appelez checkPermissions() puis requestPermissions() si nécessaire.
  • Écouteurs: supprimez les handles lors du démontage des écrans.
  • Initialiser une seule fois: exécutez le setup lors du bootstrap de l'app.

Initialisez le plugin BLE. Doit être appelé avant toute autre méthode, sauf addListener(). Enregistrez adapterStateChanged avant d’appeler initialize() afin de ne pas manquer l’événement d’état initial sur iOS.

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

Installer le shim Web Bluetooth Capacitor sur navigator.bluetooth. Appelez ceci manuellement avant d'utiliser l’API Web Bluetooth depuis une application native Capacitor.

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

Vérifier si le Bluetooth est disponible sur l'appareil.

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

Vérifier si le Bluetooth est activé sur l'appareil.

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

Vérifier si les services de localisation sont activés (Android uniquement).

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

Ouvrir la page des paramètres de l'application.

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

Ouvrir la page des paramètres Bluetooth (Android uniquement).

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

Ouvrir la page des paramètres de localisation (Android uniquement).

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

Vérifier le statut actuel des permissions.

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

Demander les permissions Bluetooth.

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

Lancer la recherche d'appareils BLE.

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

Arrêter la recherche d'appareils BLE.

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

Se connecter à un appareil BLE.

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

Se déconnecter d'un appareil BLE.

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

Créer un appairage avec un appareil BLE (Android uniquement).

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

Vérifier si un appareil est appairé (Android uniquement).

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

Découvrir les services sur un appareil connecté.

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

Récupérer les services découverts pour un appareil.

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

Récupérer la liste des appareils connectés.

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

Lire la valeur d'une caractéristique.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { value } = await BluetoothLowEnergy.readCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});

Écrire une valeur dans une caractéristique.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.writeCharacteristic({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A39',
value: [0x01]
});

Activer les notifications pour une caractéristique.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startCharacteristicNotifications({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});

Arrêter les notifications pour une caractéristique.

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopCharacteristicNotifications({
deviceId: 'AA:BB:CC:DD:EE:FF',
service: '180D',
characteristic: '2A37'
});

Lire la valeur d'un descripteur.

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

Écrire une valeur dans un descripteur.

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

Lire le RSSI (force du signal) d'un appareil connecté.

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

Demander un changement de taille MTU (Android uniquement).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { mtu } = await BluetoothLowEnergy.requestMtu({
deviceId: 'AA:BB:CC:DD:EE:FF',
mtu: 512
});

Demander la priorité de connexion (Android uniquement).

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

Commencer à diffuser en tant que périphérique (serveur BLE).

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

Arrêter la diffusion.

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

Démarrer un service de premier plan pour maintenir les connexions BLE en arrière-plan (Android uniquement).

import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startForegroundService({
title: 'BLE Connection',
body: 'Maintaining connection...'
});

Arrêter le service de premier plan (Android uniquement).

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

Écoutez les changements d'alimentation de l'adaptateur Bluetooth. Cet événement est émis sur iOS et Android. Il n'est pas émis sur le web. Disponible depuis la version 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();

La charge utile est { enabled: boolean } uniquement. enabled est true lorsque l'adaptateur est allumé, et false lorsqu'il est éteint. Le plugin n'ajoute pas d'autres champs.

Quand il se déclenche :

  • Android : lorsque le système signale BluetoothAdapter.STATE_OFF (enabled: false) ou STATE_ON (enabled: true). Les états intermédiaires d'allumage et d'extinction n'émettent pas cet événement. L'état actuel n'est pas envoyé au initialize() temps, uniquement lorsque l’adaptateur passe ensuite à l’état off ou on.
  • iOS : lorsque le gestionnaire Core Bluetooth pour le mode actuel signale un nouvel état, et uniquement si enabled a changé depuis la dernière émission. enabled est true uniquement lorsque l'état de ce gestionnaire est .poweredOn. Les autres états (éteint, en cours de réinitialisation, non autorisé, etc.) sont signalés comme enabled: false. Dans central en mode central, la source est le gestionnaire central. En peripheral mode périphérique, la source est le gestionnaire périphérique (le callback du gestionnaire central n'émet pas). La création du gestionnaire pendant initialize() signale également l'état actuel. Ce callback d'état initial peut se déclencher avant que initialize() ne se résolve, et le plugin ne conserve pas l'événement, donc un écouteur enregistré par la suite peut le manquer et ne recevoir que les changements ultérieurs. Enregistrez l'écouteur avant d'appeler initialize(). iOS peut émettre enabled: false puis en enabled: true si le gestionnaire démarre dans un état autre que .poweredOn et devient ensuite allumé. Après que initialize() se soit résolu, appelez isEnabled() pour lire l'état actuel de l'adaptateur.

Lorsque le Bluetooth s'éteint, le plugin supprime également les enregistrements locaux de services et de caractéristiques GATT qu'il conservait, et émet centralDisconnected pour chaque central suivi, avant adapterStateChanged par enabled: false. Sur Android, cela ferme également le serveur GATT et efface le callback de publicité. Le plugin ne restaure pas les services ni la publicité par lui-même.

Si votre application est un périphérique, attendez adapterStateChanged par enabled: true, puis appelez addGattService à nouveau pour chaque service et startAdvertising à nouveau. Comme le plugin a effacé ses enregistrements locaux, l’ajout du même UUID de service est accepté au lieu d’être rejeté avec « Service already exists ». Sur Android, un scanner (mode central) ou un émetteur (mode périphérique) manquant est réacquis lorsque l’adaptateur revient. Vous devez toujours ajouter les services et démarrer la publicité vous-même.

Options d'initialisation du 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';
}

Résultat de la méthode isAvailable.

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

Résultat de la méthode isEnabled.

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

Résultat de la méthode isLocationEnabled.

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

Statut des permissions pour le Bluetooth et la localisation.

export interface PermissionStatus {
/**
* Bluetooth permission status.
*
* @since 1.0.0
*/
bluetooth: PermissionState;
/**
* Location permission status (Android only).
*
* @since 1.0.0
*/
location: PermissionState;
}

Options pour démarrer un scan.

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

Options pour se connecter à un appareil.

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

Options pour se déconnecter d'un appareil.

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

Options pour créer un appairage.

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

Options pour vérifier l'état d'appairage.

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

Résultat de la méthode isBonded.

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

Options pour découvrir les services.

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

Événement émis lorsque l’adaptateur Bluetooth est activé ou désactivé. Depuis la version 8.2.11.

export interface AdapterStateChangedEvent {
/**
* Whether Bluetooth is enabled (adapter powered on).
*
* @since 8.2.11
*/
enabled: boolean;
}

Cette page est générée à partir de src/definitions.ts. Relancez la synchronisation lorsque l’API public change en amont.

Si vous utilisez Prise en main pour planifier les opérations du dashboard et de API, connectez-l’avec Utiliser @capgo/capacitor-bluetooth-low-energy pour la capacité native dans Utiliser @capgo/capacitor-bluetooth-low-energy, Aperçu de API pour les détails d'implémentation dans « Vue d'ensemble de API », Introduction pour les détails d'implémentation dans l'introduction, Clés API pour les détails d'implémentation dans « Clés API », et Appareils pour les détails d'implémentation dans Devices.