Support WinRT BLE discovery and connection on Windows 1809

This commit is contained in:
evgeny committed 2026-10-30 10:30:22 +01:00
1 parent 123f6a6c62
commit 99834cede0
2 files changed
+100 -22

No files matched your search

+42 -20
View File
@@ -97,6 +97,7 @@ struct WinState : std::enable_shared_from_this<WinState> {
ble_link_id operation_link = 0;
struct posted_task* posted = nullptr;
bool stopped = false, failed = false, overflow = false, apartment = false, scan_ready = false, service_ready = false;
int received_address_type_api = -1; /* -1: ещё не было объявления; 0/1: фактический интерфейс EventArgs2. */
IAsyncInfo startup{nullptr};
BluetoothLEAdvertisementWatcher watcher{nullptr};
BluetoothLEAdvertisementPublisher publisher{nullptr};
@@ -205,6 +206,22 @@ struct WinState : std::enable_shared_from_this<WinState> {
if (buffer.Length() > BLE_VALUE_MAX) throw hresult_invalid_argument();
std::vector<uint8_t> result(buffer.Length()); DataReader::FromBuffer(buffer).ReadBytes(result); return result;
}
/* До Windows 2004 тип адреса известен только системному кешу, заполненному watcher. */
ble_endpoint advertisement_endpoint(BluetoothLEAdvertisementReceivedEventArgs const& args) {
step("Received.QueryInterface(IBluetoothLEAdvertisementReceivedEventArgs2)");
auto address_api = args.try_as<IBluetoothLEAdvertisementReceivedEventArgs2>();
if (received_address_type_api != int(bool(address_api))) {
received_address_type_api = bool(address_api);
DEBUG_INFO(CAT, "BLE WinRT discovery address_type_api=%d; %s", received_address_type_api,
address_api ? "using advertised address type" : "using watcher cache (address type unspecified)");
}
auto type = BluetoothAddressType::Unspecified;
if (address_api) { step("Received.BluetoothAddressType"); type = address_api.BluetoothAddressType(); }
step("Received.BluetoothAddress"); auto address = args.BluetoothAddress();
ble_endpoint ep{};
std::snprintf(ep.id, sizeof(ep.id), "%012llx/%d", (unsigned long long)address, (int)type);
return ep;
}
void ready() {
DEBUG_DEBUG(CAT, "BLE WinRT readiness scan=%d service=%d", scan_ready, service_ready);
if (scan_ready && service_ready) ble_backend_status(owner, 1, "WinRT scan/GATT ready");
@@ -453,15 +470,7 @@ struct WinState : std::enable_shared_from_this<WinState> {
s.step("Received.Advertisement.ManufacturerData");
for (auto const& value : args.Advertisement().ManufacturerData()) {
if (value.CompanyId() != s.company || value.Data().Length() > BLE_BROADCAST_MAX) continue;
struct ble_endpoint ep{};
s.step("Received.QueryInterface(IBluetoothLEAdvertisementReceivedEventArgs2)");
auto address_api = args.try_as<IBluetoothLEAdvertisementReceivedEventArgs2>();
if (!address_api) {
s.fail("Received: IBluetoothLEAdvertisementReceivedEventArgs2 unavailable; Windows 10 2004+ required"); return;
}
s.step("Received.BluetoothAddressType"); auto type = address_api.BluetoothAddressType();
s.step("Received.BluetoothAddress"); auto address = args.BluetoothAddress();
std::snprintf(ep.id, sizeof(ep.id), "%012llx/%d", (unsigned long long)address, (int)type);
auto ep = s.advertisement_endpoint(args);
s.step("Received manufacturer buffer/DataReader");
auto data = bytes(value.Data());
s.step("Received.RawSignalStrengthInDBm"); auto rssi = args.RawSignalStrengthInDBm();
@@ -525,10 +534,21 @@ struct WinState : std::enable_shared_from_this<WinState> {
step("Publisher.Start"); publisher.Start();
}
void connect(ble_link_id id, uint64_t address, BluetoothAddressType type) {
DEBUG_DEBUG(CAT, "BLE WinRT connect link=%llu address=%012llx type=%d", (unsigned long long)id, (unsigned long long)address, (int)type);
await("open BLE device", BluetoothLEDevice::FromBluetoothAddressAsync(address, type), id, [id](WinState& s, BluetoothLEDevice const& device) {
bool cached = type == BluetoothAddressType::Unspecified;
const char* phase = cached ? "BluetoothLEDevice.FromBluetoothAddressAsync(address)" :
"BluetoothLEDevice.FromBluetoothAddressAsync(address,type)";
DEBUG_INFO(CAT, "BLE WinRT connect link=%llu address=%012llx type=%d resolution=%s",
(unsigned long long)id, (unsigned long long)address, (int)type, cached ? "watcher-cache" : "explicit-type");
step(phase, id);
auto opening = cached ? BluetoothLEDevice::FromBluetoothAddressAsync(address) : BluetoothLEDevice::FromBluetoothAddressAsync(address, type);
await(phase, opening, id, [id](WinState& s, BluetoothLEDevice const& device) {
auto* l = s.link(id);
if (!device) { s.error(id, "BLE device unavailable"); return; }
if (!device) {
DEBUG_WARN(CAT, "BLE WinRT device lookup returned null link=%llu endpoint=%s; Windows found no paired/cached device",
(unsigned long long)id, l->endpoint.c_str());
s.error(id, "BLE device unavailable in Windows pairing/cache; rescan the peer"); return;
}
s.step("BluetoothLEDevice.BluetoothDeviceId/ConnectionStatus", id);
l->device = device; l->device_id = device.BluetoothDeviceId().Id();
DEBUG_DEBUG(CAT, "BLE WinRT device link=%llu endpoint=%s status=%d", (unsigned long long)id,
to_string(l->device_id).c_str(), (int)device.ConnectionStatus());
@@ -665,16 +685,18 @@ extern "C" struct ble_backend* ble_backend_create(struct ble_transport* owner, s
try {
DEBUG_DEBUG(CAT, "BLE WinRT initialize company=%04x node=%016llx apartment=MTA", cfg->company_id, (unsigned long long)cfg->node_id);
init_apartment(apartment_type::multi_threaded); state->apartment = true;
try {
auto version = Windows::System::Profile::AnalyticsInfo::VersionInfo();
auto raw = to_string(version.DeviceFamilyVersion());
auto number = std::stoull(raw);
DEBUG_INFO(CAT, "BLE WinRT OS family=%s version=%llu.%llu.%llu.%llu DeviceFamilyVersion=%s",
to_string(version.DeviceFamily()).c_str(), (number >> 48) & 0xffff, (number >> 32) & 0xffff,
(number >> 16) & 0xffff, number & 0xffff, raw.c_str());
} catch (...) { DEBUG_WARN(CAT, "%s", exception_reason("OS version diagnostics").c_str()); }
state->step("ApiInformation.IsPropertyPresent(BluetoothAddressType)");
bool address_type = Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent(
L"Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs", L"BluetoothAddressType");
DEBUG_INFO(CAT, "BLE WinRT API BluetoothAddressType=%d required=Windows10-2004 wire=3 channels=DATA/INVITE/ACK", address_type);
if (!address_type) throw hresult_error(E_NOINTERFACE, L"BLE requires BluetoothAddressType (Windows 10 2004 / build 19041 or newer)");
try {
auto version = Windows::System::Profile::AnalyticsInfo::VersionInfo();
DEBUG_INFO(CAT, "BLE WinRT OS family=%s version=%s", to_string(version.DeviceFamily()).c_str(),
to_string(version.DeviceFamilyVersion()).c_str());
} catch (...) { DEBUG_WARN(CAT, "%s", exception_reason("OS version diagnostics").c_str()); }
DEBUG_INFO(CAT, "BLE WinRT API BluetoothAddressType=%d optional=1 fallback=watcher-cache wire=3 channels=DATA/INVITE/ACK", address_type);
state->await("get default adapter", BluetoothAdapter::GetDefaultAsync(), 0, [](WinState& s, BluetoothAdapter const& adapter) {
if (!adapter) { s.fail("no default Bluetooth adapter"); return; }
DEBUG_DEBUG(CAT, "BLE WinRT adapter id=%s address=%012llx BLE=%d central=%d peripheral=%d", to_string(adapter.DeviceId()).c_str(),
@@ -717,7 +739,7 @@ extern "C" int ble_backend_connect(struct ble_backend* b, ble_link_id id, const
try {
auto& s = *b->state; auto l = std::make_unique<WinLink>(); l->id = id; l->endpoint = ep->id; l->outgoing = true;
s.links.emplace(id, std::move(l)); s.connect(id, address, static_cast<BluetoothAddressType>(type)); return BLE_OK;
} catch (...) { DEBUG_ERROR(CAT, "%s", exception_reason("connect", id).c_str()); b->state->close(id); return BLE_ERROR; }
} catch (...) { DEBUG_ERROR(CAT, "%s", exception_reason(b->state->operation, id).c_str()); b->state->close(id); return BLE_ERROR; }
}
extern "C" void ble_backend_close(struct ble_backend* b, ble_link_id id) { b->state->close(id); }
extern "C" int ble_backend_send(struct ble_backend* b, ble_link_id id, enum ble_wire_channel channel, const uint8_t* data, size_t len) {
+58 -2
View File
@@ -1,4 +1,4 @@
/* Настоящий WinRT mailbox без радио: исключения, изоляция link и отмена поздних callbacks.
/* WinRT без радио: старые/новые интерфейсы объявления, mailbox, изоляция link и отмена callbacks.
* Включаем backend для доступа к внутренним событиям; общий transport заменён наблюдателем. */
#include "../ble_winrt.cpp"
#include <cstdlib>
@@ -34,6 +34,62 @@ static std::shared_ptr<WinState> make_state(UASYNC* ua, ble_transport& owner) {
return s;
}
using AddressType = Windows::Devices::Bluetooth::BluetoothAddressType;
/* Настоящий QueryInterface: объект 1809 не реализует EventArgs2, объект 2004 реализует. */
template<typename... Extra>
struct TestReceivedArgs : implements<TestReceivedArgs<Extra...>, IBluetoothLEAdvertisementReceivedEventArgs, Extra...> {
uint64_t address = 0;
AddressType type = AddressType::Unspecified;
uint64_t BluetoothAddress() { return address; }
AddressType BluetoothAddressType() { return type; }
int16_t RawSignalStrengthInDBm() { CHECK(false); return 0; }
BluetoothLEAdvertisementType AdvertisementType() { CHECK(false); return BluetoothLEAdvertisementType::ConnectableUndirected; }
DateTime Timestamp() { CHECK(false); return {}; }
BluetoothLEAdvertisement Advertisement() { CHECK(false); return nullptr; }
IReference<int16_t> TransmitPowerLevelInDBm() { CHECK(false); return nullptr; }
bool IsAnonymous() { CHECK(false); return false; }
bool IsConnectable() { CHECK(false); return false; }
bool IsScannable() { CHECK(false); return false; }
bool IsDirected() { CHECK(false); return false; }
bool IsScanResponse() { CHECK(false); return false; }
};
/* Отсутствие свойства не ломает radio и не подменяет неизвестный тип на public/random. */
static void advertisement_addresses(UASYNC* ua) {
ble_transport owner;
auto s = make_state(ua, owner);
auto legacy = make_self<TestReceivedArgs<>>();
legacy->address = 0xc123456789ab;
auto args = legacy.as<BluetoothLEAdvertisementReceivedEventArgs>();
CHECK(!args.try_as<IBluetoothLEAdvertisementReceivedEventArgs2>());
unsigned processed = 0;
s->post("Watcher.Received", 0, [args, &processed](WinState& state) {
auto ep = state.advertisement_endpoint(args);
CHECK(std::string(ep.id) == "c123456789ab/2"); ++processed;
});
/* Ведущие нули сохраняются; высокий бит адреса не используется для угадывания типа. */
auto leading_zero = make_self<TestReceivedArgs<>>(); leading_zero->address = 0x12345678;
args = leading_zero.as<BluetoothLEAdvertisementReceivedEventArgs>();
s->post("Watcher.Received", 0, [args, &processed](WinState& state) {
auto ep = state.advertisement_endpoint(args);
CHECK(std::string(ep.id) == "000012345678/2"); ++processed;
});
for (auto type : {AddressType::Public, AddressType::Random, AddressType::Unspecified}) {
auto modern = make_self<TestReceivedArgs<IBluetoothLEAdvertisementReceivedEventArgs2>>();
modern->address = legacy->address; modern->type = type;
args = modern.as<BluetoothLEAdvertisementReceivedEventArgs>();
s->post("Watcher.Received", 0, [args, type, &processed](WinState& state) {
auto ep = state.advertisement_endpoint(args);
CHECK(std::string(ep.id) == "c123456789ab/" + std::to_string(int(type))); ++processed;
});
}
uasync_poll(ua, 0);
CHECK(processed == 5 && !s->failed && owner.radio_failures == 0 && owner.link_failures == 0);
CHECK(s->link(7) && s->link(9));
s->shutdown();
DEBUG_INFO(CAT, "WinRT test PASS: 1809 events use unspecified type; 2004 events preserve public/random/unspecified");
}
/* Ошибка GATT одного пира не переводит radio в failed и не теряет событие другого пира. */
static void link_exception(UASYNC* ua) {
ble_transport owner;
@@ -92,7 +148,7 @@ int main() {
debug_config_init(); debug_set_level(DEBUG_LEVEL_INFO);
init_apartment(apartment_type::multi_threaded);
UASYNC* ua = uasync_create(); CHECK(ua);
link_exception(ua); radio_exception(ua); pending_shutdown(ua);
advertisement_addresses(ua); link_exception(ua); radio_exception(ua); pending_shutdown(ua);
uasync_destroy(ua, 0); uninit_apartment();
return 0;
}