Erste Schritte
Kopiere einen Setup-Prompt mit den Installationsschritten und dem vollständigen Markdown-Guide für dieses 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.
Installieren
Abschnitt „Installation“Du kannst unser KI-gestütztes Setup nutzen, um das Plugin zu installieren. Füge die Capgo Skills mit dem folgenden Befehl deinem KI-Tool hinzu:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsNutze dann diesen Prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-bluetooth-low-energy` plugin in my project.Wenn du ein manuelles Setup bevorzugst, installiere das Plugin mit den folgenden Befehlen und befolge die plattformspezifischen Anweisungen unten:
bun add @capgo/capacitor-bluetooth-low-energynpx cap syncImportieren
Abschnitt mit dem Titel „Import“import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';Quickstart
Abschnitt „Quick start“import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });Beispiel: shimWebBluetooth
Abschnitt „Beispiel: shimWebBluetooth“import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();Beispiel: isAvailable
Abschnitt „Beispiel: isAvailable“import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();Häufige Stolperfallen
Abschnitt „Häufige Fallstricke“- Berechtigungen: aufrufen
checkPermissions()dannrequestPermissions()bei Bedarf. - Listener: Handles beim Unmounten von Screens entfernen.
- Einmalige Initialisierung: Setup beim App-Bootstrap ausführen.
API Übersicht
Abschnitt „API Übersicht“initialize
Abschnitt „initialize“Initialisiere das BLE-Plugin.
Muss vor jeder anderen Methode aufgerufen werden, außer addListener()nicht. Registriere adapterStateChanged vor dem Aufruf von initialize() damit das initiale iOS-State-Event nicht verpasst wird.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.initialize({ mode: 'central' });shimWebBluetooth
Abschnitt mit dem Titel „shimWebBluetooth“Installiere den Capacitor Web Bluetooth Shim auf navigator.bluetooth.
Rufen Sie dies manuell auf, bevor Sie Web Bluetooth API in einer nativen Capacitor-App verwenden.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
BluetoothLowEnergy.shimWebBluetooth();isAvailable
Abschnitt mit dem Titel „isAvailable“Prüft, ob Bluetooth auf dem Gerät verfügbar ist.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { available } = await BluetoothLowEnergy.isAvailable();isEnabled
Abschnitt „isEnabled“Prüfen, ob Bluetooth auf dem Gerät aktiviert ist.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isEnabled();isLocationEnabled
Abschnitt mit dem Titel „isLocationEnabled“Prüfen, ob die Standortdienste aktiviert sind (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { enabled } = await BluetoothLowEnergy.isLocationEnabled();openAppSettings
Abschnitt mit dem Titel „openAppSettings“Öffne die App-Einstellungen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openAppSettings();openBluetoothSettings
Abschnitt mit dem Titel „openBluetoothSettings“Öffne die Bluetooth-Einstellungen (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openBluetoothSettings();openLocationSettings
Abschnitt mit dem Titel „openLocationSettings“Öffne die Standort-Einstellungen (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.openLocationSettings();checkPermissions
Abschnitt „checkPermissions“Prüfe den aktuellen Berechtigungsstatus.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.checkPermissions();requestPermissions
Abschnitt „requestPermissions“Bluetooth-Berechtigungen anfordern.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bluetooth, location } = await BluetoothLowEnergy.requestPermissions();startScan
Abschnitt „startScan“Scan nach BLE-Geräten starten.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startScan({ services: ['180D'], // Heart Rate Service timeout: 10000});stopScan
Abschnitt „stopScan“Scan nach BLE-Geräten stoppen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopScan();connect
Abschnitt „connect“Mit einem BLE-Gerät verbinden.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.connect({ deviceId: 'AA:BB:CC:DD:EE:FF' });disconnect
Abschnitt „disconnect“Verbindung zu einem BLE-Gerät trennen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.disconnect({ deviceId: 'AA:BB:CC:DD:EE:FF' });createBond
Abschnitt „createBond“Einen Bond mit einem BLE-Gerät erstellen (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.createBond({ deviceId: 'AA:BB:CC:DD:EE:FF' });isBonded
Abschnitt „isBonded“Prüfen, ob ein Gerät gebondet ist (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { bonded } = await BluetoothLowEnergy.isBonded({ deviceId: 'AA:BB:CC:DD:EE:FF' });discoverServices
Abschnitt „discoverServices“Services auf einem verbundenen Gerät entdecken.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.discoverServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getServices
Abschnitt „getServices“Entdeckte Services eines Geräts abrufen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { services } = await BluetoothLowEnergy.getServices({ deviceId: 'AA:BB:CC:DD:EE:FF' });getConnectedDevices
Abschnitt mit dem Titel “getConnectedDevices”Liste der verbundenen Geräte abrufen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { devices } = await BluetoothLowEnergy.getConnectedDevices();readCharacteristic
Abschnitt mit dem Titel “readCharacteristic”Wert einer Characteristic lesen.
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
Abschnitt mit dem Titel “writeCharacteristic”Wert in eine Characteristic schreiben.
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
Abschnitt mit dem Titel “startCharacteristicNotifications”Benachrichtigungen für eine Characteristic starten.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});stopCharacteristicNotifications
Abschnitt „stopCharacteristicNotifications“Benachrichtigungen für eine Characteristic stoppen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopCharacteristicNotifications({ deviceId: 'AA:BB:CC:DD:EE:FF', service: '180D', characteristic: '2A37'});readDescriptor
Abschnitt „readDescriptor“Einen Descriptor-Wert lesen.
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
Abschnitt „writeDescriptor“Einen Wert in einen Descriptor schreiben.
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
Abschnitt „readRssi“Den RSSI (Signalstärke) eines verbundenen Geräts lesen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { rssi } = await BluetoothLowEnergy.readRssi({ deviceId: 'AA:BB:CC:DD:EE:FF' });requestMtu
Abschnitt mit dem Titel „requestMtu“MTU-Größenänderung anfordern (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
const { mtu } = await BluetoothLowEnergy.requestMtu({ deviceId: 'AA:BB:CC:DD:EE:FF', mtu: 512});requestConnectionPriority
Abschnitt mit dem Titel „requestConnectionPriority“Verbindungspriorität anfordern (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.requestConnectionPriority({ deviceId: 'AA:BB:CC:DD:EE:FF', priority: 'high'});startAdvertising
Abschnitt mit dem Titel „startAdvertising“Advertising als Peripheriegerät (BLE-Server) starten.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startAdvertising({ name: 'MyDevice', services: ['180D']});stopAdvertising
Abschnitt mit dem Titel „stopAdvertising“Werbung stoppen.
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopAdvertising();startForegroundService
Abschnitt mit dem Titel „startForegroundService“Startet einen Foreground Service, um BLE-Verbindungen im Hintergrund aufrechtzuerhalten (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.startForegroundService({ title: 'BLE Connection', body: 'Maintaining connection...'});stopForegroundService
Abschnitt mit dem Titel „stopForegroundService“Stoppt den Foreground Service (nur Android).
import { BluetoothLowEnergy } from '@capgo/capacitor-bluetooth-low-energy';
await BluetoothLowEnergy.stopForegroundService();addListener('adapterStateChanged')
Abschnitt mit dem Titel “addListener('adapterStateChanged')”Hört auf Bluetooth-Adapter-Energieänderungen. Dieses Ereignis wird auf iOS und Android ausgelöst. Es wird nicht im Web ausgelöst. Verfügbar seit 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();Die Payload ist { enabled: boolean } nur. enabled ist true wenn der Adapter eingeschaltet ist, und false wenn er nicht eingeschaltet ist. Das Plugin fügt keine anderen Felder hinzu.
Wann es ausgelöst wird:
- Android: wenn das System meldet
BluetoothAdapter.STATE_OFF(enabled: false) oderSTATE_ON(enabled: true). Zwischenzustände beim Einschalten und Ausschalten lösen dieses Ereignis nicht aus. Der aktuelle Zustand wird nicht zuminitialize()Zeit, nur wenn der Adapter später den Zustand off oder on erreicht. - iOS: wenn der Core-Bluetooth-Manager für den aktuellen Modus einen neuen Zustand meldet und nur, wenn
enabledsich seit der letzten Ausgabe geändert hat.enabledisttruenur, wenn der Zustand dieses Managers.poweredOnist. Andere Zustände (aus, zurücksetzen, nicht autorisiert und ähnliche) werden alsenabled: false. Incentralmodus, in dem die Quelle der zentrale Manager ist. Inperipheralmodus, in dem die Quelle der Peripheral Manager ist (der Callback des Central Managers wird nicht ausgelöst). Erstellen des Managers währendinitialize()meldet auch den aktuellen Zustand. Dieser initiale State-Callback kann vorinitialize()resolves, and the plugin does not retain the event, so a listener registered afterward may miss it and only hear later changes. Register the listener before callinginitialize(). iOS kann auslösenenabled: falseund dannenabled: truewenn der Manager in einem anderen Zustand als.poweredOnund später wieder eingeschaltet wird. Danachinitialize()aufgelöst, aufrufenisEnabled()um den aktuellen Adapterstatus zu lesen.
Wenn Bluetooth ausgeschaltet wird, verwirft das Plugin auch die lokalen GATT-Service- und Characteristic-Einträge, die es gehalten hat, und sendet centralDisconnected für jede verfolgte Zentrale, bevor adapterStateChanged mit enabled: false. Auf Android schließt es außerdem den GATT-Server und räumt den Advertise-Callback auf. Das Plugin stellt Services oder Advertising nicht von selbst wieder her.
Wenn deine App ein Peripheral ist, warte auf adapterStateChanged mit enabled: true, dann aufrufen addGattService wieder für jeden Service und startAdvertising wieder. Da das Plugin seine lokalen Datensätze gelöscht hat, wird das Hinzufügen desselben Service-UUIDs akzeptiert, statt mit „Service already exists“ abgelehnt zu werden. Auf Android wird ein fehlender Scanner (Central-Modus) oder Advertiser (Peripheral-Modus) neu beschafft, wenn der Adapter zurückkehrt. Du musst die Services selbst hinzufügen und das Advertising selbst starten.
Typreferenz
Abschnitt mit dem Titel „Typreferenz“InitializeOptions
Abschnitt „InitializeOptions“Initialisierungsoptionen für das 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
Abschnitt mit dem Titel „IsAvailableResult“Ergebnis der isAvailable-Methode.
export interface IsAvailableResult { /** * Whether Bluetooth is available on the device. * * @since 1.0.0 */ available: boolean;}IsEnabledResult
Abschnitt „IsEnabledResult“Ergebnis der isEnabled-Methode.
export interface IsEnabledResult { /** * Whether Bluetooth is enabled on the device. * * @since 1.0.0 */ enabled: boolean;}IsLocationEnabledResult
Abschnitt mit dem Titel „IsLocationEnabledResult“Ergebnis der isLocationEnabled-Methode.
export interface IsLocationEnabledResult { /** * Whether location services are enabled on the device. * * @since 1.0.0 */ enabled: boolean;}PermissionStatus
Abschnitt „PermissionStatus“Berechtigungsstatus für Bluetooth und Standort.
export interface PermissionStatus { /** * Bluetooth permission status. * * @since 1.0.0 */ bluetooth: PermissionState;
/** * Location permission status (Android only). * * @since 1.0.0 */ location: PermissionState;}StartScanOptions
Abschnitt „StartScanOptions“Optionen zum Starten eines Scans.
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
Abschnitt „ConnectOptions“Optionen zum Verbinden mit einem Gerät.
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
Abschnitt „DisconnectOptions“Optionen zum Trennen von einem Gerät.
export interface DisconnectOptions { /** * The device ID to disconnect from. * * @since 1.0.0 */ deviceId: string;}CreateBondOptions
Abschnitt „CreateBondOptions“Optionen zum Erstellen einer Kopplung.
export interface CreateBondOptions { /** * The device ID to bond with. * * @since 1.0.0 */ deviceId: string;}IsBondedOptions
Abschnitt „IsBondedOptions“Optionen zum Prüfen des Bonding-Status.
export interface IsBondedOptions { /** * The device ID to check. * * @since 1.0.0 */ deviceId: string;}IsBondedResult
Abschnitt „IsBondedResult“Ergebnis der isBonded-Methode.
export interface IsBondedResult { /** * Whether the device is bonded. * * @since 1.0.0 */ bonded: boolean;}DiscoverServicesOptions
Abschnitt „DiscoverServicesOptions“Optionen zum Entdecken von Services.
export interface DiscoverServicesOptions { /** * The device ID to discover services on. * * @since 1.0.0 */ deviceId: string;}AdapterStateChangedEvent
Abschnitt mit dem Titel „AdapterStateChangedEvent“Ereignis, das ausgelöst wird, wenn der Bluetooth-Adapter ein- oder ausgeschaltet wird. Seit 8.2.11.
export interface AdapterStateChangedEvent { /** * Whether Bluetooth is enabled (adapter powered on). * * @since 8.2.11 */ enabled: boolean;}Source of Truth
Abschnitt mit dem Titel „Source of Truth“Diese Seite wird aus dem Plugin generiert src/definitions.ts. Führe den Sync erneut aus, wenn sich das öffentliche API upstream ändert.
Weiter geht's nach Getting Started
Abschnitt: „Weiter geht’s mit Getting Started“Wenn du es nutzt Erste Schritte um Dashboard- und API-Operationen zu planen, verbinde es mit @capgo/capacitor-bluetooth-low-energy verwenden für die native Funktion in „@capgo/capacitor-bluetooth-low-energy verwenden“, API Übersicht für Details zur Implementierung im API Overview, Einführung für die Implementierungsdetails in der Einleitung, API Schlüssel für das Implementierungsdetail in API Keys und Geräte für das Implementierungsdetail in Devices.