diff --git a/lib/ble/ble_winrt.cpp b/lib/ble/ble_winrt.cpp index d93656ba5..406ea12dc 100644 --- a/lib/ble/ble_winrt.cpp +++ b/lib/ble/ble_winrt.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -99,6 +100,13 @@ struct WinState : std::enable_shared_from_this { 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. */ + /* Windows callbacks считают все события, включая отсеянные до mailbox. Остальные поля — только uasync. */ + std::atomic scan_events{0}, scan_no_manufacturer{0}, scan_other_company{0}, scan_matching{0}; + uint64_t scan_forwarded = 0, scan_oversized = 0; + void* diagnostics_timer = nullptr; + int publisher_status = -1; /* Последний StatusChanged; -1: publisher ещё не создан. */ + uint64_t publisher_wait_since = 0; + bool publisher_wait_warned = false; IAsyncInfo startup{nullptr}; BluetoothLEAdvertisementWatcher watcher{nullptr}; BluetoothLEAdvertisementPublisher publisher{nullptr}; @@ -120,6 +128,29 @@ struct WinState : std::enable_shared_from_this { operation = name; operation_link = id; DEBUG_TRACE(CAT, "BLE WinRT operation=%s link=%llu", name, (unsigned long long)id); } + void discovery_stats(const char* phase) { + auto wait_ms = publisher_wait_since ? (get_time_us() - publisher_wait_since) / 1000 : 0; + DEBUG_DEBUG(CAT, "BLE WinRT scan totals phase=%s scan_ready=%d service_ready=%d failed=%d company=%04x " + "events=%llu no_manufacturer=%llu other_company=%llu matching_events=%llu forwarded_fields=%llu oversized_fields=%llu " + "publisher_state=%d waiting_ms=%llu", + phase, scan_ready, service_ready, failed, company, (unsigned long long)scan_events.load(), + (unsigned long long)scan_no_manufacturer.load(), (unsigned long long)scan_other_company.load(), + (unsigned long long)scan_matching.load(), (unsigned long long)scan_forwarded, + (unsigned long long)scan_oversized, publisher_status, (unsigned long long)wait_ms); + if (wait_ms >= 10000 && !publisher_wait_warned) { + publisher_wait_warned = true; + DEBUG_WARN(CAT, "BLE WinRT publisher still waiting for radio resources elapsed_ms=%llu generation=%llu " + "scan_ready=%d service_ready=%d; manufacturer advertisement has not started", + (unsigned long long)wait_ms, (unsigned long long)publish_generation, scan_ready, service_ready); + } + } + static void diagnostics_tick(void* arg) { + auto& s = *static_cast(arg); s.diagnostics_timer = nullptr; + s.discovery_stats("periodic"); + if (s.stopped) return; + s.diagnostics_timer = uasync_set_timeout(s.ua, 10000, &s, diagnostics_tick, "ble_winrt_diagnostics"); + if (!s.diagnostics_timer) DEBUG_WARN(CAT, "BLE WinRT diagnostics timer allocation failed; periodic summaries unavailable"); + } static void dispatch(void* arg) { auto& s = *static_cast(arg); std::deque batch; @@ -458,10 +489,14 @@ struct WinState : std::enable_shared_from_this { step("Watcher.Received registration (auto_revoke)"); received = watcher.Received(auto_revoke, [weak](auto const&, BluetoothLEAdvertisementReceivedEventArgs const& args) { auto state = weak.lock(); if (!state) return; + ++state->scan_events; try { + auto fields = args.Advertisement().ManufacturerData(); + if (!fields.Size()) { ++state->scan_no_manufacturer; return; } bool matching = false; - for (auto const& value : args.Advertisement().ManufacturerData()) if (value.CompanyId() == state->company) matching = true; - if (!matching) return; + for (auto const& value : fields) if (value.CompanyId() == state->company) matching = true; + if (!matching) { ++state->scan_other_company; return; } + ++state->scan_matching; } catch (...) { auto reason = exception_reason("Received manufacturer filter"); state->post("Watcher.Received filter failure", 0, [reason](WinState& s) { s.fail(reason.c_str()); }); @@ -470,14 +505,24 @@ struct WinState : std::enable_shared_from_this { state->post("Watcher.Received", 0, [args](WinState& s) { s.step("Received.Advertisement.ManufacturerData"); for (auto const& value : args.Advertisement().ManufacturerData()) { - if (value.CompanyId() != s.company || value.Data().Length() > BLE_BROADCAST_MAX) continue; + if (value.CompanyId() != s.company) continue; auto ep = s.advertisement_endpoint(args); + s.step("Received.RawSignalStrengthInDBm"); auto rssi = args.RawSignalStrengthInDBm(); + s.step("Received manufacturer length"); auto length = value.Data().Length(); + if (length > BLE_BROADCAST_MAX) { + ++s.scan_oversized; + if (s.scan_oversized <= 3) + DEBUG_WARN(CAT, "BLE WinRT broadcast rejected endpoint=%s rssi=%d company=%04x bytes=%u max=%u reason=oversized", + ep.id, rssi, s.company, length, BLE_BROADCAST_MAX); + else DEBUG_TRACE(CAT, "BLE WinRT broadcast rejected endpoint=%s rssi=%d bytes=%u reason=oversized", ep.id, rssi, length); + continue; + } s.step("Received manufacturer buffer/DataReader"); auto data = bytes(value.Data()); - s.step("Received.RawSignalStrengthInDBm"); auto rssi = args.RawSignalStrengthInDBm(); DEBUG_TRACE(CAT, "BLE WinRT broadcast endpoint=%s company=%04x bytes=%zu rssi=%d", ep.id, s.company, data.size(), rssi); s.step("ble_backend_broadcast"); + ++s.scan_forwarded; ble_backend_broadcast(s.owner, &ep, data.data(), data.size(), rssi); } }); @@ -490,7 +535,7 @@ struct WinState : std::enable_shared_from_this { }); step("Watcher.Start"); watcher.Start(); DEBUG_DEBUG(CAT, "BLE WinRT scan requested mode=active status=%d company=%04x", (int)watcher.Status(), company); - scan_ready = true; ready(); + scan_ready = true; diagnostics_tick(this); ready(); } void publish() { step("Publisher.Status"); @@ -503,12 +548,14 @@ struct WinState : std::enable_shared_from_this { } if (status == BluetoothLEAdvertisementPublisherStatus::Stopping) return; publish_changed.revoke(); publisher = nullptr; + publisher_status = -1; publisher_wait_since = 0; publisher_wait_warned = false; } if (!broadcast_enabled) return; step("Publisher construction/manufacturer data"); BluetoothLEAdvertisement advertisement; BluetoothLEManufacturerData data; data.CompanyId(company); data.Data(buffer(broadcast.data(), broadcast_size)); advertisement.ManufacturerData().Append(data); publisher = BluetoothLEAdvertisementPublisher(advertisement); + publisher_status = int(BluetoothLEAdvertisementPublisherStatus::Created); auto weak = weak_from_this(); auto generation = ++publish_generation; step("Publisher.StatusChanged registration (auto_revoke)"); publish_changed = publisher.StatusChanged(auto_revoke, [weak, generation](auto const&, auto const& args) { @@ -519,6 +566,16 @@ struct WinState : std::enable_shared_from_this { return; } auto status = args.Status(); auto error = args.Error(); + s.publisher_status = int(status); + if (status == BluetoothLEAdvertisementPublisherStatus::Waiting) { + if (!s.publisher_wait_since) s.publisher_wait_since = get_time_us(); + } else { + if (s.publisher_wait_since) + DEBUG_INFO(CAT, "BLE WinRT publisher left Waiting elapsed_ms=%llu state=%d generation=%llu", + (unsigned long long)((get_time_us() - s.publisher_wait_since) / 1000), (int)status, + (unsigned long long)generation); + s.publisher_wait_since = 0; s.publisher_wait_warned = false; + } DEBUG_DEBUG(CAT, "BLE WinRT broadcast state=%d error=%d (%s) generation=%llu", (int)status, (int)error, bluetooth_error(error), (unsigned long long)generation); if (status == BluetoothLEAdvertisementPublisherStatus::Aborted) s.radio_error("broadcast publication aborted", error); @@ -664,9 +721,11 @@ struct WinState : std::enable_shared_from_this { std::deque discarded; { std::lock_guard guard(mutex); stopped = true; task = posted; posted = nullptr; discarded.swap(events); } DEBUG_DEBUG(CAT, "BLE WinRT shutdown links=%zu discarded_events=%zu pending_dispatch=%d", links.size(), discarded.size(), task != nullptr); + if (diagnostics_timer) { uasync_cancel_timeout(ua, diagnostics_timer); diagnostics_timer = nullptr; } discarded.clear(); if (task) uasync_cancel_post(ua, task); received.revoke(); scan_stopped.revoke(); publish_changed.revoke(); service_changed.revoke(); + discovery_stats("shutdown"); write_requested.revoke(); subscriptions_changed.revoke(); invite_write_requested.revoke(); invite_subscriptions_changed.revoke(); ack_write_requested.revoke(); ack_subscriptions_changed.revoke(); while (!links.empty()) close(links.begin()->first); diff --git a/lib/ble/tests/test_ble_winrt.cpp b/lib/ble/tests/test_ble_winrt.cpp index 3df9e2097..322723f88 100644 --- a/lib/ble/tests/test_ble_winrt.cpp +++ b/lib/ble/tests/test_ble_winrt.cpp @@ -130,18 +130,23 @@ static void radio_exception(UASYNC* ua) { static void pending_shutdown(UASYNC* ua) { ble_transport owner; auto s = make_state(ua, owner); + /* Таймер проходит реальный callback, перевзводится и затем отменяется вместе с mailbox. */ + s->diagnostics_timer = uasync_set_timeout(ua, 0, s.get(), WinState::diagnostics_tick, "test_diagnostics"); + CHECK(s->diagnostics_timer); + uasync_poll(ua, 0); + CHECK(s->diagnostics_timer); auto payload = std::make_shared(0); std::weak_ptr weak_payload = payload; bool processed = false; s->post("test.pending", 9, [payload, &processed](WinState&) { processed = true; }); payload.reset(); CHECK(!weak_payload.expired()); - s->shutdown(); CHECK(weak_payload.expired()); + s->shutdown(); CHECK(weak_payload.expired() && !s->diagnostics_timer); s->post("test.late", 9, [&processed](WinState&) { processed = true; }); CHECK(s->events.empty() && !s->posted); std::weak_ptr weak = s; s.reset(); uasync_poll(ua, 0); CHECK(weak.expired() && !processed && owner.radio_failures == 0 && owner.link_failures == 0); - DEBUG_INFO(CAT, "WinRT test PASS: shutdown cancels queued work and rejects late callbacks"); + DEBUG_INFO(CAT, "WinRT test PASS: shutdown cancels diagnostics timer/queued work and rejects late callbacks"); } int main() {