### Configuration Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/INDEX.md Guide to plugin configuration, initialization, and setup, including registration patterns, capabilities, platform-specific settings, and runtime configuration. ```APIDOC ## Configuration Reference ### Description Details on plugin configuration, initialization, and setup for various platforms. ### Topics Covered - Tauri plugin registration - Basic and error-tolerant initialization - Capabilities configuration with permission table - Platform-specific setup (iOS, Android, Linux, macOS) - Runtime configuration methods - Write behavior tuning - MTU configuration - Initialization patterns ``` -------------------------------- ### Install BlueZ on Fedora Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Install the BlueZ package on Fedora systems for Linux Bluetooth support. ```bash sudo dnf install bluez ``` -------------------------------- ### Rust ScanFilter Examples Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/types-reference.md Examples demonstrating how to create ScanFilter instances for discovering devices with specific services or manufacturer data. ```rust use tauri_plugin_blec::models::ScanFilter; use uuid::uuid; // Discover devices with specific service let filter = ScanFilter::Service(uuid!("180A")); // Discover devices from Apple (manufacturer code 0x004C) let filter = ScanFilter::ManufacturerData(0x004C, vec![0x02, 0x01]); ``` -------------------------------- ### Install BlueZ on Debian/Ubuntu Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Install the BlueZ package and tools on Debian-based systems for Linux Bluetooth support. ```bash sudo apt-get install bluez bluez-tools ``` -------------------------------- ### Usage Patterns Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/README.md Real-world code examples demonstrating common usage patterns in JavaScript/TypeScript and Rust. ```APIDOC ## Usage Patterns This section provides practical examples of how to use tauri-plugin-blec. ### Examples - **15 JavaScript/TypeScript patterns** with code snippets. - **8 Rust backend patterns** with code snippets. - Cross-platform usage examples. - End-to-end workflow demonstrations. - Error handling and retry strategies in practice. Refer to `usage-patterns.md` for complete details. ``` -------------------------------- ### Install JavaScript Bindings (NPM) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Install the JavaScript bindings for the BLEC plugin using NPM. This makes the plugin's functionality available in your frontend code. ```bash npm add @mnlphlp/plugin-blec ``` -------------------------------- ### Configuration Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/README.md Guide to setting up and configuring tauri-plugin-blec, including platform-specific instructions. ```APIDOC ## Configuration Reference This document explains how to set up and configure the tauri-plugin-blec. ### Configuration Options - Plugin initialization patterns - Permission and capability configuration - Runtime configuration options ### Platform-Specific Setup - iOS - Android - Linux - macOS ### Best Practices - Initialization sequences - Best practices for configuration Refer to `configuration-reference.md` for complete details. ``` -------------------------------- ### Usage Patterns Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/INDEX.md Illustrates real-world implementation patterns and provides complete code examples for common BLE workflows in both JavaScript and Rust. ```APIDOC ## Usage Patterns ### Description Real-world implementation patterns and complete code examples for common BLE workflows. ### JavaScript Patterns - Basic scan and connect workflow - Read/write data exchange - Subscribe to notifications - Service discovery - Error handling and retry logic - State monitoring - MTU and write optimization - Streaming large data - Connection monitoring in background - Complete application flow ### Rust Patterns - Examples for backend development and Tauri command handlers. ``` -------------------------------- ### Install JavaScript Bindings (Yarn) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Install the JavaScript bindings for the BLEC plugin using Yarn. This makes the plugin's functionality available in your frontend code. ```bash yarn add @mnlphlp/plugin-blec ``` -------------------------------- ### Backend BLEC Usage Example Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Example of using the BLEC plugin from the Rust backend to send data to a BLE device. This utilizes the `get_handler()` to access the plugin's functionality and `send_data` to transmit bytes to a specified characteristic. ```rust use uuid::{uuid, Uuid}; use tauri_plugin_blec::models::WriteType; const CHARACTERISTIC_UUID: Uuid = uuid!("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"); const DATA: [u8; 500] = [0; 500]; let handler = tauri_plugin_blec::get_handler().unwrap(); handler .send_data(CHARACTERISTIC_UUID, &DATA, WriteType::WithResponse) .await .unwrap(); ``` -------------------------------- ### Frontend BLEC Usage Example Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Example of using the BLEC plugin in the frontend to connect to a BLE device and send data. Ensure you have the device address and the correct characteristic UUID. The `connect` function takes a callback for disconnect events. ```typescript import { connect, sendString } from '@mnlphlp/plugin-blec' // get address by scanning for devices and selecting the desired one let address = ... // connect and run a callback on disconnect await connect(address, () => console.log('disconnected')) // send some text to a characteristic const CHARACTERISTIC_UUID = '51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B' await sendString(CHARACTERISTIC_UUID, 'Test', 'withResponse') ``` -------------------------------- ### Unified API for Platform-Specific Setup Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Check the Bluetooth adapter state and configure platform-specific settings like MTU for Android or note iOS address differences. Ensure Bluetooth is available before proceeding. ```typescript async function initializePlatform() { const state = await getAdapterState(); if (state !== 'On') { console.error('Bluetooth not available'); return false; } // Android-specific setup if (navigator.userAgent.includes('Android')) { await setAndroidMtu(517); } // iOS-specific setup if (navigator.userAgent.includes('iPhone') || navigator.userAgent.includes('iPad')) { // iOS uses UUIDs instead of MAC addresses console.log('iOS: device addresses are UUIDs'); } return true; } ``` -------------------------------- ### Rust Backend API Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/README.md Comprehensive documentation for the Rust backend API, including module initialization, handler methods, callback types, configuration, state management, and code examples. ```APIDOC ## Rust Backend API This section outlines the server-side API implemented in Rust for tauri-plugin-blec. ### Module Initialization Functions for initializing the plugin's backend module. ### Handler Methods Provides details on 20+ handler methods available for backend operations. - Signatures - Callback handler types and implementations - Configuration and state management - Code examples for Rust backends Refer to `rust-handler-api.md` for complete details. ``` -------------------------------- ### Configure MTU and Write Behavior (Rust) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Configure BLE write behavior and set the MTU request before connecting. This example includes Android-specific MTU configuration and checks the actual MTU after connection. ```rust use tauri_plugin_blec::get_handler; async fn setup_and_connect(address: &str) -> Result<(), Box> { let handler = get_handler()?; // Pre-connection: Configure write behavior handler.set_write_behaviour(Some(5000), true); // Android-specific: Set MTU request #[cfg(target_os = "android")] tauri_plugin_blec::handler::Handler::set_android_mtu_request(517); // Connect handler.connect(address, Default::default(), false).await?; // Post-connection: Check actual MTU let mtu = handler.mtu().await?; println!("Connected with MTU: {}", mtu); Ok(()) } ``` -------------------------------- ### Android Initialization Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Initializes the Android-specific BLE plugin. This function is part of the plugin's internal setup and not directly called by the user. ```APIDOC ## init(app: &AppHandle, api: PluginApi) ### Description Initializes the Android BLE plugin with the provided application handle and plugin API. ### Parameters - **app** (AppHandle) - The Tauri application handle. - **api** (PluginApi) - The plugin API for interacting with Tauri. ``` -------------------------------- ### Initialize BLE Application with Tauri Plugin BLEC Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Recommended initialization order for a complete application using the plugin. This includes checking permissions, adapter state, configuring write behavior, setting Android MTU, and starting the scan. ```typescript import { checkPermissions, getAdapterState, startScan, connect } from '@mnlphlp/plugin-blec'; async function initializeBLE() { // 1. Check permissions const hasPermissions = await checkPermissions(true); if (!hasPermissions) { console.error('BLE permissions denied'); return; } // 2. Check adapter state const state = await getAdapterState(); if (state === 'Off') { console.error('Bluetooth is disabled'); return; } // 3. Configure write behavior (optional) await setWriteBehavior(5000, false); // 4. Set Android MTU if needed (optional) if (navigator.userAgent.includes('Android')) { await setAndroidMtu(517); } // 5. Start scanning await startScan( (devices) => console.log('Found devices:', devices), 10000, false ); } // Run initialization await initializeBLE(); ``` -------------------------------- ### Production BLEC Configuration Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md This setup is recommended for reliable production applications. It includes strict permission checking, Bluetooth availability verification, and conservative write settings. ```typescript import { checkPermissions, getAdapterState, setWriteBehavior } from '@mnlphlp/plugin-blec'; async function setupProduction() { // Strict permission checking const hasPermissions = await checkPermissions(false); if (!hasPermissions) { throw new Error('BLE permissions required'); } // Verify Bluetooth is available const state = await getAdapterState(); if (state !== 'On') { throw new Error('Bluetooth adapter not available'); } // Conservative write settings for reliability await setWriteBehavior(10000, false); } ``` -------------------------------- ### Add Rust Plugin Dependency Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Install the Rust part of the plugin using Cargo. This command adds the `tauri-plugin-blec` crate to your project's dependencies. ```bash cargo add tauri-plugin-blec ``` -------------------------------- ### Start BLE Device Scan Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Initiate a scan for BLE devices. Provide a callback to process discovered devices and a timeout duration. Optionally enable iBeacon detection on Android by setting `allowIbeacons` to true. ```typescript import { startScan } from '@mnlphlp/plugin-blec'; await startScan((devices) => { devices.forEach(device => { console.log(`Found: ${device.name} (${device.address})`); }); }, 10000); ``` -------------------------------- ### init Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Initializes the plugin and panics on failure. Use this if initialization failure should halt the application. ```APIDOC ## init ### Description Initializes the plugin and panics on failure. ### Signature ```rust pub fn init() -> TauriPlugin ``` ### Returns `TauriPlugin` - Initialized TauriPlugin. ### Panics If handler initialization fails. ### Example ```rust tauri::Builder::default() .plugin(tauri_plugin_blec::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); ``` ``` -------------------------------- ### try_init Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Attempts to initialize the plugin, returning a TauriPlugin if successful. This is a safe way to initialize the plugin, allowing for error handling. ```APIDOC ## try_init ### Description Attempts to initialize the plugin, returning a TauriPlugin if successful. ### Signature ```rust pub fn try_init() -> Result, Error> ``` ### Returns `Result, Error>` - Initialized TauriPlugin or error. ### Example ```rust use tauri; let mut app = tauri::Builder::default(); app = match tauri_plugin_blec::try_init() { Ok(plugin) => app.plugin(plugin), Err(e) => { eprintln!("Failed to initialize blec plugin: {:?}", e); app } }; ``` ``` -------------------------------- ### Initialize BLE Plugin with Error Handling Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Attempts to initialize the BLE plugin, returning a TauriPlugin. Handles potential initialization errors by printing them. ```rust use tauri; let mut app = tauri::Builder::default(); app = match tauri_plugin_blec::try_init() { Ok(plugin) => app.plugin(plugin), Err(e) => { eprintln!("Failed to initialize blec plugin: {:?}", e); app } }; ``` -------------------------------- ### Complete BLE Application Flow (Rust) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Demonstrates a full BLE application lifecycle including service discovery, connection, setting up notifications, sending data, receiving a response, and disconnecting. ```rust use tauri_plugin_blec::{get_handler, OnDisconnectHandler, models::WriteType}; use uuid::uuid; use tokio::sync::mpsc; const SERVICE_UUID: uuid::Uuid = uuid!("180A"); const READ_CHAR: uuid::Uuid = uuid!("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"); const WRITE_CHAR: uuid::Uuid = uuid!("51FF12BB-3ED8-46E5-B4F9-D64E2FEC021B"); async fn ble_application(device_address: &str) -> Result<(), Box> { let handler = get_handler()?; // Step 1: Discover services println!("Discovering services..."); let services = handler.discover_services(device_address).await?; println!("Found {} services", services.len()); // Step 2: Connect println!("Connecting..."); handler.connect( device_address, OnDisconnectHandler::from_sync(|| { println!("Disconnected"); }), false, ).await?; // Step 3: Setup notifications let (tx, mut rx) = mpsc::channel(10); handler.subscribe(READ_CHAR, Some(SERVICE_UUID), move |data| { let tx = tx.clone(); async move { let _ = tx.send(data).await; } }).await?; // Step 4: Send command println!("Sending command..."); handler.send_data(WRITE_CHAR, Some(SERVICE_UUID), b"status", WriteType::WithResponse).await?; // Step 5: Wait for response if let Some(response) = tokio::time::timeout( std::time::Duration::from_secs(5), rx.recv() ).await? { println!("Response: {:?}", response); } // Step 6: Cleanup handler.disconnect().await?; println!("Done"); Ok(()) } ``` -------------------------------- ### Get Global BLE Handler Instance Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Retrieves the singleton BLE handler. Ensure the plugin is initialized before calling this. ```rust use tauri_plugin_blec; let handler = tauri_plugin_blec::get_handler()?; ``` -------------------------------- ### Initialize BLE Plugin and Panic on Failure Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Initializes the BLE plugin and panics if initialization fails. This is a simpler initialization method that assumes success. ```rust tauri::Builder::default() .plugin(tauri_plugin_blec::init()) .run(tauri::generate_context!()) .expect("error while running tauri application") ``` -------------------------------- ### Get Bluetooth Adapter State Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Retrieves the current operational state of the Bluetooth adapter. This is useful for checking if Bluetooth is enabled before attempting any operations. ```rust pub async fn get_adapter_state(&self) -> AdapterState ``` ```rust use tauri_plugin_blec::models::AdapterState; let handler = tauri_plugin_blec::get_handler()?; match handler.get_adapter_state().await { AdapterState::On => println!("Bluetooth is enabled"), AdapterState::Off => println!("Bluetooth is disabled"), AdapterState::Unknown => println!("Unknown state"), } ``` -------------------------------- ### Get Bluetooth Adapter State Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Retrieve the current power state of the Bluetooth adapter. Use this to check if Bluetooth is enabled before attempting other operations. ```typescript import { getAdapterState } from '@mnlphlp/plugin-blec'; const state = await getAdapterState(); if (state === 'Off') { console.log('Bluetooth is disabled'); } ``` -------------------------------- ### Initialize Tauri Plugin BLEC Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Provides two methods for initializing the plugin: `init` which panics on failure, and `try_init` which returns a `Result` for error handling. Both are essential for integrating the plugin with a Tauri application builder. ```rust pub fn init() -> TauriPlugin pub async fn try_init() -> Result, Error> ``` -------------------------------- ### JavaScript: Basic Scan and Connect Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Discover Bluetooth devices, select one, and establish a connection. Scans for a specified duration and connects to the first device found. Handles disconnection events. ```typescript import { startScan, stopScan, connect, disconnect } from '@mnlphlp/plugin-blec'; async function scanAndConnect() { const foundDevices: BleDevice[] = []; // Scan for 10 seconds await startScan((devices) => { console.log('Found devices:', devices); foundDevices.push(...devices); }, 10000); // Select first device (in real app, user would select) const device = foundDevices[0]; if (!device) { console.error('No devices found'); return; } console.log(`Connecting to ${device.name} at ${device.address}`); await connect(device.address, () => { console.log('Device disconnected'); }); console.log('Connected!'); } ``` -------------------------------- ### Handle NoDeviceConnected Error in JavaScript Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/errors-reference.md Catch and inspect errors for 'No device connected' to prompt the user to connect. This is useful for guiding users through the connection flow. ```typescript try { await read(characteristic); } catch (error) { if (error.includes("No device connected")) { console.log("Please connect to a device first"); // Trigger scan and connect flow } } ``` -------------------------------- ### Monitor BLE Connection State in Background (Rust) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Set up a background task to continuously monitor and log BLE connection status changes. Requires a Tokio runtime. ```rust use tauri_plugin_blec::get_handler; use tokio::sync::mpsc; async fn monitor_connection() -> Result, Box> { let handler = get_handler()?; let (tx, rx) = mpsc::channel(5); handler.set_connection_update_channel(tx).await; Ok(rx) } // Usage: async fn log_connection_changes() -> Result<(), Box> { let mut rx = monitor_connection().await?; tokio::spawn(async move { while let Some(connected) = rx.recv().await { println!("Connection: {}", if connected { "connected" } else { "disconnected" }); } }); Ok(()) } ``` -------------------------------- ### Handle CharacNotAvailable Error in Rust Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/errors-reference.md Provides an example of handling the `CharacNotAvailable` error in Rust, which indicates a characteristic UUID was not found on the connected device. It suggests checking available characteristics. ```rust match handler.recv_data(char_uuid, None).await { Err(Error::CharacNotAvailable(uuid)) => { eprintln!("Characteristic {} not found. Available characteristics: {:?}", uuid, available_characteristics); } _ => {} } ``` -------------------------------- ### Inspect Bluetooth Device Services and Characteristics in Rust Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Perform a complete device discovery workflow in Rust to enumerate services, characteristics, and their properties. This is useful for understanding a device's capabilities. ```rust use tauri_plugin_blec::get_handler; async fn inspect_device(address: &str) -> Result<(), Box> { let handler = get_handler()?; // Discover services let services = handler.discover_services(address).await?; for service in services { println!("Service: {}", service.uuid); for charac in service.characteristics { println!(" Characteristic: {}", charac.uuid); println!(" Properties: {:?}", charac.properties); for descriptor in charac.descriptors { println!(" Descriptor: {}", descriptor); } } } Ok(()) } ``` -------------------------------- ### JavaScript/TypeScript API Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/README.md Detailed documentation for the JavaScript and TypeScript API, including type definitions, exported functions, parameters, return types, error conditions, and code examples. ```APIDOC ## JavaScript/TypeScript API This section details the client-side API for interacting with the tauri-plugin-blec. ### Type Definitions - **BleDevice**: Represents a Bluetooth Low Energy device. - **BleCharacteristic**: Represents a BLE characteristic. - **BleService**: Represents a BLE service. - **AdapterState**: Represents the state of the Bluetooth adapter. ### Exported Functions This API exports 21 functions. Each function includes: - Full signatures - Parameter tables with types and defaults - Return types and error conditions - Code examples Refer to `javascript-api.md` for complete details. ``` -------------------------------- ### Monitor BLE Connection and Scanning States Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Sets up listeners for connection and scanning state changes. It also demonstrates how to initiate a scan and process discovered devices. ```typescript import { getConnectionUpdates, getScanningUpdates, startScan } from '@mnlphlp/plugin-blec'; async function monitorState() { // Monitor connection state await getConnectionUpdates((connected) => { console.log(`Connection state: ${connected ? 'connected' : 'disconnected'}`); }); // Monitor scanning state await getScanningUpdates((scanning) => { console.log(`Scanning: ${scanning}`); }); // Trigger a scan await startScan((devices) => { devices.forEach(dev => console.log(`Found: ${dev.name}`)); }, 5000); } ``` -------------------------------- ### Get Maximum Transfer Unit (MTU) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Retrieves the current Maximum Transfer Unit (MTU) value for the connected BLE device. This indicates the largest data packet size that can be transferred. ```typescript async function getMtu(): Promise ``` ```typescript import { getMtu } from '@mnlphlp/plugin-blec'; const mtu = await getMtu(); console.log(`MTU: ${mtu} bytes`); ``` -------------------------------- ### Configuration Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Functions for configuring BLE behavior and settings. ```APIDOC ## getMtu(deviceId: string) -> Promise ### Description Gets the current Maximum Transmission Unit (MTU) size for a connected BLE peripheral. ### Parameters - **deviceId** (string) - The ID of the target device. ### Returns - **Promise** - A promise that resolves with the MTU size. ``` ```APIDOC ## setWriteBehavior(behavior: 'WriteWithoutResponse' | 'Write') ### Description Sets the default write behavior for GATT operations. Can be set to 'WriteWithoutResponse' or 'Write'. ### Parameters - **behavior** ('WriteWithoutResponse' | 'Write') - The desired write behavior. ``` ```APIDOC ## setAndroidMtu(deviceId: string, mtu: number) ### Description Sets the Maximum Transmission Unit (MTU) size for a specific Android BLE peripheral. This is an Android-specific setting. ### Parameters - **deviceId** (string) - The ID of the target Android device. - **mtu** (number) - The desired MTU size. ``` -------------------------------- ### JavaScript API Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/INDEX.md Provides the complete JavaScript/TypeScript API for BLE operations, including type definitions, exported functions with signatures, parameter details, return types, error conditions, and usage examples. ```APIDOC ## JavaScript API ### Description Complete JavaScript/TypeScript API for BLE operations. ### Key Functions - **Device Discovery:** `startScan()`, `stopScan()` - **Connection:** `connect()`, `disconnect()` - **GATT Operations:** `send()`, `read()`, `subscribe()` - **Configuration:** `setWriteBehavior()`, `setAndroidMtu()`, `getMtu()` ### Type Definitions - `BleDevice` - `BleCharacteristic` - `BleService` - `AdapterState` ``` -------------------------------- ### startScan Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Initiates a BLE device scan for the specified duration. ```APIDOC ## startScan ### Description Initiates a BLE device scan for the specified duration. ### Method `async function startScan( handler: (devices: BleDevice[]) => void, timeout: Number, allowIbeacons: boolean = false ): Promise` ### Parameters #### Path Parameters - **handler** (function) - Required - Callback invoked with discovered devices - **timeout** (Number) - Required - Scan duration in milliseconds - **allowIbeacons** (boolean) - Optional - If true, request fine location permission for iBeacon detection on Android ### Returns `Promise` — Resolves when scan completes ### Errors Rejects if scanning fails or if BLE is unavailable ### Example ```typescript import { startScan } from '@mnlphlp/plugin-blec'; await startScan((devices) => { devices.forEach(device => { console.log(`Found: ${device.name} (${device.address})`); }); }, 10000); ``` ``` -------------------------------- ### listServices Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Discovers and lists all available services on a specified Bluetooth Low Energy device. ```APIDOC ## listServices ### Description Discovers and lists services available on a device. ### Method Signature ```typescript async function listServices(address: string): Promise ``` ### Parameters #### Path Parameters - **address** (string) - Required - MAC address of the device ### Returns `Promise` — Array of services or error message string ### Errors Rejects if the device is not found or service discovery fails ### Example ```typescript import { listServices } from '@mnlphlp/plugin-blec'; const address = 'AA:BB:CC:DD:EE:FF'; const services = await listServices(address); console.log('Services:', services); ``` ``` -------------------------------- ### Timeout Handling for Read Operations Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Implement a timeout mechanism for asynchronous read operations to prevent indefinite waiting. This example uses `tokio::time::timeout` to limit the execution time of receiving data from a characteristic. ```rust use std::time::Duration; use tokio::time::timeout; async fn read_with_timeout( char_uuid: uuid::Uuid, max_wait: Duration, ) -> Result, Box> { let handler = get_handler()?; let result = timeout( max_wait, handler.recv_data(char_uuid, None) ).await; match result { Ok(Ok(data)) => Ok(data), Ok(Err(e)) => Err(Box::new(e)), Err(_) => Err("Read operation timed out".into()), } } // Usage with different timeouts let data = read_with_timeout(uuid, Duration::from_secs(5)).await?; ``` -------------------------------- ### Rust Handler API Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/INDEX.md Details the complete Rust backend API for BLE operations, including module initialization, handler methods, callback types, type conversions, and asynchronous patterns. ```APIDOC ## Rust Handler API ### Description Complete Rust backend API for BLE operations, intended for Tauri command handlers. ### Key Methods - **Module Initialization:** `init()`, `try_init()`, `get_handler()` - **Connection:** `connect()`, `disconnect()` - **Discovery:** `discover()`, `discover_services()` - **GATT:** `send_data()`, `recv_data()`, `subscribe()`, `unsubscribe()` - **Configuration:** `set_write_behaviour()`, `set_android_mtu_request()` ### Callback Handlers - `OnDisconnectHandler` - `SubscriptionHandler` ``` -------------------------------- ### Register Plugin in Tauri (Basic) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Register the BLEC plugin in your Tauri application by calling `tauri_plugin_blec::init()` within your `src-tauri/src/lib.rs` file. This is the standard way to initialize the plugin. ```rust tauri::Builder::default() .plugin(tauri_plugin_blec::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); ``` -------------------------------- ### Subscribe with Sync and Async Closures Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Demonstrates subscribing to notifications using both synchronous and asynchronous closures. The asynchronous version requires an `async` block. ```rust // Sync closure handler.subscribe(uuid, None, |data| { println!("Received: {:?}", data); }).await?; // Async closure handler.subscribe(uuid, None, |data| async { println!("Received: {:?}", data); }).await?; ``` -------------------------------- ### Register for Connection State Updates Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Sets up a channel to receive asynchronous updates on the Bluetooth connection state. Use this to react to connection status changes in your application. ```rust pub async fn set_connection_update_channel(&self, tx: mpsc::Sender) ``` ```rust use tokio::sync::mpsc; let handler = tauri_plugin_blec::get_handler()?; let (tx, mut rx) = mpsc::channel(1); handler.set_connection_update_channel(tx).await; while let Some(connected) = rx.recv().await { println!("Connected: {}", connected); } ``` -------------------------------- ### Connect to Bluetooth Device in Rust Backend Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Use this pattern to establish a connection to a Bluetooth device from your Rust backend. It includes setting up a disconnect handler for asynchronous notification. ```rust use tauri::async_runtime; use uuid::uuid; use tauri_plugin_blec::{get_handler, OnDisconnectHandler}; async fn connect_to_device(address: &str) -> Result<(), Box> { let handler = get_handler()?; let disconnect_handler = OnDisconnectHandler::from_sync(|| { println!("Device disconnected!"); }); handler.connect(address, disconnect_handler, false).await?; println!("Connected to {}", address); Ok(()) } // In your tauri command: #[tauri::command] async fn my_command(address: String) -> Result { match connect_to_device(&address).await { Ok(_) => Ok("Connected".to_string()), Err(e) => Err(e.to_string()), } } ``` -------------------------------- ### Plugin Initialization Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Functions to initialize the BLEC plugin, with options for error handling. ```APIDOC ## Initialization Functions ### `init()` Initializes the plugin with default settings. Panics on failure. - **Returns**: `TauriPlugin` ### `try_init()` Initializes the plugin, returning a `Result` to handle potential errors gracefully. - **Returns**: `Result, Error>` ``` -------------------------------- ### Handle HandlerNotInitialized Error in Rust Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/errors-reference.md Safely initialize the BLE plugin using `try_init()` and handle potential initialization failures. This ensures the plugin is ready before use. ```rust match tauri_plugin_blec::try_init() { Ok(plugin) => { app = app.plugin(plugin); } Err(e) => { eprintln!("Failed to initialize plugin: {}", e); // Fall back to app without plugin } } ``` -------------------------------- ### Configure Write Operation Behavior Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Sets how write operations are handled, allowing configuration of timeouts and whether to wait for confirmation. Useful for optimizing performance or handling specific device behaviors. ```rust pub fn set_write_behaviour(&self, timeout_in_ms: Option, skip_waiting_on_success: bool) ``` ```rust let handler = tauri_plugin_blec::get_handler()?; handler.set_write_behaviour(Some(5000), true); ``` -------------------------------- ### Error-Tolerant Tauri Plugin Initialization Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Initialize the tauri-plugin-blec in a way that allows the application to continue running even if BLE is unavailable. Errors during initialization are caught and logged. ```rust use tauri::Builder; fn main() { let mut app = Builder::default(); app = match tauri_plugin_blec::try_init() { Ok(plugin) => app.plugin(plugin), Err(e) => { eprintln!("Failed to initialize blec plugin: {:?}", e); app } }; app.run(tauri::generate_context!()) .expect("error while running tauri application") } ``` -------------------------------- ### Service Discovery Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Retrieves the list of services offered by a BLE peripheral. ```APIDOC ## listServices(deviceId: string) -> Promise ### Description Retrieves a list of all available GATT services on a connected BLE peripheral. ### Parameters - **deviceId** (string) - The ID of the target device. ### Returns - **Promise** - A promise that resolves with an array of `BleService` objects. ``` -------------------------------- ### Connection Management Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Functions for establishing and terminating connections with BLE peripherals. ```APIDOC ## connect(deviceId: string) ### Description Connects to a specific Bluetooth Low Energy peripheral using its device ID. ### Parameters - **deviceId** (string) - The unique identifier of the device to connect to. ### Returns - A promise that resolves when the connection is established. ``` ```APIDOC ## disconnect(deviceId: string) ### Description Disconnects from a connected Bluetooth Low Energy peripheral. ### Parameters - **deviceId** (string) - The unique identifier of the device to disconnect from. ``` -------------------------------- ### Configure BLE Write Behavior (JavaScript) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Control BLE write operation timeouts and confirmation waiting. Use 'Optimize for Speed' to reduce latency by skipping confirmations, or 'Optimize for Reliability' to ensure full confirmation with a longer timeout. ```typescript import { setWriteBehavior, send } from '@mnlphlp/plugin-blec'; // Skip waiting for confirmation and use 3-second timeout await setWriteBehavior(3000, true); // Writes will return faster await send(characteristic, data, 'withResponse'); ``` ```typescript import { setWriteBehavior, send } from '@mnlphlp/plugin-blec'; // Wait for full confirmation with 10-second timeout await setWriteBehavior(10000, false); // Writes will be more reliable but slower await send(characteristic, data, 'withResponse'); ``` -------------------------------- ### Type System Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/INDEX.md A comprehensive reference to the type system used by the plugin, covering both TypeScript and Rust types, enumerations, field descriptions, and type conversion rules. ```APIDOC ## Type System Reference ### Description Complete reference for the plugin's type system, detailing data structures and their properties. ### TypeScript Types - `BleDevice` - `BleCharacteristic` - `BleService` - `AdapterState` ### Rust Structs - `BleDevice` - `Service` - `Characteristic` - `CharProps` ### Enumerations - `WriteType` - `AdapterState` - `ScanFilter` - `CharProps` ### Key Aspects - Field descriptions, requirements, and constraints - Type conversion rules between Rust and JavaScript - Platform-specific differences - Error type definition ``` -------------------------------- ### Register Plugin in Tauri (with Error Handling) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Register the BLEC plugin with error handling. This approach uses `tauri_plugin_blec::try_init()` and logs any initialization errors to stderr, allowing the application to continue running. ```rust let mut app = tauri::Builder::default(); app = match tauri_plugin_blec::try_init() { Ok(plugin) => app.plugin(plugin), Err(e) => { eprintln!("Failed to initialize blec plugin: {:?}", e); app } }; app.run(tauri::generate_context!()) .expect("error while running tauri application"); ``` -------------------------------- ### Create Synchronous OnDisconnectHandler Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Use `from_sync` to create a synchronous disconnect handler. This is suitable for simple, non-blocking operations. ```rust pub fn from_sync(func: F) -> Self ``` ```rust use tauri_plugin_blec::OnDisconnectHandler; let handler = OnDisconnectHandler::from_sync(|| { println!("Device disconnected!"); }); ``` -------------------------------- ### Handle Btleplug Error in Rust Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/errors-reference.md Demonstrates how to catch and handle specific `Btleplug` errors when performing BLE operations in Rust. This allows for targeted error recovery or logging. ```rust use tauri_plugin_blec::Error; match handler.send_data(uuid, None, data, WriteType::WithResponse).await { Err(Error::Btleplug(e)) => { eprintln!("BLE operation failed: {}", e); // Retry or disconnect } Err(e) => eprintln!("Other error: {}", e), Ok(_) => println!("Success"), } ``` -------------------------------- ### connect Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Connects to a BLE device by address. ```APIDOC ## connect ### Description Connects to a BLE device by address. ### Method `async function connect( address: string, onDisconnect: (() => void) | null, allowIbeacons: boolean = false ): Promise` ### Parameters #### Path Parameters - **address** (string) - Required - MAC address of the device to connect to - **onDisconnect** (function | null) - Required - Callback invoked when the device disconnects; pass null if no callback needed - **allowIbeacons** (boolean) - Optional - If true, enable iBeacon detection on Android ### Returns `Promise` — Resolves when connected ### Errors Rejects if the device is not found or connection fails ### Example ```typescript import { connect } from '@mnlphlp/plugin-blec'; const address = 'AA:BB:CC:DD:EE:FF'; await connect(address, () => { console.log('Disconnected!'); }); ``` ``` -------------------------------- ### Configure Write Behavior and MTU Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/usage-patterns.md Allows configuration of write behavior (fast vs. reliable) and requests a larger MTU on Android for optimized data transfer. It also shows how to retrieve the actual MTU. ```typescript import { setWriteBehavior, setAndroidMtu, getMtu, send } from '@mnlphlp/plugin-blec'; async function optimizeTransfer(targetThroughput: boolean = true) { // Configure write behavior if (targetThroughput) { // Fast writes: skip waiting for confirmation await setWriteBehavior(3000, true); } else { // Reliable writes: wait for full confirmation await setWriteBehavior(10000, false); } // Request large MTU on Android await setAndroidMtu(517); // Check actual MTU after connecting const mtu = await getMtu(); console.log(`Actual MTU: ${mtu} bytes`); // Calculate max data per write (subtract GATT header) const maxData = mtu - 3; console.log(`Max data per write: ${maxData} bytes`); } ``` -------------------------------- ### Android BLE Module Functions Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Provides essential functions for initializing the Android BLE plugin and checking Bluetooth permissions. ```rust pub fn init(app: &AppHandle, api: PluginApi) pub fn check_permissions(ask_if_denied: bool) -> Result ``` -------------------------------- ### Check BLE Permissions Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Verify if the application has the necessary permissions to perform BLE operations. By default, it will prompt the user again if permissions were previously denied. ```typescript import { checkPermissions } from '@mnlphlp/plugin-blec'; const hasPermissions = await checkPermissions(); if (!hasPermissions) { console.log('BLE permissions not granted'); } ``` -------------------------------- ### Core BLE Handler Methods Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Exposes methods for managing BLE connections, discovery, GATT operations, and subscriptions. These methods form the backbone of the plugin's BLE functionality, handling asynchronous operations and state management. ```rust // Connection pub async fn connect(&'static self, address: &str, on_disconnect, allow_ibeacons) pub async fn disconnect(&self) pub fn is_connected(&self) -> bool // Discovery pub async fn discover(&'static self, tx, timeout, filter, allow_ibeacons) pub async fn discover_services(&self, address) -> Vec pub async fn stop_scan(&self) // GATT Operations pub async fn send_data(&self, char: Uuid, service: Option, data: &[u8], write_type) pub async fn recv_data(&self, char: Uuid, service: Option) -> Vec // Subscriptions pub async fn subscribe(&self, char: Uuid, service: Option, callback) pub async fn unsubscribe(&self, char: Uuid) // Configuration pub fn set_write_behaviour(&self, timeout_ms: Option, skip_waiting: bool) pub async fn mtu(&self) -> u16 pub async fn get_adapter_state(&self) -> AdapterState // State channels pub async fn set_connection_update_channel(&self, tx: mpsc::Sender) pub async fn set_scanning_update_channel(&self, tx: mpsc::Sender) ``` -------------------------------- ### getAdapterState Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Returns the current state of the Bluetooth adapter. ```APIDOC ## getAdapterState ### Description Returns the current state of the Bluetooth adapter. ### Method `async function getAdapterState(): Promise` ### Returns `Promise` — Current adapter state ### Example ```typescript import { getAdapterState } from '@mnlphlp/plugin-blec'; const state = await getAdapterState(); if (state === 'Off') { console.log('Bluetooth is disabled'); } ``` ``` -------------------------------- ### Register for Connection Updates Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Set up a callback to be notified of changes in the BLE device connection state. This is useful for updating UI or handling disconnections. ```typescript import { getConnectionUpdates } from '@mnlphlp/plugin-blec'; await getConnectionUpdates((connected) => { console.log(`Device ${connected ? 'connected' : 'disconnected'}`); }); ``` -------------------------------- ### Type System Reference Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/README.md Documentation for the type system used by tauri-plugin-blec, covering both TypeScript/JavaScript and Rust definitions. ```APIDOC ## Type System Reference This document describes the type system used throughout tauri-plugin-blec. ### Definitions - **TypeScript/JavaScript**: Detailed type definitions for client-side usage. - **Rust**: Struct and enum definitions for backend implementation. ### Details - Field descriptions and constraints - Type conversion rules - Platform-specific type differences Refer to `types-reference.md` for complete details. ``` -------------------------------- ### Handle UnknownPeripheral Error in Rust Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/errors-reference.md Illustrates how to handle the `UnknownPeripheral` error in Rust, which occurs when a specified device address cannot be found. It suggests scanning first as a preventative measure. ```rust match handler.connect(address, disconnect_handler, false).await { Err(Error::UnknownPeripheral(addr)) => { eprintln!("Device {} not found. Did you scan first?", addr); } _ => {} } ``` -------------------------------- ### Configure Write Behavior Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Configures how write operations are handled, including setting a timeout and whether to wait for success confirmation. Useful for optimizing write performance. ```typescript async function setWriteBehavior( timeoutInMs: number | null | undefined, skipWaitingOnSuccess: boolean ): Promise ``` ```typescript import { setWriteBehavior } from '@mnlphlp/plugin-blec'; // Set 5 second timeout and don't wait for success confirmation await setWriteBehavior(5000, true); ``` -------------------------------- ### Create Asynchronous OnDisconnectHandler Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/rust-handler-api.md Use `from_async` to create an asynchronous disconnect handler. This is suitable for operations that may involve waiting or I/O. ```rust pub fn from_async(func: F) -> Self where F: FnOnce() -> FUTURE + Send + 'static, FUTURE: Future + Send + 'static, ``` ```rust use tauri_plugin_blec::OnDisconnectHandler; let handler = OnDisconnectHandler::from_async(|| async { println!("Device disconnected!"); }); ``` -------------------------------- ### Add Rust Plugin to Cargo.toml Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/README.md Alternatively, manually add the `tauri-plugin-blec` dependency to your `src-tauri/Cargo.toml` file. ```toml [dependencies] tauri-plugin-blec = "0.12" ``` -------------------------------- ### getScanningUpdates Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/javascript-api.md Registers a callback to receive scanning state changes. ```APIDOC ## getScanningUpdates ### Description Registers a callback to receive scanning state changes. ### Method `async function getScanningUpdates(handler: (scanning: boolean) => void): Promise` ### Parameters #### Path Parameters - **handler** (function) - Required - Callback invoked with scanning state ### Returns `Promise` — Resolves when the listener is registered ### Example ```typescript import { getScanningUpdates } from '@mnlphlp/plugin-blec'; await getScanningUpdates((scanning) => { console.log(`Scanning: ${scanning}`); }); ``` ``` -------------------------------- ### BLE Data Structures and Models Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/architecture.md Defines the core data structures for Bluetooth Low Energy devices, services, and characteristics. Includes enums for properties and write types, and utility functions for formatting addresses. ```rust pub struct BleDevice { ... } pub struct Service { ... } pub struct Characteristic { ... } pub enum CharProps { ... } pub enum WriteType { ... } pub enum AdapterState { ... } pub enum ScanFilter { ... } pub trait BondingPeripheral { ... } pub fn fmt_addr(addr: BDAddr) -> String ``` -------------------------------- ### Enable Detailed BLEC Plugin Logs Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md For the most detailed logs from the tauri_plugin_blec, set the RUST_LOG environment variable to 'tauri_plugin_blec=trace'. ```bash RUST_LOG=tauri_plugin_blec=trace cargo tauri dev ``` -------------------------------- ### Configure Android MTU (JavaScript) Source: https://github.com/mnlphlp/tauri-plugin-blec/blob/main/_autodocs/configuration-reference.md Request a specific MTU value for Android connections to optimize throughput. Call this before connecting. The actual MTU may be less than requested. ```typescript import { setAndroidMtu, connect } from '@mnlphlp/plugin-blec'; // Request maximum MTU before connecting await setAndroidMtu(517); await connect(address, onDisconnect); // Check actual MTU after connection const mtu = await getMtu(); console.log(`Actual MTU: ${mtu}`); ```