Blue Falcon Documentation

repository·master·Indexed 19 days ago

https://github.com/reedyuk/blue-falcon

A Bluetooth Low Energy (BLE) Kotlin Multiplatform library providing a unified, type-safe API for iOS, Android, macOS, JavaScript, Windows, and Raspberry Pi. Blue Falcon 3.0 features a plugin-based engine architecture, a DSL for instance creation, and supports both reactive Flow-based and delegate-based APIs.

Tokens
72.2K
Snippets
184
Records
294
Agent score
66%

What's inside Blue Falcon

  1. Overview of Blue Falcon testing infrastructure

    master

    Blue Falcon 3.0 provides a comprehensive testing suite designed to verify different layers of the library. The testing stack is built on:

    • Framework: Kotlin Test (kotlin.test)
    • Coroutines: kotlinx-coroutines-test for testing asynchronous operations
    • Mocking: Custom fakes and mocks (e.g., FakeBlueFalconEngine, MockPeripheral)
    • Assertions: Built-in Kotlin Test assertions

    The infrastructure supports unit tests, integration tests, plugin verification, platform-specific engine tests, and mock implementations.

  2. Available Blue Falcon Example Projects

    master

    The examples/ directory contains several specialized projects for different use cases:

    • ArchitecturePOC: Demonstrates the three-layer architecture (Core → Engine → Platform) and the DSL API.
    • Plugin-Example: Focuses on custom plugin implementation, configuration, and the interceptor pattern.
    • Engine-Example: Shows how to implement the BlueFalconEngine interface for custom platform-specific BLE integration.
    • Notification-Example: Demonstrates subscribing to BLE characteristic notifications using SharedFlow<ByteArray> and the onNotificationReceived hook.
    • Peripheral-Example: A production-grade GATT echo server implementation for devices acting as peripherals.
    • ComposeMultiplatform-3.0-Example: A modern implementation using Compose UI, Coroutines, and Flows.
    • ComposeMultiplatform-Legacy-Example: A legacy implementation using the 2.x callback-based delegate pattern.
    • JS-Example: Web Bluetooth integration using Kotlin/JS.
    • WASM-Example: Web Bluetooth integration using Kotlin/Wasm.
  3. Windows Bluetooth LE Performance Characteristics

    master

    The Windows implementation utilizes the Windows Runtime (WinRT) API design, resulting in the following performance profile:

    • Startup Time: < 1 second for Bluetooth initialization.
    • Scan Latency: 100-500ms to first device discovery.
    • Connection Time: 1-3 seconds typical.
    • Memory Footprint: Minimal; native memory is managed by WinRT.
    • CPU Usage: Low; uses asynchronous operations with event callbacks.

    Security & Privacy

    • Uses the standard Windows OS Bluetooth security model.
    • Pairing is handled directly by the Windows operating system.
    • No third-party dependencies are used, reducing the attack surface.
  4. Manage plugin dependencies

    master

    Plugins can depend on other plugins by accepting them as constructor parameters. This allows one plugin to utilize the functionality or state of another during its install phase.

    class MetricsPlugin(
        private val loggingPlugin: LoggingPlugin
    ) : BlueFalconPlugin {
        override fun install(client: BlueFalconClient, config: PluginConfig) {
            // Use loggingPlugin functionality
            loggingPlugin.log("MetricsPlugin installed")
        }
    }
  5. Understand the Blue Falcon Peripheral Module architecture

    master

    The peripheral module (GATT server) has been separated from blue-falcon-core into a dedicated blue-falcon-peripheral artifact. This separation ensures that client-only applications (Central role) do not inherit unnecessary server-role dependencies.

    Key architectural components include:

    • Peripheral Manager: The top-level entry point for managing GATT server capabilities.
    • Scoped Sessions: Remote centrals are represented as distinct, observable sessions. This allows for multi-central state management and targeted delivery of data to specific devices.
    • Explicit ATT Responses: Unlike previous versions, subscriptions and ATT responses are explicit, giving the application control over when and how data is acknowledged.
    • Backpressure and Readiness: The engine exposes readiness states, allowing applications to implement custom scheduling or use the official queue plugin to handle Busy states and prevent memory overload.
  6. Understand the Blue-Falcon 3.0 Plugin-Based Architecture

    master

    Blue-Falcon 3.0 uses a plugin-based engine architecture (defined in ADR 0002). This design allows for a core module to orchestrate operations while delegating platform-specific logic (like BLE operations) to specialized engines and plugins.

    Key patterns demonstrated in the architecture include:

    1. DSL-based Instance Creation: Using a new DSL API to instantiate Blue-Falcon.
    2. Plugin Interception: Creating custom plugins (e.g., a LoggingPlugin) to intercept and monitor BLE operations.
    3. Vendor-Specific Functionality: Implementing specialized plugins for specific hardware needs, such as a Nordic OTA Plugin for firmware updates.
    4. Multi-Platform Engine Selection: A pattern for selecting the appropriate engine based on the current platform (e.g., Android vs. iOS).
  7. How the Peripheral Queue Plugin manages scheduling and backpressure

    master

    The QueuePlugin uses a single scheduler coroutine to drain queues using a round-robin approach. This ensures that a continuously writable session cannot starve other sessions.

    Scheduling Logic

    • Round-Robin: During each pass, the scheduler attempts to process no more than one item from each eligible session.
    • High Throughput: A Sent result triggers an immediate next pass without waiting for a Flow collection suspension, allowing high-throughput platforms (like CoreBluetooth) to consume their acceptance window efficiently.

    Backpressure and Readiness

    When a platform returns Busy during a notify call, the plugin handles backpressure using an epoch-based mechanism:

    1. The item remains at the head of the session's FIFO queue.
    2. The session is marked as blocked.
    3. The scheduler reads the current notificationReadinessState (which exposes manager and active-session epochs).
    4. The scheduler suspends until the relevant epoch advances, ensuring the handoff from Busy to waiting is loss-free and does not allow slow observers to stall backend events.

    Session Disconnection

    • If a session disappears from peripheral.sessions, all its pending items are completed as Disconnected.
    • Stopping or closing the BlueFalconPeripheral completes all pending items across all sessions as Disconnected and cancels the scheduler.
  8. Understand Notification Readiness signals

    master

    Blue Falcon provides two ways to observe notification readiness:

    1. notificationReadiness: A bounded hint stream intended for lightweight application observation. It is optimized for speed; slow collectors do not backpressure platform callbacks.
    2. notificationReadinessState: A durable state used by plugins that require a loss-free handoff. Its manager and active-session epochs remain stable even when the hint stream coalesces under heavy load.

    Note that NotificationReadiness.Manager is manager-wide because the underlying platform (Core Bluetooth) does not identify which specific central released transmit capacity.

  9. How characteristic notifications are propagated

    master

    Blue Falcon uses two coordinated mechanisms to expose characteristic notifications to different types of consumers:

    1. Reactive Consumers (Apps/Coroutines): Use the notifications: SharedFlow<ByteArray> available on the BluetoothCharacteristic object for direct, reactive stream consumption.
    2. Plugin Consumers: Use the BlueFalconPlugin.onNotificationReceived(peripheral, characteristic, value) hook for engine-level interception.
    3. Legacy Consumers: The engine-level notification events are bridged to the legacy BlueFalconDelegate.didCharacteristcValueChanged callback, ensuring that subscribed notifications trigger existing delegate logic.

    Note that notification events are best-effort asynchronous signals; delivery and ordering are still subject to the underlying platform's BLE behavior.

  10. How the Apple Peripheral Backend lifecycle works

    master

    The start(config) method follows a strict sequence to ensure the peripheral is ready before the manager enters the Running state:

    1. Validation: Ensures the backend is currently stopped and installs a new event sink.
    2. Manager Creation: Creates the CBPeripheralManager using the provided PeripheralConfig (including the restorationIdentifier if present).
    3. Power Check: Waits for CBManagerStatePoweredOn. It will fail if the state is unsupported or if a startup timeout is reached.
    4. GATT Setup: Adopts a restored GATT database or publishes configured services.
    5. Subscription Recovery: Reconstructs restored subscriptions.
    6. Advertising: Reuses existing advertising if active, otherwise starts new advertising.
    7. Ready State: Returns only once the backend is fully ready.

    Failure Handling: If start fails, the backend performs a non-cancellable rollback: it stops advertising, removes services, detaches the current generation, clears registries, and releases pending requests.

  11. How Windows platform support is implemented

    master

    Blue Falcon implements Windows BLE support using a three-layer architecture to bridge Kotlin Multiplatform with native Windows Runtime (WinRT) APIs:

    1. Kotlin/JVM Layer: Provides the high-level Blue Falcon API using Kotlin coroutines for asynchronous operations. This layer targets the windows JVM platform.
    2. JNI Bridge Layer: A native interface layer that marshals calls between the Kotlin/Java environment and C++.
    3. Native Windows Layer: A C++ implementation that makes direct calls to the Windows.Devices.Bluetooth namespace in the Windows Runtime (WinRT).

    This architecture ensures zero third-party dependencies and native performance by using only built-in Windows APIs.