tauri-plugin-blec

repository·main·Indexed 42 days ago

https://github.com/mnlphlp/tauri-plugin-blec

A Bluetooth Low Energy (BLE) client plugin for Tauri version 0.14.1. It leverages the btleplug library to provide BLE functionality across platforms, including a unified plugin system for Android.

Tokens
18.1K
Snippets
57
Records
79
Agent score
53%

What's inside tauri-plugin-blec

  1. Overview of stress-server

    main

    The stress-server is a scriptable "chaos" BLE GATT peripheral designed for stress-testing the tauri-plugin-blec client. It runs on a Linux host using BlueZ and can simulate various network and device failures, such as dropping links, hiding advertisements, flooding notifications, delaying responses, failing requests, and simulating reboots (re-registering the GATT application).

    It is built with the bluer crate and follows a specific wire protocol defined in ../stress-protocol.md.

  2. Default permission set for Tauri Plugin blec

    main

    The plugin provides a default set of permissions that allow access to various BLE (Bluetooth Low Energy) operations without a pre-configured scope. If you use the default permission set, the following capabilities are enabled:

    • Scanning: allow-scan, allow-stop-scan, allow-scanning-state
    • Connection: allow-connect, allow-disconnect, allow-connection-state
    • Data Transfer: allow-send, allow-recv, allow-send-string, allow-recv-string
    • Subscriptions: allow-subscribe, allow-subscribe-string, allow-unsubscribe
    • Configuration & State: allow-get-adapter-state, allow-list-services, allow-mtu, allow-set-android-mtu, allow-set-timeouts, allow-set-write-behavior
    • Permissions: allow-check-permissions
  3. Understand Integration Scripts

    main

    Integration scripts are fixed timelines followed independently by both the client and the server.

    Execution Lifecycle

    1. Baseline State: Before starting, the client must be connected and subscribed to ECHO and COUNTER.
    2. Triggering: The client sends a CONTROL write with 0x10 and a script_id.
    3. Timing: The client's t0 is the moment the 0x10 write returns; the server's t0 is the receipt of that write.
    4. Completion: The server reaches done when its last step resolves. The client polls REPORT until the server state is done or aborted.
    5. Cleanup: After a script, the client restores the baseline state before starting the next one.

    Script Verdict

    A script is considered a PASS only if every server step and every client step passed. If a step's time window elapses before its condition is met, the step fails.

  4. BLEC Stress GATT Protocol Overview

    main

    The BLEC stress protocol is a shared communication standard used by the stress-server (peripheral/Linux host) and stress-client (Tauri app/phone/PC) to perform automated Bluetooth Low Energy (BLE) stability and stress testing.

    Advertising Details

    • Local Name: blec_stress (can be overridden with --name on the server).
    • Service UUID: Contains the STRESS service.
    • Manufacturer Data ID: 0xB1EC with value [0x01].

    Service and Characteristic UUIDs (128-bit)

    NameUUIDProperties
    SERVICEb1ec5747-0000-4000-8000-000000000000primary service
    ECHOb1ec5747-0001-4000-8000-000000000000write, write-without-response, notify
    COUNTERb1ec5747-0002-4000-8000-000000000000notify
    LARGEb1ec5747-0003-4000-8000-000000000000read
    CONTROLb1ec5747-0004-4000-8000-000000000000write, write-without-response
    STATUSb1ec5747-0005-4000-8000-000000000000read
    REPORTb1ec5747-0006-4000-8000-000000000000read
  5. Requirements for running stress-server

    main

    To run the stress-server, your environment must meet the following criteria:

    System Requirements

    • Linux with BlueZ: bluetoothd must be running (tested against version 5.87).
    • BLE Adapter: A compatible adapter (e.g., hci0) must be available.
    • Permissions: Your user must have permission to communicate with bluetoothd over D-Bus (e.g., being a member of the bluetooth group or running as root).

    Critical Configuration: Disable BlueZ GATT Client Role

    By default, bluetoothd runs service discovery on every connecting central, which opens an ATT client channel to the phone. This can prevent the server from correctly detecting link drops.

    To fix this:

    1. Edit /etc/bluetooth/main.conf.
    2. Add or modify the following under the [GATT] section:
      [GATT]
      Client = false
    3. Restart the service: sudo systemctl restart bluetooth.

    Note: This only prevents the host from acting as a GATT client; it does not affect its ability to act as a server.

    Other Considerations

    • No other GATT server apps: Ensure no other apps on the phone (like digital car keys) are holding the radio link.
    • Android ACL timing: Android may keep the ACL link for ~1 second after the last GATT client closes. Integration scripts like rapid-reconnect account for this by waiting 1.5s.
  6. Run the stress-server

    main

    Navigate to the examples/stress-server directory and use cargo run. You can provide commands via stdin or drive it via the CONTROL characteristic.

    cd examples/stress-server
    # Standard run with default name 'blec_stress'
    cargo run -- --name blec_stress
    
    # Run with debug logging for bluer
    RUST_LOG=bluer=debug cargo run
    cd examples/stress-server
    cargo run -- --name blec_stress
  7. Correlate client and server logs

    main

    To debug timing issues, merge the server and client logs. Both sides use Unix millisecond timestamps as the first column.

    1. Copy the client log using the Copy log button.
    2. Save both the server log and client log to files (e.g., server.log and client.log).
    3. Merge and sort them by timestamp:
    cat server.log client.log | sort -n > merged.log

    Note: Ensure both devices have synchronized clocks (NTP) for accurate correlation.

    cat server.log client.log | sort -n > merged.log
  8. Register the blec plugin in Tauri

    main

    You must initialize the plugin within your Tauri builder in src-tauri/src/lib.rs. You can use init() for a standard setup or try_init() if you want to handle potential initialization errors gracefully.

    // Standard initialization
    tauri::Builder::default()
        .plugin(tauri_plugin_blec::init())
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
    
    // Graceful initialization
    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");
  9. Enable full type support for `.vue` imports in TypeScript

    main

    By default, TypeScript treats .vue imports as generic Vue component types, which may prevent you from seeing actual prop types when importing components into TypeScript files (e.g., when using manual h(...) calls).

    To get full type support, you must enable Volar's Take Over mode in VS Code:

    1. Open the VS Code command palette and run Extensions: Show Built-in Extensions.
    2. Locate the TypeScript and JavaScript Language Features extension.
    3. Right-click it and select Disable (Workspace).
    4. Open the command palette and run Developer: Reload Window to apply the changes.

    This allows Volar to take over the TypeScript service, providing better type information for Vue files.

  10. Install the tauri-plugin-blec Rust dependency

    main

    To use the plugin in your Tauri project, you must add the Rust crate to your src-tauri directory. You can do this using cargo add or by manually editing your Cargo.toml file.

    cargo add tauri-plugin-blec

    Or manually in src-tauri/Cargo.toml

    [dependencies]
    tauri-plugin-blec = "0.12"
  11. Configure iOS for Bluetooth usage

    main

    To support Bluetooth on iOS, you must perform two steps:

    1. Update Info.plist: Add the NSBluetoothAlwaysUsageDescription key with a description of why your app uses Bluetooth.
    2. Add CoreBluetooth Framework:
      • Open your project using tauri ios dev --open.
      • In Xcode, select your project.
      • Under General -> Frameworks, Libraries, and Embedded Content, add the CoreBluetooth framework.
    <key>NSBluetoothAlwaysUsageDescription</key>
    <string>The App uses Bluetooth to communicate with BLE devices</string>
  12. Setup the blec stress client and server

    main

    To perform integration testing, you must run both a server and a client on separate Bluetooth adapters (e.g., a Linux host for the server and a phone or second PC for the client).

    1. Run the Server

    Run the server on a Linux host with a Bluetooth adapter. It advertises as blec_stress by default.

    cd examples/stress-server
    cargo run --release

    2. Run the Client (Desktop)

    On a desktop machine, ensure you have built the JS bindings in the repository root first if dist-js/ is missing.

    # In repository root
    yarn && yarn build
    
    # In client directory
    cd examples/stress-client
    yarn
    yarn tauri dev

    3. Run the Client (Android)

    For Android, initialize the project once before running the dev command. Important: You must press Permissions in the app before the first run to grant Bluetooth and location permissions.

    cd examples/stress-client
    yarn
    yarn tauri android init
    yarn tauri android dev
    cd examples/stress-server
    cargo run --release