Probe Windows BLE publisher startup before GATT advertising
This commit is contained in:
1 parent
cad831af9b
commit
df36798070
2 files changed
+75
-28
No files matched your search
@@ -310,6 +310,18 @@ Started подтверждает обслуживание публикации W
|
||||
Код выхода 0 означает завершённое сравнение, а не успешную передачу во всех трёх окнах.
|
||||
Ошибка/таймаут — 1, неправильные аргументы — 2. При завершении все объекты освобождаются.
|
||||
Утилита собирается рядом с vibechat.exe, в пользовательский установщик не включается.
|
||||
Проверка обратного порядка запуска без предварительного включения/выключения GATT:
|
||||
.\ble_advertising_probe.exe --publisher-first 60
|
||||
Сначала запускается только publisher с теми же 18 байтами probe18. В течение максимум
|
||||
20 секунд ожидаются событие Started и подтверждающий Publisher.Status. Только после
|
||||
этого создаются GATT-сервис, характеристики и scan обычным backend. Publisher продолжает
|
||||
работать без пересоздания; phase=publisher_first_gatt_on наблюдает совместную работу
|
||||
60 секунд (можно указать 10..60, по умолчанию 20). Таймаут/ошибка publisher отменяет
|
||||
создание GATT. В result publisher относится к первоначальному publisher, service/scan —
|
||||
к запущенному после него backend; generation publisher должна остаться 1.
|
||||
На другом устройстве проверить, приходит ли probe18 после запуска GATT; кешированная
|
||||
строка в списке соседей сама по себе не подтверждает продолжение приёма объявлений.
|
||||
Входящие соединения этот режим также отклоняет: их проверка остаётся отдельным шагом.
|
||||
Объяснение приоритета GATT от Microsoft:
|
||||
https://learn.microsoft.com/en-us/answers/questions/189891/windows10-uwp-app-conflict-ble-advertisement-and-g
|
||||
Для отдельных кадров, ATT-фрагментов и переходов backpressure использовать discovery=trace.
|
||||
|
||||
@@ -56,17 +56,18 @@ struct ProbeGatt {
|
||||
};
|
||||
|
||||
/* Даём ОС всё окно наблюдения, даже после Started: важен также возврат в Waiting. */
|
||||
static bool observe(WinState& s, ble_transport& owner, const ProbeGatt& gatt, const char* phase, unsigned seconds) {
|
||||
static bool observe(WinState& s, WinState& tx, ble_transport& owner, const ProbeGatt& gatt, const char* phase, unsigned seconds) {
|
||||
const auto start = get_time_us(), end = start + uint64_t(seconds) * 1000000;
|
||||
uint64_t first_started_ms = 0;
|
||||
unsigned started = 0, waiting = 0, unsettled = 0;
|
||||
WinState::RadioStatus previous;
|
||||
DEBUG_INFO(CAT, "BLE advertising probe begin phase=%s seconds=%u gatt_requested=%d generation=%llu",
|
||||
phase, seconds, gatt.requested, (unsigned long long)s.publish_generation);
|
||||
phase, seconds, gatt.requested, (unsigned long long)tx.publish_generation);
|
||||
do {
|
||||
uasync_poll(s.ua, 100);
|
||||
if (s.failed || owner.failed) { DEBUG_ERROR(CAT, "BLE advertising probe phase=%s backend failed", phase); return false; }
|
||||
if (s.failed || tx.failed || owner.failed) { DEBUG_ERROR(CAT, "BLE advertising probe phase=%s backend failed", phase); return false; }
|
||||
auto actual = s.radio_status();
|
||||
if (&tx != &s) actual.publisher = tx.radio_status().publisher;
|
||||
if (actual.publisher < 0 || actual.service < 0 || actual.scan < 0) {
|
||||
DEBUG_ERROR(CAT, "BLE advertising probe phase=%s cannot read radio state", phase); return false;
|
||||
}
|
||||
@@ -83,7 +84,7 @@ static bool observe(WinState& s, ble_transport& owner, const ProbeGatt& gatt, co
|
||||
DEBUG_INFO(CAT, "BLE advertising probe result phase=%s started_samples=%u waiting_samples=%u unsettled_samples=%u "
|
||||
"first_started_ms=%llu final_publisher=%d final_service=%d final_scan=%d generation=%llu",
|
||||
phase, started, waiting, unsettled, (unsigned long long)first_started_ms,
|
||||
previous.publisher, previous.service, previous.scan, (unsigned long long)s.publish_generation);
|
||||
previous.publisher, previous.service, previous.scan, (unsigned long long)tx.publish_generation);
|
||||
if (!gatt.matches(previous.service) || previous.scan != int(BluetoothLEAdvertisementWatcherStatus::Started)) {
|
||||
DEBUG_ERROR(CAT, "BLE advertising probe phase=%s did not reach requested GATT/scan state; comparison inconclusive", phase);
|
||||
return false;
|
||||
@@ -94,12 +95,15 @@ static bool observe(WinState& s, ble_transport& owner, const ProbeGatt& gatt, co
|
||||
int main(int argc, char** argv) {
|
||||
debug_config_init(); debug_set_level(DEBUG_LEVEL_INFO); debug_set_category_level(CAT, DEBUG_LEVEL_DEBUG);
|
||||
if (argc == 2 && !std::strcmp(argv[1], "--help")) {
|
||||
DEBUG_INFO(CAT, "Usage: ble_advertising_probe.exe [seconds_per_phase=20, range=10..60]; close VibeChat first"); return 0;
|
||||
DEBUG_INFO(CAT, "Usage: ble_advertising_probe.exe [--publisher-first] [seconds_per_phase=20, range=10..60]; close VibeChat first");
|
||||
return 0;
|
||||
}
|
||||
bool publisher_first = argc > 1 && !std::strcmp(argv[1], "--publisher-first");
|
||||
int argument = publisher_first ? 2 : 1;
|
||||
char* tail = nullptr;
|
||||
long seconds = argc == 2 ? std::strtol(argv[1], &tail, 10) : 20;
|
||||
if (argc > 2 || (tail && (tail == argv[1] || *tail)) || seconds < 10 || seconds > 60) {
|
||||
DEBUG_ERROR(CAT, "BLE advertising probe expects 10..60 seconds per phase or --help"); return 2;
|
||||
long seconds = argc > argument ? std::strtol(argv[argument], &tail, 10) : 20;
|
||||
if (argc > argument + 1 || (tail && (tail == argv[argument] || *tail)) || seconds < 10 || seconds > 60) {
|
||||
DEBUG_ERROR(CAT, "BLE advertising probe expects [--publisher-first] [10..60 seconds] or --help"); return 2;
|
||||
}
|
||||
debug_enable_file_output("ble_advertising_probe.log", 1);
|
||||
DEBUG_INFO(CAT, "BLE advertising probe: close other VibeChat/probe processes; log=ble_advertising_probe.log; "
|
||||
@@ -108,9 +112,33 @@ int main(int argc, char** argv) {
|
||||
if (!ua) { DEBUG_ERROR(CAT, "BLE advertising probe cannot create uasync"); return 1; }
|
||||
ble_transport owner;
|
||||
ble_config config{}; config.node_id = 0x5643424c45544553ULL; config.company_id = 0xffff;
|
||||
auto backend = ble_backend_create(&owner, ua, &config);
|
||||
ble_backend* backend = nullptr;
|
||||
std::shared_ptr<WinState> early;
|
||||
bool completed = false;
|
||||
try {
|
||||
if (publisher_first) {
|
||||
/* Тот же publish(), но GATT ещё даже не создан; отдельное состояние живёт до конца проверки. */
|
||||
early = std::make_shared<WinState>(); early->ua = ua; early->owner = &owner; early->company = config.company_id;
|
||||
init_apartment(apartment_type::multi_threaded); early->apartment = true;
|
||||
int size = ble_identity_encode(early->broadcast.data(), config.node_id, "probe18");
|
||||
if (size < 0) throw std::runtime_error("cannot encode manufacturer identity");
|
||||
early->broadcast_size = size; early->broadcast_enabled = true;
|
||||
DEBUG_INFO(CAT, "BLE advertising probe mode=publisher-first; starting publisher before creating GATT/scan");
|
||||
early->publish();
|
||||
auto start = get_time_us(), deadline = start + 20000000;
|
||||
while (!owner.failed && early->publisher_status != int(BluetoothLEAdvertisementPublisherStatus::Started) &&
|
||||
get_time_us() < deadline) uasync_poll(ua, 100);
|
||||
auto actual = early->radio_status();
|
||||
if (owner.failed || early->publisher_status != int(BluetoothLEAdvertisementPublisherStatus::Started) ||
|
||||
actual.publisher != int(BluetoothLEAdvertisementPublisherStatus::Started)) {
|
||||
DEBUG_ERROR(CAT, "BLE advertising probe publisher-first startup failed event=%d actual=%d; GATT was not started",
|
||||
early->publisher_status, actual.publisher);
|
||||
throw std::runtime_error("publisher did not reach Started within 20s before GATT creation");
|
||||
}
|
||||
DEBUG_INFO(CAT, "BLE advertising probe publisher-first Started elapsed_ms=%llu generation=%llu; now creating GATT/scan",
|
||||
(unsigned long long)((get_time_us() - start) / 1000), (unsigned long long)early->publish_generation);
|
||||
}
|
||||
backend = ble_backend_create(&owner, ua, &config);
|
||||
if (!backend) throw std::runtime_error("backend creation failed");
|
||||
auto& s = *backend->state;
|
||||
auto deadline = get_time_us() + 20000000;
|
||||
@@ -125,28 +153,35 @@ int main(int argc, char** argv) {
|
||||
gatt->changed(state, args.Status(), args.Error());
|
||||
});
|
||||
});
|
||||
uint8_t payload[BLE_BROADCAST_MAX];
|
||||
int size = ble_identity_encode(payload, config.node_id, "probe18");
|
||||
if (size < 0 || ble_backend_advertise(backend, payload, size) != BLE_OK)
|
||||
throw std::runtime_error("manufacturer publisher startup failed");
|
||||
if (!observe(s, owner, *gatt, "gatt_on", seconds))
|
||||
throw std::runtime_error("baseline incomplete");
|
||||
DEBUG_INFO(CAT, "BLE advertising probe stopping GATT advertisement; publisher and scan remain unchanged");
|
||||
gatt->requested = false; gatt->stop_confirmed = false;
|
||||
s.provider.StopAdvertising();
|
||||
if (!observe(s, owner, *gatt, "gatt_off", seconds))
|
||||
throw std::runtime_error("GATT-off observation incomplete");
|
||||
DEBUG_INFO(CAT, "BLE advertising probe restoring GATT advertisement connectable=1 discoverable=1");
|
||||
GattServiceProviderAdvertisingParameters parameters; parameters.IsConnectable(true); parameters.IsDiscoverable(true);
|
||||
gatt->requested = true; gatt->stop_confirmed = false;
|
||||
s.provider.StartAdvertising(parameters);
|
||||
if (!observe(s, owner, *gatt, "gatt_restored", seconds))
|
||||
throw std::runtime_error("GATT-restored observation incomplete");
|
||||
if (publisher_first) {
|
||||
if (!observe(s, *early, owner, *gatt, "publisher_first_gatt_on", seconds))
|
||||
throw std::runtime_error("publisher-first observation incomplete");
|
||||
} else {
|
||||
uint8_t payload[BLE_BROADCAST_MAX];
|
||||
int size = ble_identity_encode(payload, config.node_id, "probe18");
|
||||
if (size < 0 || ble_backend_advertise(backend, payload, size) != BLE_OK)
|
||||
throw std::runtime_error("manufacturer publisher startup failed");
|
||||
if (!observe(s, s, owner, *gatt, "gatt_on", seconds))
|
||||
throw std::runtime_error("baseline incomplete");
|
||||
DEBUG_INFO(CAT, "BLE advertising probe stopping GATT advertisement; publisher and scan remain unchanged");
|
||||
gatt->requested = false; gatt->stop_confirmed = false;
|
||||
s.provider.StopAdvertising();
|
||||
if (!observe(s, s, owner, *gatt, "gatt_off", seconds))
|
||||
throw std::runtime_error("GATT-off observation incomplete");
|
||||
DEBUG_INFO(CAT, "BLE advertising probe restoring GATT advertisement connectable=1 discoverable=1");
|
||||
GattServiceProviderAdvertisingParameters parameters; parameters.IsConnectable(true); parameters.IsDiscoverable(true);
|
||||
gatt->requested = true; gatt->stop_confirmed = false;
|
||||
s.provider.StartAdvertising(parameters);
|
||||
if (!observe(s, s, owner, *gatt, "gatt_restored", seconds))
|
||||
throw std::runtime_error("GATT-restored observation incomplete");
|
||||
}
|
||||
completed = true;
|
||||
DEBUG_INFO(CAT, "BLE advertising probe comparison complete; inspect the three phase results. "
|
||||
"Started confirms Windows scheduling, not reception by another device");
|
||||
DEBUG_INFO(CAT, "BLE advertising probe complete mode=%s; inspect phase results. "
|
||||
"Started confirms Windows scheduling, not reception or incoming connections",
|
||||
publisher_first ? "publisher-first" : "gatt-on-off-restored");
|
||||
} catch (...) { DEBUG_ERROR(CAT, "%s", exception_reason("advertising probe").c_str()); }
|
||||
if (backend) ble_backend_destroy(backend);
|
||||
if (early) early->shutdown();
|
||||
uasync_destroy(ua, 0); debug_disable_file_output();
|
||||
return completed ? 0 : 1;
|
||||
}
|
||||
Reference in new issue
Block a user