chore(#686): vendor flutter_blue_plus_winrt from upstream master 7b4504a2

Pristine, unmodified import of chan150/flutter_blue_plus_winrt at
7b4504a2bf8409e7f01118c870ead435c1b1d681 (MIT, Copyright 2025 Himchan Park;
LICENSE retained). All 14 files hash-verified against the fetched upstream
tarball.

Vendored rather than depended on because no published version reports the BLE
MTU on Windows: gatt_sessions_ is declared but never populated, so the MTU
stays at the 23-byte default and the composer is capped at 0-4 bytes (#592,
diagnosed in #683). Our fix lands as a separate commit on top of this one so
it can be reviewed and re-applied against a future upstream.

Based on master rather than 0.0.19 to pick up two unreleased upstream fixes:
86ef4763 (data race, unbounded caches, teardown use-after-free) and 7b4504a2
(revoke per-device ConnectionStatusChanged handlers on teardown).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/741/head
diffwireauto 2 months ago committed by Benjamin Wiechel
parent ae5676741e
commit 01db7eb621

@ -0,0 +1,31 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins-dependencies
/build/
/coverage/

@ -0,0 +1,10 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "19074d12f7eaf6a8180cd4036a430c1d76de904e"
channel: "stable"
project_type: package

@ -0,0 +1,61 @@
## 0.0.18
* Fix multithreading & connection stability (#5)
## 0.0.17
* Fix: Initialize `manufacturer_data` map correctly (#10)
## 0.0.16
* Fix: MTU was always 23 on Windows. Now reports negotiated MTU correctly.
## 0.0.15
* Fix: missing runtimeobject.lib (#7)
## 0.0.14
* Improve: `systemDevices` now discovers both paired and connected devices.
* Fix: Build error (unused variable warning) in `flutterRestart`.
## 0.0.13
* Feat: Add bonding support and improve connection logic.
## 0.0.12
* Fix: Resolve extensive compilation errors (C2220, C2065, C2653, C4456) caused by scope resolution and variable shadowing in GATT discovery logic.
* Fix: `readRssi` now handles cache misses gracefully by returning 0 instead of throwing an exception when RSSI is not in the cache.
## 0.0.11
* Refactor characteristic lookup and fix memory management.
## 0.0.10
* Fix: ensure memory resources (like RSSI cache) are properly cleared upon disconnection.
## 0.0.9
* Fix: "vector erase iterator outside range" crash by safely handling device closure to avoid synchronous vector modifications.
## 0.0.8
* Fix: ensure `connect` method waits for actual physical connection completion before returning a result.
## 0.0.7
* Fix: ensure `connect` returns `false` on failure instead of throwing an exception.
* Improvement: refined connection state waiting logic for better reliability.
## 0.0.6
* Fix: ensure `connect` method waits for actual physical connection completion before returning a result.
* Fix: enhanced thread safety during rapid connection and disconnection to prevent `vector erase` crashes.
* Improvement: more robust resource cleanup when connection attempts fail.
## 0.0.5
* Fix: compilation errors (C2220) and typos in method signatures.
## 0.0.4
* Fix: crash during connection/disconnection caused by invalid vector iterators.
* Feature: add `setOptions` implementation.
## 0.0.3
* Fix: ensure physical disconnection by explicitly closing all GATT services.
* Fix: potential race condition where a device might stay connected if disconnected during the connection process.
* Fix: properly clear characteristic and descriptor caches upon disconnection.
## 0.0.2
* Fix: a version issue with `flutter_blue_plus_platform_interface` #1
## 0.0.1
* Initial release.

@ -0,0 +1,7 @@
Copyright 2025 Himchan Park
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,15 @@
# flutter_blue_plus_winrt
The Windows implementation of [`flutter_blue_plus`][1].
## Usage
This package is [endorsed][2], which means you can simply use `flutter_blue_plus`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
[1]: https://pub.dev/packages/flutter_blue_plus
[2]: https://flutter.dev/to/endorsed-federated-plugin

@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/tools/linter-rules.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/tools/analysis

@ -0,0 +1,555 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
final class FlutterBluePlusWinrt extends FlutterBluePlusPlatform {
@visibleForTesting
final methodChannel = const MethodChannel('flutter_blue_plus/methods');
var _initialized = false;
var _logLevel = LogLevel.none;
var _logColor = true;
final _onAdapterStateChangedController = StreamController<BmBluetoothAdapterState>.broadcast();
final _onBondStateChangedController = StreamController<BmBondStateResponse>.broadcast();
final _onCharacteristicReceivedController = StreamController<BmCharacteristicData>.broadcast();
final _onCharacteristicWrittenController = StreamController<BmCharacteristicData>.broadcast();
final _onConnectionStateChangedController = StreamController<BmConnectionStateResponse>.broadcast();
final _onDescriptorReadController = StreamController<BmDescriptorData>.broadcast();
final _onDescriptorWrittenController = StreamController<BmDescriptorData>.broadcast();
final _onDiscoveredServicesController = StreamController<BmDiscoverServicesResult>.broadcast();
final _onMtuChangedController = StreamController<BmMtuChangedResponse>.broadcast();
final _onNameChangedController = StreamController<BmNameChanged>.broadcast();
final _onReadRssiController = StreamController<BmReadRssiResult>.broadcast();
final _onScanResponseController = StreamController<BmScanResponse>.broadcast();
final _onServicesResetController = StreamController<BmBluetoothDevice>.broadcast();
final _onDetachedFromEngineController = StreamController<BmDetachedFromEngineResponse>.broadcast();
@override
Stream<BmBluetoothAdapterState> get onAdapterStateChanged {
return _onAdapterStateChangedController.stream;
}
@override
Stream<BmBondStateResponse> get onBondStateChanged {
return _onBondStateChangedController.stream;
}
@override
Stream<BmCharacteristicData> get onCharacteristicReceived {
return _onCharacteristicReceivedController.stream;
}
@override
Stream<BmCharacteristicData> get onCharacteristicWritten {
return _onCharacteristicWrittenController.stream;
}
@override
Stream<BmConnectionStateResponse> get onConnectionStateChanged {
return _onConnectionStateChangedController.stream;
}
@override
Stream<BmDescriptorData> get onDescriptorRead {
return _onDescriptorReadController.stream;
}
@override
Stream<BmDescriptorData> get onDescriptorWritten {
return _onDescriptorWrittenController.stream;
}
@override
Stream<BmDiscoverServicesResult> get onDiscoveredServices {
return _onDiscoveredServicesController.stream;
}
@override
Stream<BmMtuChangedResponse> get onMtuChanged {
return _onMtuChangedController.stream;
}
@override
Stream<BmNameChanged> get onNameChanged {
return _onNameChangedController.stream;
}
@override
Stream<BmReadRssiResult> get onReadRssi {
return _onReadRssiController.stream;
}
@override
Stream<BmScanResponse> get onScanResponse {
return _onScanResponseController.stream;
}
@override
Stream<BmBluetoothDevice> get onServicesReset {
return _onServicesResetController.stream;
}
@override
Stream<BmDetachedFromEngineResponse> get onDetachedFromEngine {
return _onDetachedFromEngineController.stream;
}
static void registerWith() {
FlutterBluePlusPlatform.instance = FlutterBluePlusWinrt();
}
@override
Future<bool> clearGattCache(
BmClearGattCacheRequest request,
) async {
return await _invokeMethod<bool>(
'clearGattCache',
request.remoteId.str,
) == true;
}
@override
Future<bool> connect(
BmConnectRequest request,
) async {
return await _invokeMethod<bool>(
'connect',
request.toMap(),
) == true;
}
@override
Future<bool> createBond(
BmCreateBondRequest request,
) async {
return await _invokeMethod<bool>(
'createBond',
request.toMap(),
) == true;
}
@override
Future<bool> disconnect(
BmDisconnectRequest request,
) async {
return await _invokeMethod<bool>(
'disconnect',
request.remoteId.str,
) == true;
}
@override
Future<bool> discoverServices(
BmDiscoverServicesRequest request,
) async {
return await _invokeMethod<bool>(
'discoverServices',
request.remoteId.str,
) == true;
}
@override
Future<BmBluetoothAdapterName> getAdapterName(
BmBluetoothAdapterNameRequest request,
) async {
return BmBluetoothAdapterName(
adapterName: await _invokeMethod(
'getAdapterName',
),
);
}
@override
Future<BmBluetoothAdapterState> getAdapterState(
BmBluetoothAdapterStateRequest request,
) async {
return BmBluetoothAdapterState.fromMap(
await _invokeMethod(
'getAdapterState',
),
);
}
@override
Future<BmBondStateResponse> getBondState(
BmBondStateRequest request,
) async {
return BmBondStateResponse.fromMap(
await _invokeMethod(
'getBondState',
request.remoteId.str,
),
);
}
@override
Future<BmDevicesList> getBondedDevices(
BmBondedDevicesRequest request,
) async {
return BmDevicesList.fromMap(
await _invokeMethod(
'getBondedDevices',
),
);
}
@override
Future<PhySupport> getPhySupport(
PhySupportRequest request,
) async {
return PhySupport.fromMap(
await _invokeMethod(
'getPhySupport',
),
);
}
@override
Future<BmDevicesList> getSystemDevices(
BmSystemDevicesRequest request,
) async {
// Windows implementation currently takes request.toMap(), platform interface default does not.
// Keeping request.toMap() for consistency with existing Windows code.
return BmDevicesList.fromMap(
await _invokeMethod(
'getSystemDevices',
request.toMap(),
),
);
}
@override
Future<bool> isSupported(
BmIsSupportedRequest request,
) async {
return await _invokeMethod<bool>(
'isSupported',
) == true;
}
@override
Future<bool> readCharacteristic(
BmReadCharacteristicRequest request,
) async {
return await _invokeMethod<bool>(
'readCharacteristic',
request.toMap(),
) == true;
}
@override
Future<bool> readDescriptor(
BmReadDescriptorRequest request,
) async {
return await _invokeMethod<bool>(
'readDescriptor',
request.toMap(),
) == true;
}
@override
Future<bool> readRssi(
BmReadRssiRequest request,
) async {
return await _invokeMethod<bool>(
'readRssi',
request.remoteId.str,
) == true;
}
@override
Future<bool> removeBond(
BmRemoveBondRequest request,
) async {
return await _invokeMethod<bool>(
'removeBond',
request.remoteId.str,
) == true;
}
@override
Future<bool> requestConnectionPriority(
BmConnectionPriorityRequest request,
) async {
return await _invokeMethod<bool>(
'requestConnectionPriority',
request.toMap(),
) == true;
}
@override
Future<bool> requestMtu(
BmMtuChangeRequest request,
) async {
return await _invokeMethod<bool>(
'requestMtu',
request.toMap(),
) == true;
}
@override
Future<bool> setLogLevel(
BmSetLogLevelRequest request,
) async {
_logLevel = request.logLevel;
_logColor = request.logColor;
return await _invokeMethod<bool>(
'setLogLevel',
request.logLevel.index,
) == true;
}
@override
Future<bool> setNotifyValue(
BmSetNotifyValueRequest request,
) async {
return await _invokeMethod<bool>(
'setNotifyValue',
request.toMap(),
) == true;
}
@override
Future<bool> setOptions(
BmSetOptionsRequest request,
) async {
return await _invokeMethod<bool>(
'setOptions',
request.toMap(),
) == true;
}
@override
Future<bool> setPreferredPhy(
BmPreferredPhy request,
) async {
return await _invokeMethod<bool>(
'setPreferredPhy',
request.toMap(),
) == true;
}
@override
Future<bool> startScan(
BmScanSettings request,
) async {
return await _invokeMethod<bool>(
'startScan',
request.toMap(),
) == true;
}
@override
Future<bool> stopScan(
BmStopScanRequest request,
) async {
return await _invokeMethod<bool>(
'stopScan',
) == true;
}
@override
Future<bool> turnOff(
BmTurnOffRequest request,
) async {
return await _invokeMethod<bool>(
'turnOff',
) == true;
}
@override
Future<bool> turnOn(
BmTurnOnRequest request,
) async {
return await _invokeMethod<bool>(
'turnOn',
) == true;
}
@override
Future<bool> writeCharacteristic(
BmWriteCharacteristicRequest request,
) async {
return await _invokeMethod<bool>(
'writeCharacteristic',
request.toMap(),
) == true;
}
@override
Future<bool> writeDescriptor(
BmWriteDescriptorRequest request,
) async {
return await _invokeMethod<bool>(
'writeDescriptor',
request.toMap(),
) == true;
}
Future<T?> _invokeMethod<T>(
String method, [
dynamic arguments,
]) async {
// initialize
await _initFlutterBluePlus();
// log args
if (_logLevel == LogLevel.verbose) {
var func = '<$method>';
var args = arguments.toString();
func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func;
args = _logColor ? '\x1B[1;35m$args\x1B[0m' : args;
print('[FBP] $func args: $args');
}
// invoke
final out = await methodChannel.invokeMethod<T>(method, arguments);
// log result
if (_logLevel == LogLevel.verbose) {
var func = '($method)';
var result = out.toString();
func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func;
result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result;
print('[FBP] $func result: $result');
}
return out;
}
Future<void> _initFlutterBluePlus() async {
if (_initialized) {
return;
}
_initialized = true;
// set platform method handler
methodChannel.setMethodCallHandler(_methodCallHandler);
// flutter restart - wait for all devices to disconnect
if ((await methodChannel.invokeMethod('flutterRestart')) != 0) {
await Future.delayed(const Duration(milliseconds: 50));
while ((await methodChannel.invokeMethod('connectedCount')) != 0) {
await Future.delayed(const Duration(milliseconds: 50));
}
}
}
Future<void> _methodCallHandler(
MethodCall call,
) async {
// log result
if (_logLevel == LogLevel.verbose) {
var func = '[[ ${call.method} ]]';
var result = switch (call.method) {
'OnDiscoveredServices' => _prettyPrint(call.arguments),
_ => call.arguments.toString(),
};
func = _logColor ? '\x1B[1;30m$func\x1B[0m' : func;
result = _logColor ? '\x1B[1;33m$result\x1B[0m' : result;
print('[FBP] $func result: $result');
}
// handle method call
switch (call.method) {
case 'OnAdapterStateChanged':
return _onAdapterStateChangedController.add(
BmBluetoothAdapterState.fromMap(
call.arguments,
),
);
case 'OnBondStateChanged':
return _onBondStateChangedController.add(
BmBondStateResponse.fromMap(
call.arguments,
),
);
case 'OnCharacteristicReceived':
return _onCharacteristicReceivedController.add(
BmCharacteristicData.fromMap(
call.arguments,
),
);
case 'OnCharacteristicWritten':
return _onCharacteristicWrittenController.add(
BmCharacteristicData.fromMap(
call.arguments,
),
);
case 'OnConnectionStateChanged':
return _onConnectionStateChangedController.add(
BmConnectionStateResponse.fromMap(
call.arguments,
),
);
case 'OnDescriptorRead':
return _onDescriptorReadController.add(
BmDescriptorData.fromMap(
call.arguments,
),
);
case 'OnDescriptorWritten':
return _onDescriptorWrittenController.add(
BmDescriptorData.fromMap(
call.arguments,
),
);
case 'OnDetachedFromEngine':
return _onDetachedFromEngineController.add(
BmDetachedFromEngineResponse(),
);
case 'OnDiscoveredServices':
return _onDiscoveredServicesController.add(
BmDiscoverServicesResult.fromMap(
call.arguments,
),
);
case 'OnMtuChanged':
return _onMtuChangedController.add(
BmMtuChangedResponse.fromMap(
call.arguments,
),
);
case 'OnNameChanged':
return _onNameChangedController.add(
BmNameChanged.fromMap(
call.arguments,
),
);
case 'OnReadRssi':
return _onReadRssiController.add(
BmReadRssiResult.fromMap(
call.arguments,
),
);
case 'OnScanResponse':
return _onScanResponseController.add(
BmScanResponse.fromMap(
call.arguments,
),
);
case 'OnServicesReset':
return _onServicesResetController.add(
BmBluetoothDevice.fromMap(
call.arguments,
),
);
}
}
String _prettyPrint(
dynamic data,
) {
if (data is Map || data is List) {
return const JsonEncoder.withIndent(' ').convert(data);
} else {
return data.toString();
}
}
}

@ -0,0 +1,26 @@
name: flutter_blue_plus_winrt
description: Windows implementation of the flutter_blue_plus plugin.
version: 0.0.20
homepage: https://github.com/chan150/flutter_blue_plus_winrt
environment:
sdk: ^3.0.0
flutter: '>=3.7.0'
dependencies:
flutter:
sdk: flutter
flutter_blue_plus_platform_interface: ">=9.0.0"
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints:
flutter:
plugin:
implements: flutter_blue_plus
platforms:
windows:
pluginClass: FlutterBluePlusPlugin
dartPluginClass: FlutterBluePlusWinrt

@ -0,0 +1,17 @@
flutter/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

@ -0,0 +1,73 @@
# The Flutter tooling requires that developers have a version of Visual Studio
# installed that includes CMake 3.14 or later. You should not increase this
# version, as doing so will cause the plugin to fail to compile for some
# customers of the plugin.
cmake_minimum_required(VERSION 3.14)
# Project-level configuration.
set(PROJECT_NAME "flutter_blue_plus_winrt")
project(${PROJECT_NAME} LANGUAGES CXX)
# Enable C++20 and coroutines
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# This value is used when generating builds using this plugin, so it must
# not be changed
set(PLUGIN_NAME "flutter_blue_plus_winrt_plugin")
# Any new source files that you add to the plugin should be added here.
list(APPEND PLUGIN_SOURCES
"flutter_blue_plus_winrt_plugin.cpp"
"flutter_blue_plus_winrt_plugin.h"
)
# Define the plugin library target. Its name must not be changed (see comment
# on PLUGIN_NAME above).
add_library(${PLUGIN_NAME} SHARED
"include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h"
"flutter_blue_plus_winrt_plugin_c_api.cpp"
${PLUGIN_SOURCES}
)
# Apply a standard set of build settings that are configured in the
# application-level CMakeLists.txt. This can be removed for plugins that want
# full control over build settings.
apply_standard_settings(${PLUGIN_NAME})
# Symbols are hidden by default to reduce the chance of accidental conflicts
# between plugins. This should not be removed; any symbols that should be
# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro.
set_target_properties(${PLUGIN_NAME} PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)
# Source include directories and library dependencies. Add any plugin-specific
# dependencies here.
target_include_directories(${PLUGIN_NAME} INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin runtimeobject ole32)
# List of absolute paths to libraries that should be bundled with the plugin.
# This list could contain prebuilt libraries, or libraries created by an
# external build triggered from this build file.
set(flutter_blue_plus_winrt_bundled_libraries
""
PARENT_SCOPE
)
# === Tests ===
# These unit tests can be run from a terminal after building the example, or
# from Visual Studio after opening the generated solution file.
# Only enable test builds when building the example (which sets this variable)
# so that plugin clients aren't building the tests.
# Test section disabled because test directory is missing from the package.
# if (${include_${PROJECT_NAME}_tests})
# ...
# endif()

@ -0,0 +1,223 @@
#ifndef FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_
#define FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <winrt/Windows.Devices.Bluetooth.Advertisement.h>
#include <winrt/Windows.Devices.Bluetooth.h>
#include <winrt/Windows.Devices.Bluetooth.GenericAttributeProfile.h>
#include <winrt/Windows.Foundation.h>
#include <memory>
#include <string>
#include <vector>
#include <utility>
#include <map>
#include <atomic>
#include <mutex>
namespace flutter_blue_plus_winrt {
struct SubscribedCharacteristic {
winrt::Windows::Foundation::IInspectable characteristic = nullptr;
winrt::event_token token;
};
class FlutterBluePlusWinrtPlugin : public flutter::Plugin {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar);
FlutterBluePlusWinrtPlugin(flutter::PluginRegistrarWindows* registrar);
~FlutterBluePlusWinrtPlugin();
// Disallow copy and assign.
FlutterBluePlusWinrtPlugin(const FlutterBluePlusWinrtPlugin&) = delete;
FlutterBluePlusWinrtPlugin& operator=(const FlutterBluePlusWinrtPlugin&) = delete;
private:
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
flutter::PluginRegistrarWindows* registrar_;
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> channel_;
winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher watcher_{};
winrt::event_token received_token_{};
winrt::event_token stopped_token_{};
// Shared "alive" flag. Held by a shared_ptr so that fire-and-forget
// coroutines / event handlers can capture a copy and safely check whether
// the plugin has been destroyed after resuming, instead of dereferencing a
// dangling `this`.
std::shared_ptr<std::atomic<bool>> is_alive_ = std::make_shared<std::atomic<bool>>(true);
// UI Thread context
winrt::apartment_context ui_thread_;
std::mutex devices_mutex_;
std::vector<std::pair<std::string, winrt::Windows::Foundation::IInspectable>> connected_devices_{};
std::vector<std::pair<std::string, winrt::Windows::Foundation::IInspectable>> currently_connecting_devices_{};
std::map<std::string, int32_t> rssi_cache_{};
std::map<std::string, std::map<flutter::EncodableValue, flutter::EncodableValue>> scan_results_cache_{};
// Map to store event tokens and characteristic objects for notifications
std::map<std::string, SubscribedCharacteristic> subscribed_characteristics_{};
// Guards the GATT object caches below (characteristic_cache_,
// descriptor_cache_, service_cache_, subscribed_characteristics_,
// gatt_sessions_, mtu_tokens_, connection_tokens_). These are accessed both
// from background thread-pool continuations (service discovery / read /
// write) and from the UI thread (ClearDeviceResources on disconnect), so
// every access must hold this mutex. NOTE: never hold this across a
// `co_await`.
std::mutex gatt_cache_mutex_;
// Caches for GATT objects to avoid repeated discovery
std::map<std::string, winrt::Windows::Foundation::IInspectable> characteristic_cache_{};
std::map<std::string, winrt::Windows::Foundation::IInspectable> descriptor_cache_{};
std::map<std::string, std::vector<winrt::Windows::Foundation::IInspectable>> service_cache_{};
// MTU / Session Handling
std::map<std::string, winrt::Windows::Foundation::IInspectable> gatt_sessions_{};
std::map<std::string, winrt::event_token> mtu_tokens_{};
// Per-device ConnectionStatusChanged event tokens, so the handlers can be
// revoked (in ClearDeviceResources and the destructor) and never fire into a
// destroyed plugin. Guarded by gatt_cache_mutex_.
std::map<std::string, winrt::event_token> connection_tokens_{};
void OnAdvertisementReceived(
const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher&,
const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementReceivedEventArgs&);
void OnAdvertisementStopped(
const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcher&,
const winrt::Windows::Devices::Bluetooth::Advertisement::BluetoothLEAdvertisementWatcherStoppedEventArgs&);
winrt::fire_and_forget GetSystemDevicesAsync(
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget GetAdapterStateAsync(
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget GetBondedDevicesAsync(
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget CreateBondAsync(
std::string remote_id,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget RemoveBondAsync(
std::string remote_id,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget GetBondStateAsync(
std::string remote_id,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget ConnectAsync(
std::string remote_id,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget DiscoverServicesAsync(
std::string remote_id,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget SetNotifyValueAsync(
std::shared_ptr<flutter::EncodableMap> args);
winrt::fire_and_forget ReadCharacteristicAsync(
flutter::EncodableMap args,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget WriteCharacteristicAsync(
flutter::EncodableMap args,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget ReadDescriptorAsync(
flutter::EncodableMap args,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
winrt::fire_and_forget WriteDescriptorAsync(
flutter::EncodableMap args,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
void OnConnectionStatusChanged(
const winrt::Windows::Devices::Bluetooth::BluetoothLEDevice&,
const winrt::Windows::Foundation::IInspectable&);
void OnCharacteristicValueChanged(
std::string remote_id,
const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic& sender,
const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs& args);
void OnMaxPduSizeChanged(
std::string remote_id,
const winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattSession& sender,
const winrt::Windows::Foundation::IInspectable& args);
winrt::fire_and_forget PeriodicConnectionCheck();
std::string uint64_to_mac_string(uint64_t addr);
// --- Private GATT Helpers ---
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
GetCharacteristicInternalAsync(
winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device,
std::string remote_id,
std::string service_uuid_str,
std::string characteristic_uuid_str,
std::string primary_service_uuid_str,
int instance_id);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
GetCharacteristicByHandleAsync(
winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device,
int instance_id);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
GetCharacteristicAsync(
winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device,
std::string service_uuid_str,
std::string characteristic_uuid_str,
std::string primary_service_uuid_str,
int instance_id);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
FindCharacteristicInServiceAsync(
winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service,
int instance_id,
winrt::Windows::Devices::Bluetooth::BluetoothCacheMode cacheMode);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
FindCharacteristicByDescriptorHandleInServiceAsync(
winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service,
int descriptor_handle,
winrt::Windows::Devices::Bluetooth::BluetoothCacheMode cacheMode);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic>
GetCharacteristicByDescriptorHandleAsync(
winrt::Windows::Devices::Bluetooth::BluetoothLEDevice device,
int descriptor_handle);
winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor>
GetDescriptorAsync(
winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic characteristic,
std::string descriptor_uuid_str);
winrt::Windows::Foundation::IAsyncAction PopulateCharacteristicsAsync(
winrt::Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService service,
std::string remote_id,
std::string primaryServiceUuid,
std::shared_ptr<flutter::EncodableList> outList);
void ClearDeviceResources(std::string remote_id);
};
} // namespace flutter_blue_plus_winrt
#endif // FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_H_

@ -0,0 +1,12 @@
#include "include/flutter_blue_plus_winrt/flutter_blue_plus_plugin.h"
#include <flutter/plugin_registrar_windows.h>
#include "flutter_blue_plus_winrt_plugin.h"
void FlutterBluePlusPluginRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
flutter_blue_plus_winrt::FlutterBluePlusWinrtPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));
}

@ -0,0 +1,23 @@
#ifndef FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_
#define FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_
#include <flutter_plugin_registrar.h>
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)
#else
#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
FLUTTER_PLUGIN_EXPORT void FlutterBluePlusPluginRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_PLUGIN_FLUTTER_BLUE_PLUS_WINRT_PLUGIN_C_API_H_
Loading…
Cancel
Save

Powered by TurnKey Linux.