Repository navigation
Conversation
* Implement unified and type safe error messages * Fix Apple error handling * improve linux exception handling * improve web exception handling * fix window imports * update pigeon generated files * Fix compilaton issue * Fix windows error parsing * Fix windows compilation * Improve error handling on dart side * rename _wrapFuture to _executeWithErrorHandling * Add pigeon generation script and format generated dart file * Update changelog * Update readme --------- Co-authored-by: Foti Dim <foti@navideck.com>
* Fix iOS example app asking permission on app launch * Dispose controllers
* Implement isScanning api * Improve IOS scanning api * Update Readme and Changelog
* Add button to hide discovered devices in example app * Resolve Ai Comments * Apply suggestion from @fotiDim * Add tooltip --------- Co-authored-by: Foti Dim <foti@navideck.com>
* Implement requestPermission api * Update example ios podfile * Update example windows dependencies * Update Readme and Changelog * Resolve Ai Comments * Improve bluetooth permission handling * Update Readme * Improve readme --------- Co-authored-by: Foti Dim <foti@navideck.com>
* Improve disconnect api * Get disconnection event on Web from callback * Wait for disconnection result on calling disconnect * Improve linux disconnection * Update Changelog * Fix Ai comments
* Implement characteristic descriptor discovery * Improve Darwin services discovery * Minor mac fix * Implement Windows support * discover descriptors in DiscoverServicesAsync api on windows * Add withDescriptors in discoverServices api * Implement withDescriptors for Apple and Android * Fix ai comment and format pigeon generated file * Resolve Ai comment * Capitalize API * Handle empty services scenario --------- Co-authored-by: Foti Dim <foti@navideck.com>
* Implement timestamp in scanResult * Update pigeon * implement windows * Update changelog * Fix Swift formatting * Remove android unused import * Format pigeon generated file
* Implement Logging * Add timestamp in OnValueChanged * improve web and linux logging * Implement windows and format pigeon * Fix windows build and unity log level * Log commands with timestamp * Fix code doc * Remove unnecessary import * Update docs * Fix crash on windows 11 because of failed pairing * Update changelog * Fix native code formatting
* Implement hasPermissions api * Bump minimum MacOS version to 10.15 * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
- Clarified MTU request behavior and platform limitations in README.md. - Added best practices for MTU management in cross-platform BLE applications. - Enhanced documentation for `requestMtu` method in UniversalBle and BleDeviceExtension to reflect best-effort nature of MTU requests and platform-specific behaviors. Co-authored-by: Foti Dim <foti@navideck.com>
* Improve example app ui * Store favorite services in local storage * Use Text instead of SelectableText * Improve colors * Fix flutter analyzer issues * Revert example app minimum sdk requirement * Implement hasPermission api and improve ui flow * More ui improvements * Improve ScannedItem ui * Improve control ui * Change color theme to blue * Minor improvements wip * improve responsive ui and flow * More improvements * More improvements * Update Mac podfile * Fix home page scroll view * Update app and package name * Revert changelog * Resolve Ai comments --------- Co-authored-by: Foti Dim <foti@navideck.com>
* Enforce cxx_std_20 * Bump version * Switch to private
- Implemented loading and saving of scan filters (services, name prefix, manufacturer data, and search term) using SharedPreferences. - Added functionality to apply filters from the loaded preferences. - Updated the UI to save filters when they change or when the search is cleared.
* Add autoConnect support * Enhance autoConnect functionality for Bluetooth devices - Added support for managing a set of auto-connect devices in both Android and iOS implementations. - Updated connection and disconnection logic to handle auto-reconnect scenarios appropriately. - Improved cleanup processes to prevent unwanted reconnections when devices are manually disconnected. * Refactor connection button and add auto-reconnect toggle - Updated the connection button layout for better UI consistency. - Introduced an auto-reconnect toggle to manage automatic reconnections when devices become available. - Enhanced connection and disconnection logic to respect the auto-connect setting. * Update version to 1.2.0 and add CHANGELOG for new features - Bumped version to 1.2.0. - Added CHANGELOG.md detailing new features including support for `autoConnect` and UI updates for automatic reconnection. * Improve readme * Refactor variable naming for clarity in Bluetooth connection logic - Changed variable name from `isAutoConnect` to `shouldAutoConnect` for better readability and understanding of its purpose in the connection state handling. * Refactor connection handling in UniversalBlePlugin - Simplified connection logic by always cleaning up internal state before sending connection change callbacks. - Ensured GATT resources are only closed when autoConnect is disabled, allowing for better management of Bluetooth connections. * Refactor disconnection handling in UniversalBlePlugin - Introduced a new method `handlePeripheralDisconnection` to encapsulate disconnection logic, improving code readability and maintainability. - Updated the `centralManager` methods to utilize the new disconnection handler, ensuring consistent behavior across connection state changes. * Update darwin/Classes/UniversalBlePlugin.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Foti Dim <fotios.dimanidis@a2zebra.de> Co-authored-by: Navideck Labs <130186950+navidecklabs@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Test added, fails. * Bound Windows BLE cleanup during app shutdown Give the final connection cleanup drain three seconds. If WinRT disposal is still pending, pin the plugin DLL and continue teardown while the worker retains its resources. If pinning fails, keep waiting so the worker can finish safely. Cover the deadline, pin failure fallback, and normal cleanup in the native regression tests. Fixes Navideck#375. * Windows: bound Bluetooth shutdown with a shared deadline Close Flutter message delivery before teardown and keep native Bluetooth state alive while admitted work finishes. Share a three-second wait budget across initialization, callbacks, and native cleanup. If work remains, pin the DLL before returning and keep waiting if pinning fails. Cover stalled initialization, late publication, the callback deadline, and the pin failure fallback in native tests. * Windows: limit shutdown fix to connection cleanup Restore the existing initialization, callback, and Flutter delivery paths. Keep the bounded connection cleanup drain, silent disposal workers, and fast pin failure test. * Windows: restore connection disposal logging Bring back the error logging in the connection disposal workers and GATT cleanup, and drop the log_errors parameter that silenced it. The logs cover every disconnect, not only shutdown, and a worker that outlives the bounded drain can still log safely. Also remove a redundant IsIdle() check from DrainConnectionCleanup. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Comment update --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Android below API 26 reports unknown connectability instead of throwing NoSuchMethodError on the first scan result; Windows queries IBluetoothLEAdvertisementReceivedEventArgs2 with try_as and keeps the answer unknown (`std::optional<bool>`) when the interface is unavailable, instead of dereferencing a null vtable or reporting a fabricated false. Fixes Navideck#383, Navideck#373.
…Bluetooth restarts (Navideck#389) Cached peripheral state now dies with the service it describes, and an adapter restart invalidates the GATT server instead of leaving a dead one cached. - Scoped cache clearing on removeService/clearServices, keeping the state of a different service that exposes the same characteristic UUID. - ACTION_STATE_CHANGED drops the server, advertiser and session state, reporting connected centrals as disconnected and advertising as idle. - A rejected registration is retried once only when the server predates the current adapter session, so a duplicate addService no longer tears down every other service. Fixes Navideck#384, Navideck#385.
disconnect no longer waits behind the device's serialized GATT queue. It dispatches the platform disconnect outside serialization and cancels queued commands for that device across the default and custom queues, preserving work for other devices and commands that are already running. Two visible consequences, both documented: disconnect's queueId is deprecated and ignored, and cancelled commands fail with a UniversalBleException carrying UniversalBleErrorCode.operationCancelled and the canonical device id in details. getConnectionState is now queued under its device so a disconnect can cancel it.
…lbacks (Navideck#376, Navideck#381) Every pending Android read, write, descriptor operation, RSSI request, discovery and notification subscription is now bound to the BluetoothGatt that submitted it, so a callback or cleanup from a replaced client cannot complete or fail a newer request for the same address. Building on that ownership model, connection state, connection parameters and notifications reported by a client that a newer connect() replaced are dropped, as are notifications from the client disconnect() is closing until its STATE_DISCONNECTED arrives. A connection that arrives before the client is published is still delivered, and a replaced client's disconnect is no longer reported as the current connection's. Fixes Navideck#381.
…videck#378) Pending writes now record the submitting CBPeripheral and are matched by object identity, so two peripherals sharing a UUID can no longer consume each other's didWrite or ready callbacks. Disconnection and replacement settle abandoned owners by comparing against the object the plugin actually routes callbacks to, which also covers a predecessor whose state still reports connected. A predecessor's write that can no longer complete now fails with deviceDisconnected ("Peripheral replaced") instead of hanging until the Dart timeout. Disconnect keeps device-wide cleanup for callers holding no object.
…ess (Navideck#386) CoreBluetooth supports only one CBCentralManager per restoration identifier, so with several FlutterEngines every manager after the first was reported as unsupported and restoration became unpredictable. Ownership now lives in a CoreBluetooth-free type: the first claim wins, later engines get a manager without an identifier, and the identifier frees when the owner is deallocated. A denied claim is logged once at the point the identifier-less manager is created, and the assert that claims precede manager creation is a release-safe guard.
…avideck#390) * Android: fail a refused write without stranding its pending result (Navideck#387) * Android: correct the write-refusal API level and cover the descriptor guard The 512-byte IllegalArgumentException was added to writeCharacteristic(characteristic, value, writeType) in Android 15 (API 35), not 13, and writeDescriptor never length-checks at all, so the comments, changelog and test header named the wrong trigger. The length guard now runs after the device, characteristic and write-support lookups, so a >512-byte write still reports deviceNotFound or characteristicNotFound as it did before. The descriptor guard gains a test, and the precedence it preserves is covered too. `write` and `writeDescriptor` document the cap, and the tests match the sibling files' 4-space indentation.
…#392) * Distinguish same-UUID characteristics in different services (Navideck#391) A GATT database may expose the same characteristic UUID in several services (one Battery Service per battery, or the reporter's four sensor services), and each instance notifies on its own attribute handle. Values were routed by device and characteristic UUID only, so every listener received the values of every instance with that UUID. The Pigeon onValueChanged callback now carries the UUID of the service that owns the characteristic, BleCharacteristicValue exposes it as serviceId, characteristicValueStream takes an optional serviceId filter, and BleCharacteristic.onValueReceived uses its own service automatically. Android, Apple, Windows, Linux and Web report the owning service. A value whose service a platform does not report still reaches a service-filtered stream, so custom platform implementations and an unusable service id keep their existing behaviour instead of losing values. * Document service-routing caveats and cover the Pigeon callback `onValueReceived` and the README claimed unconditional per-service isolation, but the filter deliberately passes values whose owning service the platform cannot report; say so where users read it. Mark the `UniversalBlePlatform` override break in the CHANGELOG, since an out-of-tree implementation that overrides `characteristicValueStream` or `updateCharacteristicValue` no longer compiles, and state the scope of subscription tracking now that value routing is service-aware. Add a test that starts at the Pigeon `onValueChanged` callback, so dropping the service on the way in fails in Dart rather than only in the native tests.
* Track subscription state per characteristic instance A GATT database may expose the same characteristic UUID in several services (one Battery Service per battery), and each instance has its own CCC descriptor. The subscription cache was keyed by device and characteristic UUID only, so subscribing to one instance reported every instance as subscribed and unsubscribing one cleared the state that describes the others — a peripheral still notifying for service B was reported as unsubscribed. Key the cache by device -> service -> characteristic, and take the service in `updateSubscription` from the `setNotifiable` call that already carries it. `UniversalBle.isSubscribed` and `getSubscribedCharacteristics` gain an optional `serviceId`: with it they answer for one instance, without it they keep the previous answer, which is "any service exposes this characteristic". `BleCharacteristic.isSubscribed` passes its own service, so it reports the instance it was discovered from. * Sort getSubscribedCharacteristics and cover the unusable-service guard Flattening the per-service sets returned the subscriptions grouped by service, so the same subscriptions could come back in a different order than the previous flat cache produced. Sort both the filtered and the unfiltered result, and say so in the doc comments and the CHANGELOG. The "unusable service id" test subscribed nothing first, so both methods returned at the "no subscriptions for this device" guard before parsing `serviceId`; the test passed even with the try/catch blocks removed. Subscribe one characteristic first so the parse is reached, and assert the valid subscription survives the failed lookups.
…ck#394) (Navideck#395) * Android: refuse requests on a disconnected autoConnect client (Navideck#394) An autoConnect client stays open after a link loss, so writeValue could still find the cached characteristic and the stack could accept the write and drop it without ever calling onCharacteristicWrite. The orphaned pending entry was then completed by the first callback of the reconnected link, so every later write lagged by one and timed out after 10 s - about one write per timeout with the per-device queue. Register a request only while its client's link is up, under the same lock the disconnect cleanup sweeps, so a concurrent submit is either swept or refused with deviceDisconnected. Apply that to reads, writes, descriptor reads/writes and CCCD subscriptions. As a backstop, a client kept open by autoConnect that reports STATE_CONNECTED again fails anything still pending from its previous link. readDescriptorValue now registers its pending result before issuing the read, as readValue already does. * Android: gate every GATT request on a live link, sweep before reconnect (Navideck#394) Follow-up to the autoConnect link-loss fix. - requestMtu, discoverServices and readRssi registered their pending result without the link check, so the same accept-and-drop gap could strand an entry for them. They now register under the disconnect cleanup's lock only while the link is up, and before issuing the request, as readValue does. - A subscription to a characteristic without a CCCD was never gated: there is no CCCD write to refuse, but setCharacteristicNotification() succeeds locally on a linkless client and reported a subscription the stack cannot deliver. It is now refused like any other request. - On STATE_CONNECTED the backstop now sweeps before connectedGatts marks the link up. Otherwise a request that passed the submission gate in that window was failed with deviceDisconnected after the stack had accepted it. - LinkLossOperationTest: theBackstopTouchesOnlyTheReconnectingClient registered its write before the disconnect sweep, which cleanUpConnection already failed, so the test passed with the backstop removed. Register it after the sweep, and add coverage for the sweep ordering, the CCCD-less subscription and the MTU/discovery/RSSI refusal. - MtuCompletionTest attaches its clients as connected, matching the new gate. - README/CHANGELOG: document the wider scope and the dependency on the platform reporting the disconnection. 122 Android unit tests, 0 failures. flutter analyze clean.
…ailures (Navideck#394) (Navideck#396) * Linux/Web: name a disconnected device in GATT request failures (Navideck#394) Neither platform supports autoConnect, so a dropped link removes the GATT objects (BlueZ) or clears the service cache (Web) instead of leaving a client open. A request submitted while disconnected therefore failed as 'characteristic not found' on Linux, and on Web as an unclassified browser NetworkError or a missing characteristic, even though the device was still known and simply not connected. Resolve the device once and refuse the request with deviceDisconnected when the link is down, for reads, writes, descriptor reads/writes and subscriptions - the same set Android gates. A BlueZ device is checked through the platform's Connected property; on Web the connection state comes from the dependency's seeded connected stream, as getConnectionState already reads it. Unknown devices now report deviceNotFound on Web too. * Windows: refuse GATT requests on a link that is already down (Navideck#394) A Windows connection has no autoConnect, but the agent stays registered until the ConnectionStatusChanged handler runs. A request submitted between the drop and that callback was issued to WinRT anyway and completed with Unreachable, which maps to failed rather than deviceDisconnected. Check the link before issuing a read, write, descriptor read/write or subscription, and refuse it with deviceDisconnected. A status read that throws counts as connected so the operation still reports the real error. * Apple: refuse GATT requests on a disconnected peripheral (Navideck#394) Only writeValue and discoverServices guarded on peripheral.state, so a read, descriptor read/write or subscription submitted while the peripheral was disconnected was handed to CoreBluetooth, which cannot serve it. Guard them the same way writeValue does since Navideck#378: characteristic/descriptor lookup first, then deviceDisconnected. No test: these paths need a connected CBPeripheral. The sources typecheck against FlutterMacOS.framework and the isolated Apple test helpers still pass. * Document the platform-wide disconnect behaviour * Web: read the live GATT flag for the disconnect check (Navideck#394) The seeded `connected` stream only learns about a drop once the browser dispatches `gattserverdisconnected`, which happens in a task, so a request issued right after `disconnect()` — or in the turn a drop is detected — still saw the device as connected. It then reached the dependency's discoverServices(), which throws "Cannot discover services if the device is not connected", so the caller got an unclassified error instead of deviceDisconnected. Read the browser's own `gatt.connected` flag instead. The getter is `@visibleForTesting`, so the read is scoped with an ignore. Also align the Linux and Web message with the "Device Disconnected" text Android, Windows and Apple emit, and document the behaviour under Error Handling in the README, including that Linux and Web report deviceDisconnected before the characteristic lookup.
…try, one submit path (Navideck#397) * Android: refuse requests on a disconnected autoConnect client (Navideck#394) An autoConnect client stays open after a link loss, so writeValue could still find the cached characteristic and the stack could accept the write and drop it without ever calling onCharacteristicWrite. The orphaned pending entry was then completed by the first callback of the reconnected link, so every later write lagged by one and timed out after 10 s - about one write per timeout with the per-device queue. Register a request only while its client's link is up, under the same lock the disconnect cleanup sweeps, so a concurrent submit is either swept or refused with deviceDisconnected. Apply that to reads, writes, descriptor reads/writes and CCCD subscriptions. As a backstop, a client kept open by autoConnect that reports STATE_CONNECTED again fails anything still pending from its previous link. readDescriptorValue now registers its pending result before issuing the read, as readValue already does. * Linux/Web: name a disconnected device in GATT request failures (Navideck#394) Neither platform supports autoConnect, so a dropped link removes the GATT objects (BlueZ) or clears the service cache (Web) instead of leaving a client open. A request submitted while disconnected therefore failed as 'characteristic not found' on Linux, and on Web as an unclassified browser NetworkError or a missing characteristic, even though the device was still known and simply not connected. Resolve the device once and refuse the request with deviceDisconnected when the link is down, for reads, writes, descriptor reads/writes and subscriptions - the same set Android gates. A BlueZ device is checked through the platform's Connected property; on Web the connection state comes from the dependency's seeded connected stream, as getConnectionState already reads it. Unknown devices now report deviceNotFound on Web too. * Windows: refuse GATT requests on a link that is already down (Navideck#394) A Windows connection has no autoConnect, but the agent stays registered until the ConnectionStatusChanged handler runs. A request submitted between the drop and that callback was issued to WinRT anyway and completed with Unreachable, which maps to failed rather than deviceDisconnected. Check the link before issuing a read, write, descriptor read/write or subscription, and refuse it with deviceDisconnected. A status read that throws counts as connected so the operation still reports the real error. * Apple: refuse GATT requests on a disconnected peripheral (Navideck#394) Only writeValue and discoverServices guarded on peripheral.state, so a read, descriptor read/write or subscription submitted while the peripheral was disconnected was handed to CoreBluetooth, which cannot serve it. Guard them the same way writeValue does since Navideck#378: characteristic/descriptor lookup first, then deviceDisconnected. No test: these paths need a connected CBPeripheral. The sources typecheck against FlutterMacOS.framework and the isolated Apple test helpers still pass. * Document the platform-wide disconnect behaviour * Share the Android test fixture for GATT wiring Ten test classes rebuilt the same mock device, gatt, service, characteristic and main-looper handler, and most of them repeated the reflection keys for the pending-operation lists. A change to the plugin's internals, or to PluginTestSupport's reflection helpers, had to be mirrored a dozen times. Add GattFixture (one mock peripheral: gatt + service + characteristic + descriptors, optional stack-accepting stubs), pluginWithInlineLooper / pluginWithRecordedLooper with drainPosts, mockGatt / mockCharacteristic, and typed pending-list accessors in PluginTestSupport. Migrate the test classes onto them; no test logic changes. * Track each GATT client's lifecycle in one state field The plugin kept one client's connection state in five places: the address registry, connectedGatts, closingGatts, awaitingReconnectGatts and autoConnectDevices. Every transition in connect() / disconnect() / onConnectionStateChange() / cleanConnection() had to update several of them, and the close fallback timer needed extra bookkeeping to notice that a set had already been cleared. Give each client a GattClient record holding its gatt, its State (CONNECTING, CONNECTED, AWAITING_RECONNECT, CLOSING, CLOSED) and its autoConnect flag, and keep those in GattRegistry. The registry maps an address to the client API calls resolve, and separately tracks clients that are closing or were replaced, so a replacement can be published while the previous client still owes its teardown. Reads that were set membership tests are now state reads: isLinkUp, the superseded check, the keep-open decision and the fallback timer. finishClose() is a compare-and-set, so STATE_DISCONNECTED and the fallback timer cannot close the same client twice. autoConnect moves from an address set to the client: connect() copies the decision onto the client it replaces, and disconnect() withdraws it from every client of the address. * Give pending GATT operations one typed registry Eight hand-written lists held near-identical future classes that differed only in their completion type. Registering, matching the oldest entry, sweeping on a disconnect and delivering the failure were copy-pasted per list: the disconnect sweep alone was eight blocks, and each operation kind had its own lock. Each future now implements PendingOperation (gatt, deviceId, fail), and PendingOperations<T> owns the list under its own monitor with add, addIfLinkedUp, remove, takeOldest, drainMatching, failMatching, any and size. Completion still goes through the plugin's main-looper delivery, with the same per-kind log label. failPendingOperations is eight one-line sweeps, the withdraw helpers are plain remove calls, and the MTU cache shares the MTU collection's lock. The collection also owns the link check the submission paths used to repeat, so a request is still either registered before the sweep or refused (Navideck#394). * Submit GATT requests through one path readValue, writeValue, readDescriptorValue and writeDescriptorValue each repeated the same sequence: resolve the characteristic or descriptor, validate it, register a pending result with the link check, call the stack, withdraw and fail when it refused, and withdraw again in the exception handler. The validation ordering was a comment in three of them, and the refusal mapping was easy to get subtly different. submitGattRequest() now owns registration, submission and withdrawal. It keeps the link check and the registration under the pending collection's lock, so the disconnect sweep cannot strand a request that is accepted afterwards (Navideck#394), and it withdraws a refused or throwing call so a completion cannot be delivered to an orphaned entry (Navideck#387). Callers pass their stack call and the error their operation reports for a refusal, which keeps deviceNotFound, characteristicNotFound, the write-support codes and invalidAttributeLength in their existing order. The withdrawal now also reports whether another path already claimed the reply. A disconnect that sweeps a read or write while its stack call is running answers the Dart call once, instead of racing a second reply. * Split setNotifiable into a CCCD write and the notification toggle The function carried two local closures, a reassigned pending future, nested try/catch around the deprecated and the API 33+ descriptor overloads, and a switch to the characteristic notification. The reply bookkeeping was the hardest part to follow, and it had a real bug: the inner handler withdrew the pending result and rethrew, then the outer handler tried to withdraw again, found nothing, and sent no reply at all. A throwing CCCD write (a descriptor rebuilt by a concurrent discovery, a closed client) left the Dart call awaiting until its timeout. Extract writeCccdDescriptor() and its status mapping, and give the function a single reply path: the pending future is withdrawn once, and the failure is delivered by the same place that detected it. A CCCD callback or disconnect that already owns the reply still wins, so nothing is answered twice. Cover both directions: a throwing CCCD write answers exactly once, and a write swept by a disconnect while the stack refuses it is not answered twice. * Keep the link check and the disconnect report correct through a teardown STATE_DISCONNECTED took the client's link down only after sweeping the pending collections, so a request submitted while the sweep ran passed the link check, registered in a list that had already been swept, and then reached a dead link — the Navideck#394 hang the ordering was meant to prevent. Settle the client's state (AWAITING_RECONNECT or CLOSING) before the sweep, as the old connected-set did, and keep the client in the active slot until it is done so a replacement published meanwhile is still told apart from it. The disconnect report read `wasConnected` from the client's state, which disconnect() has already moved to CLOSING, so a locally initiated teardown that carries a non-zero status reported connectionFailed instead of the status-specific code. GattClient now remembers that the link came up and hands it out once per STATE_DISCONNECTED. cleanConnection() no longer publishes an untracked client: a teardown racing the fallback timer could evict a newer connection from the active slot. And connect() now tears down the client it replaces — a client left waiting for autoConnect to reconnect it was dropped from the registry but never closed, so it kept an open GATT and an autoConnect attempt next to the new link. * Drop the test-only drain hook from PendingOperations beforeDrain ran inside the collection's lock on every drain and existed for one test. Completions are already delivered while the sweep is still running, so that test can publish the replacement from a completion instead and exercise the same ordering without a hook in production code. * Web: read the live GATT flag for the disconnect check (Navideck#394) The seeded `connected` stream only learns about a drop once the browser dispatches `gattserverdisconnected`, which happens in a task, so a request issued right after `disconnect()` — or in the turn a drop is detected — still saw the device as connected. It then reached the dependency's discoverServices(), which throws "Cannot discover services if the device is not connected", so the caller got an unclassified error instead of deviceDisconnected. Read the browser's own `gatt.connected` flag instead. The getter is `@visibleForTesting`, so the read is scoped with an ignore. Also align the Linux and Web message with the "Device Disconnected" text Android, Windows and Apple emit, and document the behaviour under Error Handling in the README, including that Linux and Web report deviceDisconnected before the characteristic lookup.
* CI: typecheck the Apple sources on every pull request No workflow job built the darwin sources: the pull request checks are Windows, Linux, Android, Chrome and pana, so a Swift change was only verified by whoever ran it locally. That is how the guards added in Navideck#394 could reach review with nothing but a local typecheck behind them. Add a macOS job that downloads Flutter's macOS and iOS engine frameworks and typechecks the shared plugin sources against each: the files branch with #if os(...) and import FlutterMacOS or Flutter, so a single platform's module only proves that platform's branch. It also runs the three isolated Apple helpers (write ownership, discovery progress, central restoration ownership), which compile one source file each with counted assertions. * CI: resolve the Apple engine layout by looking for the frameworks The job failed twice on the runner. First the hosted SDK's engine directory existed without the macOS framework, so precache skipped the download. Then, once it did download, the framework turned out to be a slice inside FlutterMacOS.xcframework rather than a bare FlutterMacOS.framework beside the engine artifacts — and the directory is named after the host arch (darwin-x64, darwin-arm64). Move the typecheck into .github/scripts/typecheck_apple.sh, which locates the macOS framework in either layout under the arch-named directory, resolves the iOS flutter.xcframework/ios-arm64 slice, forces the precache download when either is missing, and prints the engine listing if they still are not found. The two workflow steps only call it, with --download-only for the fetch step. Verified locally against both layouts: the installed SDK's bare framework and a simulated runner tree with FlutterMacOS.xcframework/macos-arm64_x86_64.
…k#399) * Apple: manual HIL coverage for the Navideck#394 disconnect guard PR Navideck#396 left the Apple half of the fail-fast check untested: the guard needs a connected CBPeripheral, and there is no unit-level substitute. Add two manual integration tests to the example app, to be run on a Mac or an iOS device against a nearby peripheral that exposes a readable, a notifiable and a descriptor-bearing characteristic (the file documents the one used). apple_gatt_disconnect_test.dart Deterministic. Verifies the connected path (read, descriptor read, descriptor write through CCCD, subscribe/unsubscribe) and then both windows a link loss produces: requests raced against disconnect() while the peripheral is .disconnecting and still holds its attribute tree (all four report deviceDisconnected, the Navideck#396 guard), and requests after the disconnect completes (all four report characteristicNotFound, because CoreBluetooth has discarded CBPeripheral.services and the lookup runs before the guard). Both are refused locally, never handed to CoreBluetooth. apple_link_loss_test.dart The real link-loss case. Connects (optionally with autoConnect), waits for the peripheral to drop the link on its own, then immediately issues the same four requests and reports their codes. A drop has to be triggered on the peripheral side; the file explains how to set the wait and what NO_LINK_LOSS means. Neither test runs in CI. Observed on macOS 26.6.2 and iPadOS 26.6.1 with identical results. On iPadOS the Bluetooth prompt only surfaced once the example's NSAccessorySetupKitSupports keys were absent, so the test waits for poweredOn before scanning. * Apple: check the link before the GATT lookup The Navideck#394 guard Navideck#396 added checked `CBPeripheral.state` after the characteristic/descriptor lookup. CoreBluetooth discards a peripheral's attribute tree when the link drops, so by the time a request arrives after the drop the lookup fails first and the caller still got characteristicNotFound for a characteristic it had just used. The guard only fired in the .disconnecting window, where the tree is still cached. Move the state check ahead of the lookup in readValue, writeValue, setNotifiable, readDescriptorValue and writeDescriptorValue, matching Linux and Web. A request on a disconnected peripheral now reports deviceDisconnected whether or not CoreBluetooth still holds the tree; an unknown characteristic on a connected peripheral still reports characteristicNotFound. Android keeps the lookup-first order because an autoConnect client stays open with its services cached, which is what makes its link check reachable; a client it closes reports deviceNotFound instead. README and CHANGELOG now describe the platform split that way. Verified with example/integration_test/apple_gatt_disconnect_test.dart on macOS 26.6.2 and iPadOS 26.6.1 against a real peripheral: the connected path (read, descriptor read/write, subscribe) passes, and both the raced and the settled disconnect report deviceDisconnected for all four operations. * iOS example: build on Xcode 26 and get Bluetooth on a fresh install Two local fixes the iPad HIL run needed, kept in the repo: - Raise the example's iOS deployment target from 13.1 to 15.0 (Runner project and Podfile). Xcode 26 refuses to build 13.1; the plugin's own podspec keeps its 13.1 minimum for library consumers. - Drop the NSAccessorySetupKitSupports / NSAccessorySetupBluetoothServices / NSAccessorySetupBluetoothNames keys. With them, iPadOS 26.6.1 did not show the broad Bluetooth permission prompt on a fresh install: CBCentralManager stayed poweredOff and scanning found nothing for 90 s. Without them the prompt appears and the scan works. The example README explains that the AccessorySetupKit picker needs the keys added back, and that one build cannot do both on a first install. * Android/Windows/Apple: gate every request on the link before the lookup Steps 1 and 3 of the cross-platform alignment; step 2 (what a closed client reports) is a separate change. - Android: readValue, writeValue, setNotifiable, readDescriptorValue and writeDescriptorValue check isLinkUp(gatt) before the characteristic lookup. An autoConnect client keeps its cached tree across a link loss, so the lookup could still fail with characteristicNotFound for a characteristic the caller had used; the answer now depends on the connection, not the cache. submitGattRequest/addIfLinkedUp keep their lock-protected check as the authoritative one for the Navideck#394 race. - Windows: HasLiveLink now runs before FetchCharacteristicForOperation in ReadValue, WriteValue, ReadDescriptorValue, WriteDescriptorValue and SetNotifiableAsync, for the same reason. - Apple: requestMtu and readRssi refuse a disconnected peripheral with deviceDisconnected instead of reaching CoreBluetooth, and discoverServices uses the same "Device Disconnected" message, so the gated set and the error text match Android. Result: a known device whose link is down reports deviceDisconnected whether or not the cached attribute tree still holds the characteristic; characteristicNotFound now means the link was up. Clients the plugin has already forgotten still report deviceNotFound on Android and Windows (step 2). Verification: Android unit tests 129 passed (two new cases: an unknown characteristic on a dropped link reports disconnected, and on a live link it still reports not-found); Apple sources typecheck for macOS and iOS, the three isolated helpers pass, flutter analyze clean, flutter test 341 passed. The macOS HIL run against FS-7A25F8 now exercises six gated calls: MTU and RSSI succeed while connected and report deviceDisconnected in both the raced and the settled disconnect. Windows is compile-checked by CI. * Trim the link-check comments and drop the link-loss probe The precedence rule was repeated as a five-line comment at every call site (five times in the Android plugin, three plus two in the Swift one). State it once next to isLinkUp and leave a single line where the check is made. Delete example/integration_test/apple_link_loss_test.dart. It waits for a peripheral to drop the link on its own, which the test device never does without help, so it cannot run unattended; apple_gatt_disconnect_test.dart covers the raced and the settled disconnect deterministically. * Review follow-ups: doc accuracy, descriptor coverage, HIL cleanup - README: drop the claim that characteristicNotFound implies a live link. Android reports it for a read the stack refuses to start, which the parallel-queueId flow can produce on a live link. - requestMtu: document that a disconnected device fails with deviceDisconnected, including iOS/macOS where the value is local. - Retarget the Android value-length comments to the reordered checks: a wrong device, attribute or operation now outranks an oversized payload. - Add the descriptor precedence tests, dropped link and live link, as the characteristic paths already have. - Warn in the example's picker sheet that this build omits the AccessorySetupKit keys, so the picker cannot be shown. - HIL test: record unexpected error types instead of aborting the run, and disconnect in a teardown so a failed assertion leaves no link open.
…avideck#401) Windows reserves a few GATT services for its own stack and answers GetCharacteristicsAsync with AccessDenied for them whether or not the device is paired. HID over GATT (0x1812) is the common one. Since Navideck#284 turned the discovery loop's `continue` into `break`, that answer aborted the whole connection attempt, so a device exposing HID could not connect at all. classify_discovery_status() in windows/src/gatt_discovery_policy.h maps the status to include, skip or fail, and both discovery loops use it. AccessDenied is skipped, so the reserved service stays out of the service map while the rest of the database connects normally. Unreachable and ProtocolError still fail discovery, which keeps Navideck#284's intent of reporting a discovery a dropped link cut short. Two boundaries keep the skip from hiding a real problem. AccessDenied is not exclusive to reserved services, so if every service of a device was denied the connection still succeeds but a warning names the count. In the Service Changed refresh, a denied service the map already exposes is not dropped: reads and subscriptions are live against it, so the previous map is kept and the error is logged, as before the loop skipped reserved services. Cover it with the fixture's existing SET_HID_SERVICE command (0x17): the new Windows HIL test registers the HID service, reconnects so connect-time discovery meets the denied service, checks the reserved service is absent while the fixture's own service stays readable, then adds the auxiliary service and requires it to appear, which proves the refresh walked past the denied service. A Windows unit test pins the status classification for pull-request CI, where the HIL suite does not run.
…end (Navideck#403) (Navideck#404) * Android peripheral: one lock around the notification value and its send Below API 33 notifyCharacteristicChanged takes the payload from the shared BluetoothGattCharacteristic.value, and two threads wrote it. updateCharacteristic set it unconditionally on the main thread, while drainNotifications assigned the next queued payload and called notifyCharacteristicChanged outside the pendingNotifications monitor — the in-flight check was outside it too. Called from onNotificationSent on the binder thread, a main-thread update could land between that assignment and the notify call, so a payload of the same length was silently transmitted with the wrong content: corrupted reports when a characteristic is updated faster than the stack drains its notifications. drainNotifications now does the in-flight check, the dequeue, the server lookup, the in-flight marker, the value assignment and the notify call inside one synchronized(pendingNotifications) block. API 33 and newer take the stateless four-argument overload and treat only BluetoothStatusCodes.SUCCESS as sent; the deprecated three-argument path stays for older releases. On failure the marker is still removed and the payload pushed back to the front, so no notification is dropped. updateCharacteristic resolves the subscribed devices before taking that monitor, because isSubscribed takes subscribedCharDevicesMap and the descriptor and cleanup paths take those two monitors in the opposite order; nesting them the other way would deadlock. The static, readable value is now written only when no target device is subscribed, instead of on every update, so a queued update cannot overwrite the value an in-flight notification is being sent from. Verification: queuedUpdateDoesNotOverwriteInFlightCharacteristicValue added to PeripheralRegressionTest (fails against the previous code, passes now); Android unit tests 132 passed; flutter test 341 passed; flutter analyze clean.
…) Darwin queue (Navideck#402) (Navideck#405) Three independent causes made a bulk notification transfer slow (~15 KB/s): the Darwin update was fire-and-forget, macOS negotiated latency=1, and the Darwin pending queue removed elements with Array.removeFirst(). This also carries the Navideck#403 Android notification-race fix, aligned with fix/403-android-notification-race (Navideck#404) so that Navideck#405 rebases cleanly once it lands: the transmit critical section is the same code, and the only additions here are the async settlement and completion aggregation. * A completion contract for updateCharacteristicValue `UniversalBlePeripheralChannel.updateCharacteristic` is now an async Pigeon callback, so the Dart future completes when the notification is settled rather than when it was handed to the plugin. Awaiting it between chunks is therefore real backpressure, and a native failure reaches the caller. Android completes on `onNotificationSent` (success on GATT_SUCCESS, failure otherwise). Apple completes when CBPeripheralManager.updateValue returns true, immediately or after peripheralManagerIsReady(toUpdateSubscribers). Windows completes from the NotifyValueAsync completion handler. With several targets, the call completes once all settle, reporting the first error; a call with no subscriber still updates the readable value and completes immediately. A queued update that can never be sent now fails with a descriptive error instead of leaving the Dart future pending: clearPendingNotifications, removeService/clearServices, central unsubscription, adapter reset, engine disposal and device disconnect all settle what they discard. Each update is settled exactly once. * Apple: O(1) queue and connection latency PeripheralNotificationQueue keeps a read head index over its storage instead of shifting the tail per chunk; storage is compacted in batches and released when drained. drain() reports each accepted element through onSent exactly once, and removeAll()/removeAll(where:) return what they discarded so those callers can be failed. Backpressure semantics are unchanged. Add UniversalBlePeripheral.setDesiredConnectionLatency (Apple only), mapped to CBPeripheralManager.setDesiredConnectionLatency(_:for:). It throws notFound for an unknown central. initialValues still receives the last value on every update: that assignment is O(1) and was not the quadratic cost. * Android: settle from onNotificationSent, and the Navideck#403 race Track the in-flight PendingNotification per client address rather than just a busy marker, so onNotificationSent can complete the right update. Settlement is posted to the main handler; no Dart callback runs on a binder thread or under the pendingNotifications monitor. The settlement is queued before the next packet is handed to the stack, so two updates for one client complete in submission order. Apply the Navideck#403 fix in the same path: updateCharacteristic only writes characteristic.value when nobody is subscribed, and drainNotifications holds the pendingNotifications monitor across the in-flight check, dequeue, bookkeeping, value assignment and notifyCharacteristicChanged. API 33+ uses the stateless four-argument call and treats BluetoothStatusCodes.SUCCESS as sent; older releases keep the deprecated three-argument call. isSubscribed is resolved before taking the pending monitor, since the descriptor-write and disconnect paths take the two locks in the opposite order. * Windows: reply from the completion handler UpdateCharacteristic returns the Pigeon reply callback and completes it from NotifyValueAsync.Completed (success) or a non-completed status (failure), and from the synchronous catch as before. The callback is copied into the lambda rather than moved, so the catch path still holds a valid std::function instead of throwing std::bad_function_call. Failure logging is unchanged. * Dart, docs and tests Add the platform-interface default no-op, the iOS/macOS-only forwarding that canonicalises the device id, the public API and the PeripheralConnectionLatency export. Rewrite the updateCharacteristicValue and README completion semantics to describe pacing bulk transfers by awaiting the future, and document the latency setter. CHANGELOG records the behavioural change under Unreleased. Tests: Android adds four cases for the completion contract (accepted packet is not completed early, non-success status fails, the Navideck#403 queued update does not overwrite the in-flight value, and clearPendingNotifications/reset fail what they discard). The Apple helper covers onSent exactly once, blocked elements not reported until resume, and removeAll returning removed elements. Dart adds the Apple forwarding/no-op latency test and two channel tests proving the future waits for the native settlement reply and surfaces its failure. Generated files were rebuilt with Pigeon 29.0.12, the version origin/main's files were generated with, so their diff is limited to the new enum, the asyncCallback signature and setDesiredConnectionLatency plus the resulting codec type-index renumbering. Verification: flutter analyze clean, flutter test 344 passed, Android unit tests 136 passed, the Apple native reliability checks pass, and the shared Apple sources typecheck for macOS and iOS. Windows is compile-checked by CI; it cannot be built on macOS. (Navideck#402)
…ontract (Navideck#406) * Peripheral: document and test the updateCharacteristicValue timeout contract * Peripheral: correct the timeout and recovery docs for updateCharacteristicValue The README and the dartdoc said the update future is bounded by the peripheral command timeout, but in QueueType.global and QueueType.perDevice the timeout starts only when the queue item runs: Queue._QueuedFuture.execute wraps closure() in .timeout() at that point, so time spent waiting behind earlier commands is not counted. QueueType.none, the QueueType.auto default on Apple and Windows, bounds the call as submitted. Say which one applies. The recovery advice also overclaimed clearPendingNotifications. On Android it drops the queued notifications and keeps the in-flight marker until onNotificationSent arrives (dropNotifications(includeInFlight = false), as asserted by clearPendingNotificationsFailsQueuedUpdatesButKeepsTheOneInFlight), so later updates for that client still wait behind the packet that timed out. Windows has no plugin-owned queue: ClearPendingNotifications returns without touching anything, so an operation already running cannot be cancelled. Spell out what the call discards and what it cannot recall. List UniversalBlePeripheral.timeout in the README Timeout section, which only covered UniversalBle.timeout, and cross-link the notification caveats. Also explain why the "does not wedge the queue" test releases its gate after the second submission: the fake reads the field when the platform call starts, so the first update keeps the never-completing completer. Verification: flutter analyze clean, flutter test 348 passed, and this test file also passes under flutter test --platform chrome.
) (Navideck#407) drainNotifications pushes a refused payload (notifyCharacteristicChanged returns false) back to the front of pendingNotifications and removes the in-flight marker. Nothing then schedules another drain: the marker was absent before the send, so there is no packet whose onNotificationSent would retry it. The queued update therefore waits for an unrelated updateCharacteristic for the same client, and every later update queues behind it. A payload enqueued in the window between the isSubscribed check in updateCharacteristic and the enqueue (a CCCD unsubscribe can land in between) could likewise be transmitted stale after a resubscription. A refusal now schedules a retry for that client on the existing main Handler. At most one runnable exists per address, so further refusals coalesce into it. The delay is 10 ms, doubled per consecutive refusal and capped at 500 ms; the attempt counter stops at the ceiling so the shift distance stays in range, and a successful send clears it, leaving at most one int map entry per device. The runnable re-checks the subscription outside the pendingNotifications monitor, because isSubscribed takes subscribedCharDevicesMap and the descriptor/cleanup paths take the two monitors in the opposite order. When the client has unsubscribed, the queued payloads of the characteristic at the head of its queue are dropped with dropNotifications(includeInFlight = false) and settled with "Central unsubscribed", which ends the retry loop, and the client's other characteristics still drain. A client that resubscribes before the retry fires is treated as still wanting the update, like any queued payload. Settlements still go through settleNotifications, so no Dart callback runs on a binder thread. Disconnect, adapter reset, removeService/clearServices, clearPendingNotifications and the CCCD unsubscribe path cancel a retry that is no longer needed, and the onNotificationSent flow that settles a successful send is unchanged. The queued payload a drain finds with no server is unreachable through the public paths and now says so instead of scheduling a retry against a server that is still null. Tests (PeripheralRegressionTest) add a captured postDelayed helper that runs retries manually, never with real delays, and cover: one retry for a refusal that succeeds when it runs, one retry for several queued updates, the 10/20/40/80/160/320/500/500 ms backoff, the unsubscribe drop with a failed callback and no resend after resubscribing, dropping the unsubscribed characteristic while the client's other characteristic keeps draining, disconnect/removeService/reset/clearPendingNotifications cancelling the runnable and failing the queue, removeService keeping a retry that another service's payload still needs, and the attempt state cleared by a successful send. The retry cases fail against the unfixed production file ("The refusal schedules exactly one retry ==> expected: <1> but was: <0>"). Verification: flutter analyze clean, flutter test 344 passed, Android unit tests 145 passed (142 before).
RefreshGattServicesAsync disposes the replaced service maps, and with them calls GattDeviceService::Close, on whichever apartment its co_awaits resume in. Started on Flutter's STA, that Close can re-enter the STA while Windows is already closing the same service and wait on itself forever, the hang DisposeConnection and DisposePartialConnection already avoid. Hop to the thread pool first, so every continuation and Close runs on MTA. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…builds The Windows native log only goes to stdout, gated by setLogLevel, which is debug-only. A release Windows app has no stdout, so an error the plugin catches and survives (e.g. the peripheral callback guards) left no trace in an app's own logs or support reports. UniversalBleLogger now forwards every error and warning, whatever the log level, to a sink the plugin installs; the plugin posts it to the UI thread and sends it over a new pigeon FlutterApi, UniversalBleNativeLogCallback. Apps receive it with UniversalBle.nativeLogHandler. The sink is cleared first in the plugin's destructor, and a thread-local guard drops a message logged from inside the sink instead of deadlocking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A second Flutter engine (e.g. an overlay window) creates its own plugin instance. With a single global sink it took the sink over, and its teardown left the main engine with none. Each instance now keeps its own sink; messages go to all of them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PeripheralSubscribedClientsChanged is a fire_and_forget coroutine with no exception handling. Session(), DeviceId() and MaxPduSize() throw for a client whose link has just dropped (the departed-client loop asks exactly those), and an exception escaping a fire_and_forget terminates the process. The handler is now guarded and logs instead. The read-request responses (RespondWithValue / RespondWithProtocolError) run on the UI thread from the Dart callback and throw when the request can no longer be answered; they are now guarded like the write path already was. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FlutterError(code, message, nullptr) picks EncodableValue(const char*), which calls strlen(NULL). RemoveService for an unknown service and every UpdateCharacteristic error path crashed instead of returning the error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
C++/WinRT resumes each co_await on the apartment the coroutine started on, so ConnectAsync, started from Flutter's Connect handler, ran every step of an attempt on the UI thread (STA): device lookup, uncached service and characteristic discovery, event registration. Each is a cross-process call into the Bluetooth service in svchost. A peripheral rebooting mid-connect (a Click V2 left side restarts about once a minute) can stall that service, and the window then stops responding (MoAppHangXProc waiting on svchost). ConnectAsync now leaves the STA before its first Bluetooth call, as RefreshGattServicesAsync and the dispose paths already do. Results still reach Dart through NotifyConnectionChanged, which posts to the UI thread. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
CI only: runs the PR workflow (flutter build windows + ctest on windows-latest) on the BikeControl port of the fork onto upstream 3.4.2. Do not merge.
Ported: 31bdd4a, 14a8c73, 2fd85f2, b87bf63.
Skipped: 04f3030 (covered by upstream Navideck#402/Navideck#405), 848138a + 4d1ab9a (covered by upstream Navideck#400).
🤖 Generated with Claude Code