From feb52e09ec91c14933dc03988ac4470d3223e5b5 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 01:07:35 +0000 Subject: [PATCH 01/30] shared-module/mdns: add a portable DNS-SD browser Adds a socketpool-based DNS-SD (RFC 6762/6763) browser in shared-module so ports with an IP stack but no native mDNS library can implement `mdns.Server` without a per-port responder. Selected with CIRCUITPY_MDNS_SHARED=1, which filters common-hal/mdns out of the build and compiles the shared-module sources in its place; shared-bindings/mdns/*.h pick the matching struct definitions. This is a browser only. `find()` works; `advertise_service()` raises NotImplementedError, except on the web-workflow path where it stays silent so the supervisor's own call is not a hard error. The supervisor path also must not raise or allocate: `mdns_server_find()` wraps the call in nlr_push(), and the receive buffer is static rather than GC-allocated. Browser.c is a separate translation unit from Server.c on purpose. A port that already has a native responder but no browser can add Browser.c alone to its sources and call shared_module_mdns_find() from its own common-hal find(), without dragging in a second set of common_hal_mdns_server_* definitions. Parsing details worth noting: PTR matches check both the service-type and protocol labels, SRV matches validate the whole owner name so two services on one host cannot overwrite each other, A records are ignored for entries with no hostname yet, and entries still missing a port get a follow-up SRV query at the halfway point of the timeout for responders that do not send the full set unprompted. The receive loop yields with mp_hal_delay_ms(1) when no packet is pending instead of spinning. Built and verified for raspberrypi (Pico W) both ways: with CIRCUITPY_MDNS_SHARED=1 and with the port's existing common-hal/mdns, the latter producing no shared-module/mdns objects and no size change. zephyr-cp emits the flag from its builder when the port has no common-hal/mdns of its own; that path is not yet exercised on hardware. Co-Authored-By: Claude Opus 5 --- .../zephyr-cp/cptools/build_circuitpython.py | 8 + py/circuitpy_defns.mk | 23 + py/circuitpy_mpconfig.mk | 15 + shared-bindings/mdns/RemoteService.h | 4 + shared-bindings/mdns/Server.c | 5 +- shared-bindings/mdns/Server.h | 4 + shared-module/mdns/Browser.c | 476 ++++++++++++++++++ shared-module/mdns/Browser.h | 37 ++ shared-module/mdns/RemoteService.c | 41 ++ shared-module/mdns/RemoteService.h | 25 + shared-module/mdns/Server.c | 142 ++++++ shared-module/mdns/Server.h | 29 ++ shared-module/mdns/__init__.c | 7 + 13 files changed, 815 insertions(+), 1 deletion(-) create mode 100644 shared-module/mdns/Browser.c create mode 100644 shared-module/mdns/Browser.h create mode 100644 shared-module/mdns/RemoteService.c create mode 100644 shared-module/mdns/RemoteService.h create mode 100644 shared-module/mdns/Server.c create mode 100644 shared-module/mdns/Server.h create mode 100644 shared-module/mdns/__init__.c diff --git a/ports/zephyr-cp/cptools/build_circuitpython.py b/ports/zephyr-cp/cptools/build_circuitpython.py index 87a97939062..45f46fdbe93 100644 --- a/ports/zephyr-cp/cptools/build_circuitpython.py +++ b/ports/zephyr-cp/cptools/build_circuitpython.py @@ -439,6 +439,14 @@ async def build_circuitpython(): # noqa: C901 translation = os.environ.get("TRANSLATION") or cmake_args["TRANSLATION"] or "en_US" for module in ALWAYS_ON_MODULES: circuitpython_flags.append(f"-DCIRCUITPY_{module.upper()}=1") + # mdns has two implementations: a port's native responder in common-hal, or + # the portable browser in shared-module. The source selection below already + # falls back to shared-module when a port has no common-hal for a module, + # but shared-bindings/mdns/*.h also need to know which struct to include, + # and that is a compile-time decision. Keep the two in step. + zephyr_common_hal = pathlib.Path(__file__).resolve().parents[1] / "common-hal" + if not (zephyr_common_hal / "mdns").is_dir(): + circuitpython_flags.append("-DCIRCUITPY_MDNS_SHARED=1") lto = cmake_args.get("LTO", "n") == "y" # LVGL module enabled for this board. The flag comes from CONFIG_LVGL via # ExternalProject args so it stays in sync with the Kconfig choice. Any board that diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index e92e8722b4c..04bf172c795 100755 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -659,6 +659,12 @@ SRC_COMMON_HAL_ALL = \ wifi/ScannedNetworks.c \ wifi/__init__.c \ +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +# The portable browser replaces the port's common-hal/mdns entirely; the +# shared-module sources are added to SRC_SHARED_MODULE_ALL below. +SRC_COMMON_HAL_ALL := $(filter-out mdns/%, $(SRC_COMMON_HAL_ALL)) +endif + SRC_COMMON_HAL = $(filter $(SRC_PATTERNS), $(SRC_COMMON_HAL_ALL)) ifeq ($(CIRCUITPY_BLEIO_HCI),1) @@ -980,6 +986,23 @@ $(filter $(SRC_PATTERNS), \ endif # All possible sources are listed here, and are filtered by SRC_PATTERNS. +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +SRC_SHARED_MODULE_ALL += \ + mdns/__init__.c \ + mdns/Server.c \ + mdns/RemoteService.c +# Browser.c has no shared-bindings counterpart, so it belongs in the INTERNAL +# list rather than SRC_SHARED_MODULE_ALL, which is prefixed with both paths. +SRC_SHARED_MODULE_INTERNAL += \ + mdns/Browser.c +endif + +# A port with a native mDNS responder but no browser can get find() alone by +# adding shared-module/mdns/Browser.c to its own sources and calling +# shared_module_mdns_find() from its common-hal find(). Browser.c is a separate +# translation unit precisely so that does not also pull in Server.c's +# common_hal_mdns_server_* definitions. + SRC_SHARED_MODULE = $(filter $(SRC_PATTERNS), $(SRC_SHARED_MODULE_ALL)) SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 7c6fb206e05..a542dc864a7 100755 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -495,6 +495,14 @@ CFLAGS += -DCIRCUITPY_MAX3421E=$(CIRCUITPY_MAX3421E) CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI) CFLAGS += -DCIRCUITPY_MDNS=$(CIRCUITPY_MDNS) +# Use the portable DNS-SD browser in shared-module/mdns instead of a per-port +# common-hal/mdns. It needs only socketpool, so it suits ports with an IP stack +# but no native mDNS library. It is a browser only: advertise_service() raises +# NotImplementedError. Ports with a native implementation leave this at 0. +CIRCUITPY_MDNS_SHARED ?= 0 +CFLAGS += -DCIRCUITPY_MDNS_SHARED=$(CIRCUITPY_MDNS_SHARED) +# The socketpool dependency is checked below, where CIRCUITPY_SOCKETPOOL is set. + CIRCUITPY_MEMORYMAP ?= 0 CFLAGS += -DCIRCUITPY_MEMORYMAP=$(CIRCUITPY_MEMORYMAP) @@ -653,6 +661,13 @@ CFLAGS += -DCIRCUITPY_SKIP_SAFE_MODE_WAIT=$(CIRCUITPY_SKIP_SAFE_MODE_WAIT) CIRCUITPY_SOCKETPOOL ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_SOCKETPOOL=$(CIRCUITPY_SOCKETPOOL) +# The shared-module mDNS browser is built on socketpool. +ifeq ($(CIRCUITPY_MDNS_SHARED),1) +ifneq ($(CIRCUITPY_SOCKETPOOL),1) +$(error CIRCUITPY_MDNS_SHARED requires CIRCUITPY_SOCKETPOOL) +endif +endif + CIRCUITPY_SPITARGET ?= 0 CFLAGS += -DCIRCUITPY_SPITARGET=$(CIRCUITPY_SPITARGET) diff --git a/shared-bindings/mdns/RemoteService.h b/shared-bindings/mdns/RemoteService.h index c7efa64083d..c39831c076b 100644 --- a/shared-bindings/mdns/RemoteService.h +++ b/shared-bindings/mdns/RemoteService.h @@ -9,7 +9,11 @@ #pragma once #include "py/obj.h" +#if CIRCUITPY_MDNS_SHARED +#include "shared-module/mdns/RemoteService.h" +#else #include "common-hal/mdns/RemoteService.h" +#endif extern const mp_obj_type_t mdns_remoteservice_type; diff --git a/shared-bindings/mdns/Server.c b/shared-bindings/mdns/Server.c index 1c16348d425..4d56b9c30b1 100644 --- a/shared-bindings/mdns/Server.c +++ b/shared-bindings/mdns/Server.c @@ -166,7 +166,10 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(mdns_server_find_obj, 1, _mdns_server_find); //| If web workflow is active, the port it uses can't also be used to advertise a service. //| //| **Limitations**: Publishing TXT records (up to 32) is supported only on RP2xxx. -//| There is currently no TXT record support on Espressif boards. +//| There is currently no TXT record support on Espressif boards. On boards that +//| use the portable DNS-SD browser rather than a native mDNS responder, this +//| raises `NotImplementedError`: those boards can discover services but not +//| advertise them. //| //| :param str service_type: The service type such as "_http" //| :param str protocol: The service protocol such as "_tcp" diff --git a/shared-bindings/mdns/Server.h b/shared-bindings/mdns/Server.h index df4b6f438db..ba456a8b099 100644 --- a/shared-bindings/mdns/Server.h +++ b/shared-bindings/mdns/Server.h @@ -8,7 +8,11 @@ #include +#if CIRCUITPY_MDNS_SHARED +#include "shared-module/mdns/Server.h" +#else #include "common-hal/mdns/Server.h" +#endif #include "shared-bindings/mdns/RemoteService.h" diff --git a/shared-module/mdns/Browser.c b/shared-module/mdns/Browser.c new file mode 100644 index 00000000000..4d0f08e2fec --- /dev/null +++ b/shared-module/mdns/Browser.c @@ -0,0 +1,476 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes out from an ephemeral port with the unicast-response (QU) bit +// set, so responders reply directly to us and we never have to join the +// 224.0.0.251 multicast group. That matters because socketpool exposes +// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is +// not portable today. The cost is that responses a responder chooses to +// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered +// recently) are missed; a repeat find() generally picks them up. + + +// The portable DNS-SD browser. +// +// Deliberately its own translation unit, separate from the common_hal_* entry +// points in Server.c. A port that has a native mDNS *responder* but no browser +// (zephyr-cp, say) can keep its own common-hal/mdns and compile just this file +// to get find(); linking Server.c instead would drag in a second definition of +// every common_hal_mdns_server_* symbol. + +#include "shared-module/mdns/Browser.h" + +#include +#include + +#include "py/runtime.h" +#include "py/mphal.h" + +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/mdns/RemoteService.h" +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/socketpool/SocketPool.h" +#include "supervisor/shared/tick.h" + +#define MDNS_MULTICAST_IPV4 "224.0.0.251" +#define MDNS_PORT (5353) + +#define DNS_RRTYPE_A (1) +#define DNS_RRTYPE_PTR (12) +#define DNS_RRTYPE_SRV (33) + +#define DNS_RRCLASS_IN (1) +// Top bit of QCLASS in a question asks for a unicast reply; in a resource +// record the same bit is the cache-flush flag. Mask it off before comparing. +#define DNS_CLASS_UNICAST_RESPONSE (0x8000) +#define DNS_CLASS_MASK (0x7fff) + +#define DNS_HEADER_LEN (12) +// mDNS responses may be larger, but a single DNS-SD service rarely needs more +// and anything truncated is simply re-queried by calling find() again. +#define MDNS_PACKET_SIZE (1460) + +// How long to wait between polls of the socket while a browse is running. +#define MDNS_POLL_INTERVAL_MS (10) + +// Longest label plus NUL, matching RemoteService's instance_name field. +#define MDNS_LABEL_SIZE (64) +// ...local - enough to validate any name we read. +#define MDNS_MAX_LABELS (4) + +// Case-insensitive compare, since DNS labels are case-insensitive (RFC 1035 +// Section 2.3.3) and responders do not preserve the case of the query. +static bool name_eq(const char *a, const char *b) { + while (*a != '\0' && *b != '\0') { + char ca = *a; + char cb = *b; + if (ca >= 'A' && ca <= 'Z') { + ca += 'a' - 'A'; + } + if (cb >= 'A' && cb <= 'Z') { + cb += 'a' - 'A'; + } + if (ca != cb) { + return false; + } + a++; + b++; + } + return *a == *b; +} + +// Read a DNS name at `offset`, following compression pointers (RFC 1035 Section +// 4.1.4). Writes up to `max_labels` leading labels into `labels`, and the number +// actually written into `n_labels`. +// +// Several labels rather than one: validating a record means checking the whole +// owner name, not its first label. An SRV for "Dev._ssh._tcp.local" and one for +// "Dev._http._tcp.local" share a first label, and matching on that alone made +// whichever arrived last win. +// +// Returns the offset of the byte after the name *in the record being read* - +// which is not where parsing ended if a pointer was followed - or 0 on a +// malformed name. +static size_t read_name(const uint8_t *pkt, size_t pkt_len, size_t offset, + char labels[][MDNS_LABEL_SIZE], size_t max_labels, size_t *n_labels) { + size_t resume = 0; + size_t jumps = 0; + size_t got = 0; + + for (size_t i = 0; i < max_labels; i++) { + labels[i][0] = '\0'; + } + if (n_labels != NULL) { + *n_labels = 0; + } + + while (offset < pkt_len) { + uint8_t len = pkt[offset]; + if (len == 0) { + // End of name. + if (n_labels != NULL) { + *n_labels = got; + } + return resume != 0 ? resume : offset + 1; + } + if ((len & 0xc0) == 0xc0) { + if (offset + 1 >= pkt_len) { + return 0; + } + size_t pointer = ((size_t)(len & 0x3f) << 8) | pkt[offset + 1]; + if (resume == 0) { + resume = offset + 2; + } + // Bound the jumps so a self-referential packet cannot hang us. + jumps++; + if (jumps > 8 || pointer >= pkt_len || pointer == offset) { + return 0; + } + offset = pointer; + continue; + } + if ((len & 0xc0) != 0) { + // Reserved label type. + return 0; + } + offset++; + if (offset + len > pkt_len) { + return 0; + } + if (got < max_labels) { + size_t copy = len; + if (copy > MDNS_LABEL_SIZE - 1) { + copy = MDNS_LABEL_SIZE - 1; + } + memcpy(labels[got], pkt + offset, copy); + labels[got][copy] = '\0'; + got++; + } + offset += len; + } + return 0; +} + +// Skip a name without decoding it. Same return convention as read_name(). +static size_t skip_name(const uint8_t *pkt, size_t pkt_len, size_t offset) { + return read_name(pkt, pkt_len, offset, NULL, 0, NULL); +} + +// Does a name's labels[1..] name the service this browse asked about, i.e. is +// `labels` of the form ..[.local]? +static bool is_instance_of(char labels[][MDNS_LABEL_SIZE], size_t n_labels, + const char *service_type, const char *protocol) { + return n_labels >= 3 && + name_eq(labels[1], service_type) && + name_eq(labels[2], protocol); +} + +static uint16_t read_u16(const uint8_t *p) { + return ((uint16_t)p[0] << 8) | p[1]; +} + +typedef struct { + mdns_remoteservice_obj_t *out; + size_t count; + size_t max; + const char *service_type; + const char *protocol; +} find_state_t; + +// Look up an in-progress result by instance name, appending a new one if there +// is room. Returns NULL when the result array is full. +static mdns_remoteservice_obj_t *get_entry(find_state_t *state, const char *instance_name, bool create) { + if (instance_name[0] == '\0') { + return NULL; + } + for (size_t i = 0; i < state->count; i++) { + if (name_eq(state->out[i].instance_name, instance_name)) { + return &state->out[i]; + } + } + if (!create || state->count >= state->max) { + return NULL; + } + mdns_remoteservice_obj_t *entry = &state->out[state->count]; + memset(entry, 0, sizeof(*entry)); + entry->base.type = &mdns_remoteservice_type; + strlcpy(entry->instance_name, instance_name, sizeof(entry->instance_name)); + strlcpy(entry->service_name, state->service_type, sizeof(entry->service_name)); + strlcpy(entry->protocol, state->protocol, sizeof(entry->protocol)); + state->count++; + return entry; +} + +// Walk every resource record in a response. +// +// `want_addresses` selects the pass: the first pass takes PTR and SRV records to +// learn which instances exist and what host each one points at, the second takes +// A records and attaches addresses to the instances found. Two passes because +// the A record for an SRV target usually arrives in the additional section, +// which may be *before* or after the SRV record that needs it. +static void parse_records(find_state_t *state, const uint8_t *pkt, size_t pkt_len, bool want_addresses) { + if (pkt_len < DNS_HEADER_LEN) { + return; + } + // Only parse responses. + if ((pkt[2] & 0x80) == 0) { + return; + } + size_t questions = read_u16(pkt + 4); + size_t records = (size_t)read_u16(pkt + 6) + read_u16(pkt + 8) + read_u16(pkt + 10); + + size_t offset = DNS_HEADER_LEN; + for (size_t i = 0; i < questions; i++) { + offset = skip_name(pkt, pkt_len, offset); + if (offset == 0 || offset + 4 > pkt_len) { + return; + } + offset += 4; + } + + char owner[MDNS_MAX_LABELS][MDNS_LABEL_SIZE]; + size_t owner_n; + for (size_t i = 0; i < records; i++) { + offset = read_name(pkt, pkt_len, offset, owner, MDNS_MAX_LABELS, &owner_n); + if (offset == 0 || offset + 10 > pkt_len) { + return; + } + uint16_t type = read_u16(pkt + offset); + uint16_t rrclass = read_u16(pkt + offset + 2) & DNS_CLASS_MASK; + uint16_t rdlength = read_u16(pkt + offset + 8); + size_t rdata = offset + 10; + offset = rdata + rdlength; + if (offset > pkt_len) { + return; + } + if (rrclass != DNS_RRCLASS_IN) { + continue; + } + + if (!want_addresses && type == DNS_RRTYPE_PTR) { + // The owner is ..local. Check BOTH labels: a PTR + // for _http._udp must not satisfy a browse for _http._tcp. + if (owner_n < 2 || !name_eq(owner[0], state->service_type) || + !name_eq(owner[1], state->protocol)) { + continue; + } + // RDATA is the full instance name: ... + char target[MDNS_MAX_LABELS][MDNS_LABEL_SIZE]; + size_t target_n; + if (read_name(pkt, pkt_len, rdata, target, MDNS_MAX_LABELS, &target_n) == 0) { + continue; + } + if (!is_instance_of(target, target_n, state->service_type, state->protocol)) { + continue; + } + get_entry(state, target[0], true); + } else if (!want_addresses && type == DNS_RRTYPE_SRV) { + // The owner is ...local and RDATA is + // priority(2) weight(2) port(2) target-name. + if (rdlength < 7) { + continue; + } + // Check the whole owner name, not just the instance label, so an SRV + // for a different service of the same instance cannot overwrite us. + if (!is_instance_of(owner, owner_n, state->service_type, state->protocol)) { + continue; + } + // Only complete an instance the PTR pass already accepted, so an + // unrelated SRV cannot add a result this browse did not ask for. + mdns_remoteservice_obj_t *entry = get_entry(state, owner[0], false); + if (entry == NULL) { + continue; + } + entry->port = read_u16(pkt + rdata + 4); + char target[1][MDNS_LABEL_SIZE]; + if (read_name(pkt, pkt_len, rdata + 6, target, 1, NULL) != 0) { + strlcpy(entry->hostname, target[0], sizeof(entry->hostname)); + } + } else if (want_addresses && type == DNS_RRTYPE_A) { + if (rdlength != 4) { + continue; + } + // Attach to every instance whose SRV target is this host. The + // hostname guard matters: without it an entry that has no SRV yet + // (empty hostname) matches an A record with a root owner name. + for (size_t j = 0; j < state->count; j++) { + mdns_remoteservice_obj_t *entry = &state->out[j]; + if (entry->ipv4_address == 0 && entry->hostname[0] != '\0' && + owner_n >= 1 && name_eq(entry->hostname, owner[0])) { + // Keep the bytes in network order, as the native backends do. + entry->ipv4_address = (uint32_t)pkt[rdata] | + (uint32_t)pkt[rdata + 1] << 8 | + (uint32_t)pkt[rdata + 2] << 16 | + (uint32_t)pkt[rdata + 3] << 24; + } + } + } + // TXT records are skipped: RemoteService has nowhere to put them today. + } +} + +// Build "..local" as a length-prefixed DNS QNAME, +// followed by QTYPE and QCLASS. Returns the total query length, or 0 if the +// names do not fit. +static size_t build_query(uint8_t *buf, size_t buf_len, const char *instance, + const char *service_type, const char *protocol, uint8_t qtype) { + if (buf_len < DNS_HEADER_LEN) { + return 0; + } + memset(buf, 0, DNS_HEADER_LEN); + // ID 0 is correct for multicast DNS (RFC 6762 Section 18.1). + buf[5] = 1; // QDCOUNT = 1 + size_t offset = DNS_HEADER_LEN; + + // With an instance the name is ...local (an + // SRV follow-up for one result); without, ..local. + const char *labels[4]; + size_t n_labels = 0; + if (instance != NULL && instance[0] != '\0') { + labels[n_labels++] = instance; + } + labels[n_labels++] = service_type; + labels[n_labels++] = protocol; + labels[n_labels++] = "local"; + for (size_t i = 0; i < n_labels; i++) { + size_t len = strlen(labels[i]); + if (len == 0 || len > 63 || offset + 1 + len + 5 > buf_len) { + return 0; + } + buf[offset++] = len; + memcpy(buf + offset, labels[i], len); + offset += len; + } + buf[offset++] = 0; // Root label. + + buf[offset++] = 0; + buf[offset++] = qtype; + uint16_t qclass = DNS_RRCLASS_IN | DNS_CLASS_UNICAST_RESPONSE; + buf[offset++] = qclass >> 8; + buf[offset++] = qclass & 0xff; + return offset; +} + +// Receive one datagram, treating a timeout or would-block as "nothing arrived" +// rather than letting it escape as an OSError. A browse is best-effort. +static size_t try_recv(socketpool_socket_obj_t *sock, uint8_t *buf, size_t buf_len) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_uint_t received = common_hal_socketpool_socket_recvfrom_into(sock, buf, buf_len, NULL); + nlr_pop(); + return received; + } + return 0; +} + +size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_type, + const char *protocol, mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len) { + + if (out_len == 0) { + return 0; + } + + socketpool_socketpool_obj_t pool; + pool.base.type = &socketpool_socketpool_type; + common_hal_socketpool_socketpool_construct(&pool, network_interface); + + socketpool_socket_obj_t sock; + if (!socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_DGRAM, 0, &sock)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); + } + + find_state_t state; + state.out = out; + state.count = 0; + state.max = out_len; + state.service_type = service_type; + state.protocol = protocol; + + // Everything below must not leak the socket, which socketpool_socket() + // deliberately leaves unregistered. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + // An ephemeral source port is what makes this a one-shot query rather + // than a full mDNS responder sharing port 5353. + if (common_hal_socketpool_socket_bind(&sock, "", 0, 0) != 0) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); + } + // RFC 6762 Section 11 wants a TTL of 255. Not every backend implements + // the option, and the default of 1 still reaches the local link, so a + // failure here is not fatal. + uint8_t ttl = 255; + common_hal_socketpool_socket_setsockopt(&sock, SOCKETPOOL_IPPROTO_IP, + SOCKETPOOL_IP_MULTICAST_TTL, &ttl, sizeof(ttl)); + common_hal_socketpool_socket_settimeout(&sock, MDNS_POLL_INTERVAL_MS); + + // Deliberately static, not m_malloc(): mdns_server_find() is called + // from the supervisor's web workflow where there may be no VM heap to + // allocate from. Documented as non-reentrant on that basis. + static uint8_t buf[MDNS_PACKET_SIZE]; + + size_t query_len = build_query(buf, MDNS_PACKET_SIZE, NULL, service_type, protocol, + DNS_RRTYPE_PTR); + if (query_len == 0) { + mp_raise_ValueError(MP_ERROR_TEXT("Invalid service type")); + } + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, query_len); + + uint64_t start_ticks = supervisor_ticks_ms64(); + // A negative timeout would wrap to an effectively infinite loop. + uint64_t timeout_ms = timeout > 0 ? (uint64_t)(timeout * 1000) : 0; + // Run to the full timeout even once the array is full: later packets + // still carry the SRV and A records that complete entries already found. + // A responder MAY answer with only the PTR and leave SRV/A to a + // follow-up (RFC 6763 Section 12.1 is a SHOULD, not a MUST). Without + // chasing those the browse returns entries with port 0 and no address, + // which looks like a flaky browser. Ask once, halfway through. + bool chased = false; + while (supervisor_ticks_ms64() - start_ticks < timeout_ms && + !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + uint64_t elapsed = supervisor_ticks_ms64() - start_ticks; + if (!chased && elapsed > timeout_ms / 2) { + chased = true; + for (size_t i = 0; i < state.count; i++) { + if (state.out[i].port != 0) { + continue; + } + size_t n = build_query(buf, MDNS_PACKET_SIZE, state.out[i].instance_name, + service_type, protocol, DNS_RRTYPE_SRV); + if (n != 0) { + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, n); + } + } + } + if (!common_hal_socketpool_readable(&sock)) { + // Without a yield this loop spins at 100% CPU for the whole + // timeout, which also starves the background tasks it runs. + mp_hal_delay_ms(1); + continue; + } + size_t received = try_recv(&sock, buf, MDNS_PACKET_SIZE); + if (received == 0) { + continue; + } + parse_records(&state, buf, received, false); + parse_records(&state, buf, received, true); + } + nlr_pop(); + } else { + socketpool_socket_close(&sock); + nlr_jump(nlr.ret_val); + } + socketpool_socket_close(&sock); + + return state.count; +} diff --git a/shared-module/mdns/Browser.h b/shared-module/mdns/Browser.h new file mode 100644 index 00000000000..e445666b074 --- /dev/null +++ b/shared-module/mdns/Browser.h @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes out from an ephemeral port with the unicast-response (QU) bit +// set, so responders reply directly to us and we never have to join the +// 224.0.0.251 multicast group. That matters because socketpool exposes +// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is +// not portable today. The cost is that responses a responder chooses to +// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered +// recently) are missed; a repeat find() generally picks them up. + + +#pragma once + +#include "py/obj.h" + +#include "shared-bindings/mdns/RemoteService.h" + +// Run one DNS-SD browse over plain sockets and return how many services were +// written into `out` (at most `out_len`). +// +// Needs only a SocketPool, so it works on any backend that terminates an IP +// stack on the host. `network_interface` is what a SocketPool is constructed +// from. May raise; callers without an nlr handler must wrap it. +// +// Not reentrant: it uses a single static receive buffer so that it can run in +// supervisor context, where there may be no VM heap. +size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_type, + const char *protocol, mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len); diff --git a/shared-module/mdns/RemoteService.c b/shared-module/mdns/RemoteService.c new file mode 100644 index 00000000000..f9e2b7d3c89 --- /dev/null +++ b/shared-module/mdns/RemoteService.c @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mdns/RemoteService.h" + +#include "shared-bindings/ipaddress/IPv4Address.h" + +const char *common_hal_mdns_remoteservice_get_service_type(mdns_remoteservice_obj_t *self) { + return self->service_name; +} + +const char *common_hal_mdns_remoteservice_get_protocol(mdns_remoteservice_obj_t *self) { + return self->protocol; +} + +const char *common_hal_mdns_remoteservice_get_instance_name(mdns_remoteservice_obj_t *self) { + return self->instance_name; +} + +const char *common_hal_mdns_remoteservice_get_hostname(mdns_remoteservice_obj_t *self) { + return self->hostname; +} + +mp_int_t common_hal_mdns_remoteservice_get_port(mdns_remoteservice_obj_t *self) { + return self->port; +} + +uint32_t mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { + return self->ipv4_address; +} + +mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { + uint32_t addr = mdns_remoteservice_get_ipv4_address(self); + if (addr == 0) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(addr); +} diff --git a/shared-module/mdns/RemoteService.h b/shared-module/mdns/RemoteService.h new file mode 100644 index 00000000000..420ade61a20 --- /dev/null +++ b/shared-module/mdns/RemoteService.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +// Field names and sizes match the native backends (see +// ports/raspberrypi/common-hal/mdns/RemoteService.h) so that shared-bindings +// and the web workflow are agnostic to which implementation is built. +typedef struct { + mp_obj_base_t base; + uint32_t ipv4_address; // Network byte order, as the native backends store it. + uint16_t port; + char protocol[5]; // RFC 6763 Section 7.2 - 4 bytes + 1 for NUL + char service_name[17]; // RFC 6763 Section 7.2 - 16 bytes + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + mp_obj_t next; +} mdns_remoteservice_obj_t; diff --git a/shared-module/mdns/Server.c b/shared-module/mdns/Server.c new file mode 100644 index 00000000000..4bcb8095662 --- /dev/null +++ b/shared-module/mdns/Server.c @@ -0,0 +1,142 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// A portable DNS-SD browser built on socketpool, so that mdns.Server.find() +// works on any port that terminates an IP stack on the host rather than only on +// those with a native mDNS library. +// +// This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: +// the query goes out from an ephemeral port with the unicast-response (QU) bit +// set, so responders reply directly to us and we never have to join the +// 224.0.0.251 multicast group. That matters because socketpool exposes +// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is +// not portable today. The cost is that responses a responder chooses to +// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered +// recently) are missed; a repeat find() generally picks them up. + + +#include "shared-bindings/mdns/Server.h" + +#include +#include + +#include "py/objtuple.h" +#include "py/runtime.h" + +#include "shared-bindings/mdns/RemoteService.h" +#include "shared-module/mdns/Browser.h" + +#if CIRCUITPY_WIFI +#include "shared-bindings/wifi/__init__.h" +#endif + +// The allocating find() collects into a bounded scratch array rather than an +// unbounded list, so a chatty network cannot exhaust the heap mid-browse. +#define MDNS_MAX_RESULTS (16) + + +void mdns_server_construct(mdns_server_obj_t *self, bool workflow) { + self->hostname[0] = '\0'; + self->instance_name[0] = '\0'; + // The web workflow calls this directly on a static object, so default the + // interface here rather than only in common_hal_mdns_server_construct(). + #if CIRCUITPY_WIFI + self->network_interface = MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj); + #else + self->network_interface = mp_const_none; + #endif + self->workflow = workflow; + self->inited = true; +} + +void common_hal_mdns_server_construct(mdns_server_obj_t *self, mp_obj_t network_interface) { + #if CIRCUITPY_WIFI + if (network_interface != MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj)) { + mp_raise_ValueError(MP_ERROR_TEXT("mDNS only works with built-in WiFi")); + } + #endif + mdns_server_construct(self, false); + self->network_interface = network_interface; +} + +void common_hal_mdns_server_deinit(mdns_server_obj_t *self) { + self->inited = false; +} + +bool common_hal_mdns_server_deinited(mdns_server_obj_t *self) { + return !self->inited; +} + +const char *common_hal_mdns_server_get_hostname(mdns_server_obj_t *self) { + return self->hostname; +} + +void common_hal_mdns_server_set_hostname(mdns_server_obj_t *self, const char *hostname) { + strlcpy(self->hostname, hostname, sizeof(self->hostname)); +} + +const char *common_hal_mdns_server_get_instance_name(mdns_server_obj_t *self) { + if (self->instance_name[0] == '\0') { + return self->hostname; + } + return self->instance_name; +} + +void common_hal_mdns_server_set_instance_name(mdns_server_obj_t *self, const char *instance_name) { + strlcpy(self->instance_name, instance_name, sizeof(self->instance_name)); +} + +void common_hal_mdns_server_advertise_service(mdns_server_obj_t *self, const char *service_type, + const char *protocol, mp_int_t port, const char *txt_records[], size_t num_txt_records) { + // This implementation is a browser only: answering queries needs a + // responder holding port 5353, which belongs in the port's own common-hal. + // + // The supervisor advertises the web workflow through this same entry point + // (supervisor/shared/web_workflow/web_workflow.c), with no nlr handler in + // place, so raising there would be fatal. Report the limitation to user code + // and let the supervisor carry on unadvertised - its HTTP server still + // serves, it simply cannot be discovered by name. + if (self->workflow) { + return; + } + mp_raise_NotImplementedError(MP_ERROR_TEXT("Advertising services is not supported on this board")); +} + +// Non-allocating entry point, also used by the supervisor's web workflow +// (supervisor/shared/web_workflow/web_workflow.c). That caller has no nlr +// handler, so nothing may escape from here: a failed browse is zero results. +size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const char *protocol, + mp_float_t timeout, mdns_remoteservice_obj_t *out, size_t out_len) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + size_t count = shared_module_mdns_find(self->network_interface, service_type, protocol, + timeout, out, out_len); + nlr_pop(); + return count; + } + // Swallowed on purpose; see the comment above. Raising here would longjmp + // into a handler that does not exist. + return 0; +} + +mp_obj_t common_hal_mdns_server_find(mdns_server_obj_t *self, const char *service_type, + const char *protocol, mp_float_t timeout) { + // Browse into a scratch array, then hand out one GC object per result so + // each is independently tracked, matching the native backends. + mdns_remoteservice_obj_t *scratch = m_new(mdns_remoteservice_obj_t, MDNS_MAX_RESULTS); + size_t count = shared_module_mdns_find(self->network_interface, service_type, protocol, + timeout, scratch, MDNS_MAX_RESULTS); + + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(count, NULL)); + for (size_t i = 0; i < count; i++) { + mdns_remoteservice_obj_t *service = m_new_obj(mdns_remoteservice_obj_t); + *service = scratch[i]; + service->base.type = &mdns_remoteservice_type; + service->next = NULL; + tuple->items[i] = MP_OBJ_FROM_PTR(service); + } + return MP_OBJ_FROM_PTR(tuple); +} diff --git a/shared-module/mdns/Server.h b/shared-module/mdns/Server.h new file mode 100644 index 00000000000..3c81ec0f8ea --- /dev/null +++ b/shared-module/mdns/Server.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +#include "shared-module/mdns/RemoteService.h" + +typedef struct { + mp_obj_base_t base; + // The radio this server queries through. Kept so find() can build a + // SocketPool on demand rather than holding a socket open. + mp_obj_t network_interface; + // Stored for the hostname/instance_name properties. This implementation has + // no responder, so they are not advertised anywhere; see + // common_hal_mdns_server_advertise_service(). + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL + // Set for the supervisor's web workflow object, which cannot handle an + // exception. See common_hal_mdns_server_advertise_service(). + bool workflow; + bool inited; +} mdns_server_obj_t; diff --git a/shared-module/mdns/__init__.c b/shared-module/mdns/__init__.c new file mode 100644 index 00000000000..9ea5e1a844d --- /dev/null +++ b/shared-module/mdns/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No mdns module functions. From 759e28164408f1556808250f4bbaa469270cd445 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 01:07:47 +0000 Subject: [PATCH 02/30] docs: DNS-SD and Wi-Fi Aware research notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Working notes for tyeth/deepsleep_espnow_wifi_and_ble_env_collector#18: what it would take to add DNS-SD and Wi-Fi Aware (NAN) to CircuitPython across backends, and what the hardware actually does today. Measured on rpi-hil006 against CircuitPython's pinned ESP-IDF v6.1-dev-6096: - NAN-Sync works end to end. Cluster at 3.35 s from boot, service match 4.40 s, IPv6 NDP datapath 4.93 s, then ICMPv6 over that datapath at 2 ms RTT with no loss. It is an exclusive radio mode (wifi:mode : NAN) and the NMI MAC is randomised at every start, so the peer's link-local address changes on every wake. - NAN-USD transmits correctly but never discovers. Localised with a promiscuous capture running alongside the subscribe: the subscriber's own NIC counted 407 NAN service discovery frames while nan_de_rx_sdf() was never entered, with a positive control proving the logging was live. The frames reach the radio and are not handed to the discovery engine. This is upstream, not misconfiguration, and is reproducible without any NAN code. - USD does coexist with STA, on the associated AP's channel. Pinned to the AP's channel both boards held association for the whole run; pinned elsewhere the link dies at ~36 s with no STA_DISCONNECTED event and a stale IP left in esp_netif. Hence the API rule that USD must default to the AP's channel. SOC_WIFI_NAN_SUPPORT gates only ESP_WIFI_NAN_SYNC_ENABLE; USD depends only on IDF_EXPERIMENTAL_FEATURES. The notes no longer describe either as a demonstrated silicon requirement, since the gated chip list skips a generation and returns, and CircuitPython already runs two TSF domains on one radio via WIFI_MODE_APSTA. Conclusion recorded in the notes: do the DNS-SD browser first, since it serves every port and risks nothing, and build any wifiaware module on Sync rather than USD. Open items are listed in section 14.5 — chiefly that the browser has not yet met a real responder, and that phone interop needs secured NDP and pairing, both untested. Co-Authored-By: Claude Opus 5 --- RESEARCH-dns-sd-wifi-aware.md | 591 ++++++++++++++++++++++++++++++++++ 1 file changed, 591 insertions(+) create mode 100644 RESEARCH-dns-sd-wifi-aware.md diff --git a/RESEARCH-dns-sd-wifi-aware.md b/RESEARCH-dns-sd-wifi-aware.md new file mode 100644 index 00000000000..330c2f9ef04 --- /dev/null +++ b/RESEARCH-dns-sd-wifi-aware.md @@ -0,0 +1,591 @@ +# DNS-SD + Wi-Fi Aware (NAN) support in CircuitPython — research + +Tracking: tyeth/deepsleep_espnow_wifi_and_ble_env_collector#18 +CircuitPython @ upstream `762ab15ca0` · ESP-IDF pin `v6.1-dev-6096-g29d36039e56` (adafruit `circuitpython-v6.1`) +**v6** — two reversals from new hardware work. **§13.1a: USD does *not* inherently break an associated STA** — the earlier result was my own channel pinning. **§13.2a: the USD defect is localised** — 407 SDFs reach the NIC and the discovery engine is never called. Also reframes "needs NAN silicon" as a firmware gate (§14.2a), and revises §6/§7.1/§9/§10/§12 which v4 had left stale. v5 fixed three errors a review caught; v1's central conclusion was wrong too (§11). + +## 0. TL;DR + +* **There are two Wi-Fi Aware protocols, not one**, and nearly every conclusion depends on which you mean: + * **NAN-Sync** — clustered, synchronised. Gives pairing and an **IPv6 datapath** (real sockets). Gated by `SOC_WIFI_NAN_SUPPORT`: **esp32, esp32s2, esp32c5, esp32c61, esp32s31** — *not* S3/C3/C6. **Exclusive radio mode in this IDF** (`wifi:mode : NAN`, confirmed on hardware). See §14.2a — "needs NAN silicon" is *not* a justified reading of that gate. + * **NAN-USD** — unsynchronised. Publish / subscribe / follow-up messages only, **no datapath, no pairing**. Runs on the **STA interface**, and needs **no special hardware at all**: `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` (`esp_wifi/Kconfig:620`), never on `SOC_WIFI_NAN_SUPPORT` (which gates only `ESP_WIFI_NAN_SYNC_ENABLE`, `:595-598`). Confirmed on hardware: the ESP32-S3, with zero `SOC_WIFI_NAN_SUPPORT`, ran the USD stack and put well-formed NAN frames on the air. **A USD publish is an ordinary Public Action vendor-specific management frame** — anything that can transmit one and do remain-on-channel could in principle speak USD. +* **USD looked like the right answer for issue #18 — hardware says not yet.** Two measured results (§13): + * **USD *does* coexist with STA — on the AP's channel** (§13.1a). An earlier version of this document claimed USD is inherently radio-owning; that was an artefact of my own harness pinning USD to channel 6 while the AP was on channel 1. Re-run with USD following the AP's channel, **both boards stayed associated for 100 s and the home channel never left the AP**. Off-channel, though, the link dies **silently** — no `STA_DISCONNECTED`, stale IP kept. **API rule that falls out of this: default USD's channel to the associated AP's, and only allow another when no STA is up.** +* **USD discovery is broken in the pinned IDF, and the defect is now localised** (§13.2a). The subscriber's own radio receives **407 NAN SDFs** while its USD subscribe is active, yet `nan_de_rx_sdf()` is **never entered** (proved with a positive control on the same log tag). Frames arrive at the NIC; the closed Wi-Fi blob never delivers them to the engine's remain-on-channel callback. Not a misconfiguration — a fileable upstream bug, with a reproducer that needs no NAN code. +* **NAN-Sync, by contrast, works** (§14): cluster → service match → **open (unsecured)** IPv6 datapath in **4.9 s from boot**, then ICMPv6 at **2 ms RTT, 0 % loss**, between a classic ESP32 and an ESP32-S31. Scope this honestly: **one run, ESP-to-ESP, both boards always-on, no security**. Issue #18's two distinguishing needs — **phone interop and deep sleep — are untested**, and phone interop requires `ESP_WIFI_NAN_SECURITY` / `ESP_WIFI_NAN_PAIRING`, which *are* gated on `IDF_EXPERIMENTAL_FEATURES`, the same label held against USD. For ESP-to-ESP without phones, ESP-NOW already does AP-less transport at lower wake cost; Sync's unique value lies precisely in the untested part. +* **Sync owns the radio — but honestly** (§14.4). Starting it on a live STA fires `STA_DISCONNECTED` immediately, clears the IP, refuses `esp_wifi_connect()` with `ESP_ERR_WIFI_MODE`, and gives STA back in **1.5 s** on stop. Every transition is observable, so `wifi.radio` can model it. USD, by contrast, keeps STA alive on the AP's channel (§13.1a) but fails *silently* when taken off it — so a USD binding's job is to pick the channel for you, while a Sync binding's job is to own the radio. +* **No common working denominator.** espressif has working Sync and broken USD; zephyr-cp has USD only — **and I never tested it**, so that column is "unknown", not "broken". Note too that Zephyr's hostap USD needs a driver with `remain_on_channel`/`send_action`, which the CYW43/AIROC driver lacks, so zephyr-cp USD reaches at most `frdm_rw612`. Either way Wi-Fi Aware is espressif-only and Sync-based for now — a port-specific, radio-owning module (§7.2), not the portable one §7.1 imagined. +* **Consequence: start with Feature A (DNS-SD).** It is the only part of issue #18 that is both portable and working. +* **ESP32-S3**: v1 said it was excluded outright, which was wrong — it runs the USD stack and transmits valid NAN frames (confirmed on hardware). Since the recommendation is now Sync-based, the S3 is excluded *in practice* — but by Espressif's `SOC_WIFI_NAN_SUPPORT` declaration, which is **not demonstrably a silicon limit** (§14.2a). Worth raising with Espressif rather than treating as physics. +* **CircuitPython already ships DNS-SD** as `mdns` (espressif + raspberrypi). The gap is zephyr-cp. +* **No prior art anywhere in our ecosystem**: no NAN in MicroPython, none in arduino-esp32. +* **zephyr-cp's pinned Zephyr is USD-only** — which looked like the convergence point for a portable design, until USD turned out to be the broken half (§14.3). + +--- + +## 1. What the issue asks for + +An AP-less, DHCP-less, internet-less transport for a deep-sleeping environmental sensor collector, with a DNS-SD-shaped API and iOS/Android interop. Two separable features: + +| | Feature | Status | +|---|---|---| +| **A** | **DNS-SD** over mDNS on a normal IP network | **exists** as `mdns`; missing on zephyr-cp | +| **B** | **Wi-Fi Aware (NAN)** — AP-less discovery + optional datapath | **does not exist** in any port | + +Feature A is independently shippable and should go **first**. + +--- + +## 2. CircuitPython today + +`shared-bindings/mdns/` — `Server` (`hostname`, `instance_name`, `find()`, `advertise_service()`) and `RemoteService`. Backends: espressif (wraps the IDF `mdns` component) and raspberrypi. Gated by `CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI)`. **zephyr-cp has no `mdns`.** No NAN anywhere. + +--- + +## 3. ESP-IDF — the Sync/USD split + +### 3.1 The decisive facts, from the pinned tree + +| Fact | Evidence | +|---|---| +| Sync start **forces** `WIFI_MODE_NAN` | `nan_app.c:2003` | +| Sync stop takes the whole radio down | `nan_app.c:2057` (`esp_wifi_stop()`) | +| `wifi_mode_t` has no combined NAN+STA | `esp_wifi_types_generic.h:25-33` | +| **USD runs on `WIFI_MODE_STA`** | `nan_app.c:2986` | +| USD gated only on `IDF_EXPERIMENTAL_FEATURES`, **not** on NAN silicon | `esp_wifi/Kconfig:620-623` | +| USD example targets incl. **S3, C3, C6, C2** | `examples/wifi/wifi_aware/usd_publisher/README.md:1` | +| Sync and USD **cannot coexist** | `nan_app.c:1943` | +| Hard limits: **2 services, 2 datapath peers, 2 stored credentials** | `esp_wifi_types_generic.h:875,876,884` | +| SSI payloads: follow-up ≤2048 B, publish ≤512 B | `esp_wifi_types_generic.h:890-891` | + +CP already sets `IDF_EXPERIMENTAL_FEATURES` (`ports/espressif/esp-idf-config/sdkconfig.defaults:158`), so USD, pairing and secured NDP are all reachable — but note that is Espressif-labelled **experimental** code. + +### 3.2 Chip support + +`SOC_WIFI_NAN_SUPPORT` is defined only for **esp32, esp32s2, esp32c5, esp32c61, esp32s31**. That gates **NAN-Sync and the datapath only**. + +CP board counts: esp32 **52**, esp32s2 **56**, esp32c5 **2**, esp32c61 **1**. + +**USD, and therefore discovery + messaging, works on every ESP Wi-Fi chip including the whole S3 fleet.** + +### 3.3 The `wifi_aware` component is Sync-only + +Espressif's `wifi_aware` component (`esp-wifi-apps`, Apache-2.0, v0.1.0) is the DNS-SD-shaped wrapper issue #18 links to. It calls `esp_wifi_nan_sync_start()` directly (`wa_init.c:113`) and its USD path is `#if 0`'d (`wa_init.c:115-122`). + +So **the component implies the exclusive radio mode and the datapath**. It also: +* has **no messaging API** — init / advertise / discover / pair / connect / disconnect only (`wifi_aware.h:453-642`); follow-ups are consumed internally for its SRV/TXT exchange; +* selects peer platform at **compile time** via a Kconfig *choice* — Default / iOS / Android, **mutually exclusive** (component `Kconfig:3-31`), because Android peers support no group ciphers. **One firmware cannot serve both iOS and Android.** +* includes a **private IDF header** (`apps_private/wifi_apps_private.h`) and calls `esp_nan_set_compatibility_mode_internal` — a v0.1.0 component bound to private API on a `-dev` IDF pin. + +IDF ≥6.1 is what unlocks pairing / secured NDP / iOS, and we are on 6.1-dev. That part of v1 stands. + +--- + +## 4. Zephyr + +### 4.1 DNS-SD: advertise yes, browse no + +`zephyr/net/dns_sd.h` + `mdns_responder_set_ext_records()` cover advertising. **Browsing is absent** — `CONFIG_MDNS_RESOLVER` does `.local` A/AAAA only, with no PTR→SRV→TXT enumeration. `mdns.Server.find()` has nothing to wrap. + +### 4.2 NAN: USD-only at our pin + +zephyr-cp pins `adafruit/zephyr@ab22ad4b` (`ports/zephyr-cp/zephyr-config/west.yml`). At that revision: +* `enum wifi_nan_operation` has six ops: PUBLISH, CANCEL_PUBLISH, UPDATE_PUBLISH, SUBSCRIBE, CANCEL_SUBSCRIBE, TRANSMIT; +* hostap builds only `nan_usd.c`, `nan_usd_ap.c`, `nan_de.c`; +* **no cluster sync and no NDP anywhere in the stack.** + +Upstream Zephyr main has since added `nan_ndp.c`, `nan_sec.c`, `nan_bootstrap.c` and `NAN_NDP_REQUEST`/`NAN_PAIR` control commands — only the `wifi_mgmt.h` glue is missing. So "Zephyr has no datapath" is true for us but has a **short shelf life**. + +`CONFIG_WIFI_NAN_MAX_SSI_LEN` defaults to **128 bytes** — the tightest payload ceiling in the system. + +### 4.3 Two zephyr-cp blockers + +* **No IPv6 at all.** `CONFIG_NET_IPV6` appears nowhere in zephyr-cp. `frdm_rw612/board.conf` is IPv4 + DHCPv4 only. Any IPv6 datapath story is moot there. +* **`frdm_rw612/board.conf` has no hostap/NAN config**, and whether Wi-Fi even works on that board in zephyr-cp is unverified. + +--- + +## 5. Prior art (as asked) + +* **MicroPython: no NAN** (0 hits for `esp_wifi_nan`), **no core DNS-SD module**. The esp32 port uses the IDF mdns component only for `.local` lookups. Third-party: cbrand/micropython-mdns, nickovs/slimDNS (both pure Python). **PyDevices PR #108** adds a C `mdns` module **modeled on CircuitPython's API** — influence runs our way, so don't churn `mdns`'s shape. +* **arduino-esp32: no NAN** (0 hits). `ESPmDNS` only. **No Arduino path to cross-check against** — bring-up must use ESP-IDF's own examples. + +### Phones +* **Android:** Wi-Fi Aware since 8.0 / API 26. USD support is much more recent (believed Android 16) with a small follow-up payload — **verify before committing to a USD-only design**. +* **iOS 26:** `WiFiAware` framework over Network framework; implements **DNS-SD naming on top of NAN**; service strings like `_ESP-Demo._udp` declared in `Info.plist`. **Pairing is mandatory** (6-digit PIN, no open datapath) — i.e. **iOS requires NAN-Sync + datapath**, which excludes S3 and excludes STA coexistence. + +### Testing constraints +* **The Android emulator cannot test this.** No NAN HAL; `WifiAwareManager` reports unavailable. A physical Android 8+ handset is required. +* **Apple gates iOS behind the `com.apple.developer.wifi-aware` entitlement** — request and approval needed before the app will build, plus Xcode 26 and a physical iOS 26 device. **Apply now.** + +--- + +## 6. Deep sleep — the finding that reframes the use case + +NAN-Sync is structurally hostile to a deep-sleeping sensor: +* defaults `scan_time = 3 s` and `warm_up_sec = 5` before taking anchor-master role (`esp_nan.h:19-28`); +* discovery only in windows every **524 ms** (`nan_i.h:37`); +* every wake is a cold start: scan → join/form cluster → wait for a discovery window → (for iOS) PASN pairing-verify → NDP handshake; +* **estimated** seconds of radio-on per wake vs. tens of milliseconds for ESP-NOW — one to two orders of magnitude more energy per report. *Derived from constants, not measured.* +* MAC randomisation is on by default, so each wake is a new identity and a new peer handle unless paired with NVS caching; +* the peer must be on air at wake time — a phone app must have a live session. + +**USD would avoid all of this**: no cluster, and `ttl = 0` sends a single publish (`esp_wifi_types_generic.h:1061`). One measured number now anchors the Sync side: **4.9 s from boot to a usable IPv6 datapath** (§14.1), of which 3.0 s is the default `scan_time` and so is tunable. That is a real figure to weigh against ESP-NOW's tens of milliseconds, and it confirms the order-of-magnitude estimate above rather than replacing it — the energy integral is still unmeasured. + +**But USD cannot be used for this today** (§13.2a), so the deep-sleep argument for preferring USD is currently academic. If the upstream RX defect is fixed, this section becomes the strongest argument for USD over Sync; until then it is a reason to measure Sync's wake cost properly rather than to assume either. + +**And the datapath may not be needed at all.** A sensor reading fits in a publish SSI (≤512 B) or one follow-up (≤2048 B) — no NDP, no IPv6, no sockets. + +--- + +## 7. Proposed CircuitPython API — revised + +v1 proposed capability tiers with `supported_features`. **That should be dropped.** There is no precedent for a capability-set API in `shared-bindings`; the house mechanism is module presence in the support matrix plus `NotImplementedError` on individual methods (e.g. `ports/raspberrypi/common-hal/wifi/Radio.c:540`). A module where half the classes raise on half the ports is exactly the "behaves differently per port" shape reviewers reject. + +**Split by what is genuinely common instead.** + +### 7.1 Core: a small USD-shaped module — **on hold** + +> **Status after §13/§14: do not build this yet.** It was proposed as the portable core because both backends can nominally do USD. They cannot *usefully*: espressif's USD discovery is broken upstream (§13.2a) and zephyr-cp's is untested and reaches at most one board (§14.3). The shape below is still the right shape — it is what a fixed USD should expose — but there is nothing working to implement it against today. Build §7.2 instead, or wait for the upstream fix. + +The intended shape, kept for when USD works: + +```python +import wifiaware +pub = wifiaware.publish("_envcollect._udp", ssi=b"t=21.5", ttl=0) +sub = wifiaware.subscribe("_envcollect._udp") +for peer in sub: + peer.send(b"ack") # follow-up +``` + +Three constraints the hardware work added to this design: + +* **Channel is not an implementation detail.** When a STA is associated, the binding must default USD's channel to the AP's, because off-channel USD kills the link *silently* (§13.1a). That is an API decision, not a tuning knob. +* **Payload limits differ** (ESP 2048 / Zephyr 128) — expose the ceiling as a constant rather than hiding it. +* **SSI is not interoperable as-is.** The ESP fork puts service-specific info on the wire raw; upstream hostap prepends the WFA OUI and protocol type and requires them on receive (§13.2). A portable API must decide which it speaks, or peers will discover each other and then fail to understand the payload. + +### 7.2 Datapath + pairing: espressif-only, separate + +Not a tier that raises — **classes that simply do not exist on other ports**, documented as espressif-only, like any other port-specific module. This is where iOS interop lives. + +Because NAN-Sync is an **exclusive radio mode**, the entry point belongs **on or beside `wifi.radio`**, not a free-standing object: `wifi.radio` owns mode and tracks `started`/`sta_mode`/`ap_mode` (`ports/espressif/common-hal/wifi/Radio.c:62,81,102,107`). Anything that calls NAN start behind its back desynchronises that state, and web workflow / `settings.toml` auto-connect will fight it. It needs defined errors when STA/AP is active. + +Agreed with v1: a new module, not an extension of `mdns` (`mdns.Server` requires a `network_interface`, `shared-bindings/mdns/Server.c:27-51`). + +### 7.3 Scoped IPv6 — real, but smaller than v1 claimed + +`connect`/`sendto`/`bind` all call `mp_obj_get_array_fixed_n(addr_in, 2, …)` (`shared-bindings/socketpool/Socket.c:91,129,299`), so a 4-tuple raises `ValueError` today. But output already carries scope (`getaddrinfo`/`recvfrom` return 4-tuples with `sin6_scope_id`), and lwIP parses the zoned string form `fe80::x%`. So `connect(("fe80::…%na1", port))` may already work untouched, or `Endpoint.address` can return the zoned string. Proper 4-tuple support is ~20 lines plus a common-hal signature change. **Not the dominant cost.** Moot on zephyr-cp, which has no IPv6. + +--- + +## 8. Feature A — do this first + +Porting `mdns` to zephyr-cp splits cleanly: +* `advertise_service()` → `dns_sd_rec` array + `mdns_responder_set_ext_records()`. Mechanical. +* `find()` → nothing to wrap. **Write a DNS-SD browser in `shared-module/`** over a plain UDP multicast socket. + +The shared-module browser gives `mdns.Server.find()` to **every port with sockets**, present and future — directly serving the "easily facilitate other network platforms later" goal. Independently shippable, no hardware risk. Start IPv4-only (zephyr-cp has no IPv6). + +--- + +## 9. Risks + +| # | Risk | Status | +|---|---|---| +| 1 | **NAN-Sync cannot coexist with STA/AP** | **Confirmed on hardware** (§14.4): `WIFI_MODE_NAN` is exclusive, `wifi_mode_t` has no NAN+STA value. Transitions are clean and observable, and STA returns in 1.5 s. | +| 1b | **USD cannot coexist with STA** | **Disproved** (§13.1a). USD on the AP's channel holds the link for 100 s. Off-channel it dies *silently* — so the binding must pick the channel. | +| 2 | Datapath gated by `SOC_WIFI_NAN_SUPPORT` (no S3/C3/C6) | Confirmed as a Kconfig gate; **not demonstrably silicon** (§14.2a). USD needs no such gate at all. | +| 2b | **USD discovery is broken upstream** | **Confirmed and localised** (§13.2a): 407 SDFs reach the NIC, `nan_de_rx_sdf()` never runs. Blocks every USD plan until fixed. | +| 3 | **Per-wake energy/latency of NAN-Sync** | Partly measured: 4.9 s boot→datapath (§14.1). Energy still unmeasured. | +| 4 | **Compile-time iOS/Android exclusivity** | Confirmed; one firmware cannot serve both | +| 5 | **USD (Zephyr) vs Sync (component) mismatch** | Worse than stated: zephyr-cp USD is untested *and* reaches at most `frdm_rw612` (§14.3). Also, the ESP fork puts SSI on the wire raw where upstream hostap prepends the WFA OUI — so even a working USD may not interop with a Zephyr/Android peer (§13.2). | +| 6 | Limits of 2 services / 2 datapaths / 2 credentials | Confirmed | +| 7 | zephyr-cp has **no IPv6**, and rw612 Wi-Fi unverified | Confirmed | +| 8 | `wifi_aware` is v0.1.0 on private IDF API | Maintenance risk | +| 9 | Apple entitlement lead time | Apply now | +| 10 | No Android emulator path | Physical handset needed | +| 11 | Android USD API level + payload size | **Unverified** — but moot while USD discovery is broken | +| 12 | **Secured NDP / pairing is itself experimental** | `ESP_WIFI_NAN_SECURITY` and `ESP_WIFI_NAN_PAIRING` depend on `IDF_EXPERIMENTAL_FEATURES` — the same gate held against USD, and untested here. Phone interop needs them. | + +--- + +## 10. Sequencing + +Revised against §13/§14. Steps 2a and 2b of the v2 plan are **done**; the rest is reordered because USD is blocked upstream. + +1. **Feature A — the portable DNS-SD browser.** Written and building (`shared-module/mdns/Browser.c`, selected by `CIRCUITPY_MDNS_SHARED`). Remaining: validate against a real responder on hardware, then the zephyr-cp `advertise_service()` half. No dependency on anything below. +2. **File the USD RX defect upstream** (§13.2a). Everything USD-shaped is blocked behind it, and the reproducer is small. +3. **Measure Sync's wake cost** — boot→datapath is 4.9 s (§14.1); the energy integral per report versus ESP-NOW is the number that actually decides issue #18. +4. **Test secured NDP and pairing** (risk #12). Untested, experimental, and the prerequisite for any phone interop. +5. **Apply for the Apple entitlement** — long lead time, start regardless. +6. **Then** decide the module: a `wifiaware` Sync module, espressif-only, owning `wifi.radio` (§7.2) — *or*, if step 2 lands a fix, revisit USD, which needs no `SOC_WIFI_NAN_SUPPORT` and coexists with STA on the AP's channel. + +Note what is *not* on this list any more: "`wifiaware` USD module, espressif + zephyr" (v2 step 5). There is no working USD on either backend to build it on. + +--- + +## 11. What changed from v1 + +| v1 claim | Correction | +|---|---| +| "Every ESP32-S3 board is out, permanently" | **Wrong.** The S3 runs USD; only the datapath is gated by `SOC_WIFI_NAN_SUPPORT` — which is itself a firmware declaration, not a proven silicon limit (§14.2a). | +| STA+NAN coexistence "blocking, verify on hardware" | **Settled from source** — Sync forces `WIFI_MODE_NAN`. No experiment needed. | +| NAN-USD | **Missed entirely.** v1 cited `usd_publisher` without noticing what it was, and missed `usd_subscriber`. | +| Capability tiers + `supported_features` | Dropped — no precedent in `shared-bindings`, likely rejected. | +| "Tier 1 messaging: ESP + Zephyr" | The `wifi_aware` component **has no messaging API**. | +| Zephyr facts | Verified against upstream main, **not** the pinned `adafruit/zephyr@ab22ad4b`. Pinned tree is USD-only. | +| Scoped IPv6 "may be the biggest hidden cost" | Overstated — ~20 lines, and possibly already works via zoned strings. | +| Deep sleep | Not considered. It is arguably the most important constraint of all. | +| `esp_wifi_nan_start` | On 6.x it is `esp_wifi_nan_sync_start`. | + +--- + +## 12. Other CircuitPython network platforms + +Scope is **not** limited to the deepsleep project, and **NAN-Sync is wanted as well as USD**. Surveying every Wi-Fi backend CircuitPython has: + +| Platform | DNS-SD | NAN | Evidence | +|---|---|---|---| +| **espressif** (native) | `mdns` ✔ | **Sync + USD** ✔ | IDF 6.1; USD hardware-confirmed below | +| **raspberrypi** Pico W / Pico 2 W (CYW43) | `mdns` ✔ (lwIP) | **none** | 0 hits for NAN in `georgerobotics/cyw43-driver` | +| **zephyr-cp** | advertise only, no browse | **USD only** at our pin | §4 | +| **AirLift / WiFiNINA** (`nina-fw`) | via firmware | **none** | 0 hits for NAN in `adafruit/nina-fw` | +| **ESP-Hosted** | via host IP stack | **none exposed** | `rpc_v2.proto` has no NAN RPC — only "Nano" false positives; `esp_wifi_nan` appears solely in `esp_netif_defaults` | +| **ESP8266** | — | **none** (no NAN in the NONOS SDK; CP has no esp8266 port) | — | + +Conclusions for the wider scope: + +* **NAN is espressif-silicon-only in practice.** Every co-processor path (AirLift, ESP-Hosted, CYW43) would need firmware or RPC work before CircuitPython could expose NAN on it. AirLift and ESP-Hosted *run on NAN-capable ESP32 silicon*, so the capability exists — it is the host protocol that does not carry it. ESP-Hosted is the more tractable of the two, since extending `rpc_v2.proto` is additive; `nina-fw` is a frozen Arduino-era command set. +* Infineon's WHD has some NAN event plumbing under `COMPONENT_WIFI6`, but that is not the driver Pico W / Pico 2 W use — `cyw43-driver` has none. +* **DNS-SD is reachable on more platforms — but not "everywhere", as this section previously claimed.** Corrected after review: + * **AirLift / WiFiNINA does *not* terminate its IP stack on the host.** nina-fw runs the stack on the co-processor, CircuitPython reaches it through the Python `adafruit_esp32spi` library rather than C `socketpool`, and `common_hal_mdns_server_construct` rejects any interface but the built-in radio. A `shared-module` browser over `socketpool` therefore does **not** reach AirLift. + * Pico W already has a native `find()`, so it gains nothing. + * **The realistic beneficiary of the shared browser is zephyr-cp** (plus any future socket-capable port). That is still worth doing — it is the only portable, working piece of issue #18 — but the "lights up four platforms at once" claim was wrong. +* `esp32s31` is a **preview target** in this IDF (`tools/idf_py_actions/constants.py:53`), so it builds only with `--preview`. + +--- + +### 12.1 What "needs NAN hardware" actually means + +Reframed after §13/§14, because the earlier wording ("NAN is espressif-silicon-only in practice") conflated two very different barriers. + +| | What it needs | Who is blocked, and by what | +|---|---|---| +| **NAN-USD** | Nothing special. A publish is an ordinary **Public Action vendor-specific management frame** (`04 09 50:6f:9a 13 …`), plus remain-on-channel. `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES`. | Nobody, at the silicon level. Every blocker is a **driver or host-protocol exposure** gap: `cyw43-driver` exposes no action-frame TX/ROC path, `nina-fw`'s command set is frozen, ESP-Hosted's `rpc_v2.proto` carries no NAN RPC. | +| **NAN-Sync** | TSF/cluster scheduling, several concurrent RX addresses (NMI + NDI + cluster BSSID), slot-based TDMA. Gated by `SOC_WIFI_NAN_SUPPORT`. | esp32, esp32s2, esp32c5, esp32c61, esp32s31 only — but see §14.2a: that gate is Espressif's declaration, not a demonstrated silicon limit. | + +The practical consequence is more hopeful than v3 implied: **the platforms that cannot do Wi-Fi Aware are mostly blocked by software they do not expose, not by radios that cannot do it.** ESP-Hosted is the tractable one — extending `rpc_v2.proto` is additive, and the co-processor is NAN-capable ESP32 silicon. AirLift sits on the same silicon but a frozen Arduino-era firmware. CYW43 would need action-frame plumbing the driver does not have, though Infineon's own WHD carries NAN event definitions under `COMPONENT_WIFI6`. + +None of that is work worth starting while USD discovery is broken on the one backend we *can* test (§13.2a). It does mean the ceiling is higher than "espressif only" if that defect is fixed. + +--- + +## 13. Hardware results (rpi-hil006) + +Built from CircuitPython's own pinned IDF (`v6.1-dev-6096`) and flashed to real boards. Both boards' original flash was backed up first (4 MB each, under `~/usd-test/backup/`). + +**USD runs on the STA interface — confirmed on hardware, not just from source.** `usd_subscriber` on a classic ESP32: + +``` +I (658) wifi:mode : null +I (658) wifi:mode : sta (e8:9f:6d:32:50:04) +I (658) nan_app: NaN-USD Started +I (668) nan_app: Started Subscribing to ESP-USD-TEST [Service ID - 1] +``` + +This corroborates `nan_app.c:2986`. It was the basis for expecting STA coexistence — and §13.1 shows that expectation was wrong once the board is actually *associated*. + +### 13.1 USD and an associated STA — the first, flawed run + +The decisive experiment. Purpose-built firmware (not the stock examples): associate to a WPA2 AP, confirm an IP, *then* call `esp_wifi_nan_usd_start()`, and log association state, home channel and a real DNS lookup every 5 s. Run on both boards simultaneously, 100 s. + +ESP32-S3, abridged: + +``` +I (2712) coex: PRE-USD: associated ssid= ch=1 rssi=-68 bssid=ec:fc:2f:83:dc:d8 +I (2712) coex: GOT_IP 192.168.1.203 +I (2712) coex: esp_wifi_nan_usd_start() = ESP_OK +I (2712) coex: mode after usd_start = STA +I (2722) coex: [t= 0s] home_channel=1 +I (2722) coex: publish: chan=6 ... +I (7722) coex: [t= 5s] home_channel=6 <-- radio leaves the AP's channel +I (10982) coex: wifi_event id=21 <-- STA_BEACON_TIMEOUT +W (29722) coex: [t= 20s] DNS FAIL err=202 (6999ms) +W (39722) coex: [t= 30s] mode=STA NOT-ASSOC ip=192.168.1.203 disc=0 +``` + +**The two boards did *not* behave identically** — a claim this section wrongly made before review. Per board: + +| | ESP32-S3 (publisher) | classic ESP32 (subscriber) | +|---|---|---| +| Home channel | 6 for the whole run | 6 for 13 of 16 samples, back to 1 at t=25 s and t=35 s | +| Beacon timeouts | 3 | 5, every ~10 s | +| Association | **lost at 35.8 s** (`ap_probe_send over, reset wifi status to disassoc`, `run -> init`) | **held for the full 75 s** — never once `NOT-ASSOC` | +| `STA_DISCONNECTED` | never delivered; stale IP kept | n/a | + +So the honest result is **"publisher-on-S3 lost the link; subscriber-on-ESP32 was degraded but survived"**, with role and chip confounded (one run each). The likely mechanism is airtime, not chip: the publisher transmits ~5×/s on the USD channel while the subscriber only remains-on-channel ~1×/s, so the publisher spends far more time away from the AP. + +### 13.1a Resolved: it was the channel, not USD + +The above was run with USD pinned to **channel 6** (left over from the §13.2 discovery debugging) while the AP was on **channel 1**. Review flagged that as a confound I had introduced, so I re-ran it with the harness reading `esp_wifi_sta_get_ap_info()->primary` after association and pinning USD to **the AP's own channel**: + +``` +coex: PRE-USD: associated ssid=free4all ch=1 ... +coex: USD channel = 1 (FOLLOWING THE AP) +coex: [t= 0s] home_channel=1 ... coex: [t= 40s] home_channel=1 +``` + +| over 100 s | publisher (S3) | subscriber (ESP32) | +|---|---|---| +| Home channel | **1 throughout** — never leaves the AP | **1 throughout** | +| `NOT-ASSOC` samples | **0** | **0** | +| Beacon timeouts | 1 | 7 | + +**Both boards stayed associated for the entire run.** Compare the ch6 run, where the publisher lost its association at 35.8 s. + +**So "USD is a radio-owning mode" is wrong, and §0 said so on my evidence alone.** USD does not inherently take the radio; *USD pinned to a channel other than the AP's* does, because one radio cannot be in two places. Put USD on the AP's channel and STA survives. + +What survives from §13.1 is narrower but still worth having: + +* When USD *does* go off-channel, the link dies **silently** — no `STA_DISCONNECTED`, stale IP retained. That remains the API-relevant hazard. +* A CircuitPython USD binding should therefore **default `usd_default_channel` / `usd_chan_bitmap` to the associated AP's channel**, and only allow a different channel when no STA is up (or make the cost explicit). That is a concrete, cheap API rule that this experiment produced. +* The cost of staying on the AP's channel is that discovery only reaches peers that happen to use that channel — a real limitation for an AP-less use case, but irrelevant when the device is associated anyway. + +| Observation | Consequence | +|---|---| +| Mode stays `WIFI_MODE_STA` across `usd_start` | The *mode* claim in §3.1 holds — but mode is not the whole story | +| `home_channel` moves 1 → 6 and **stays** there | The single radio is parked on the USD channel; the AP link is abandoned | +| `WIFI_EVENT_STA_BEACON_TIMEOUT` (id 21) repeatedly | Firmware knows beacons are being missed | +| `getaddrinfo` goes from failing in ~25 ms to timing out at ~7 s | Queries are now going unanswered rather than being refused — see the caveat below | +| `esp_wifi_sta_get_ap_info()` → `NOT_CONNECT` by t=30 s | Association genuinely lost | +| **`disc=0` — no `STA_DISCONNECTED` ever fires** | The application is never told. `esp_netif` keeps the stale IP (`192.168.1.203`) and the socket layer keeps answering as if connected | + +**Caveat on the DNS numbers, found later (§14).** The test AP has no working resolver: on a *healthy* STA link `getaddrinfo` already fails, immediately (~25 ms, `err=202`). So DNS failure alone is not proof that USD killed traffic. What does change under USD is the *shape* of the failure — ~25 ms refusal becomes a ~7 s timeout, i.e. queries stop being answered at all. The load-bearing evidence for this section is therefore the unambiguous radio-level facts: the home channel moving to 6 and staying, repeated `STA_BEACON_TIMEOUT`, and `esp_wifi_sta_get_ap_info()` returning `NOT_CONNECT`. Those do not depend on the AP's resolver. + +> ~~**This changes the design.** USD cannot be a quiet background service alongside `wifi.radio.connect()`; it is a radio-owning mode and the entry point belongs on `wifi.radio`.~~ +> +> **Superseded by §13.1a.** That conclusion was drawn from this run alone, and this run had USD pinned to a channel the AP was not on. The mitigation this paragraph suggested "testing later" turned out to be the whole story: pin USD to the AP's channel and the problem disappears. Kept here because the logs remain the evidence for the *silent* failure mode, which is real and still matters. + +### 13.2 Discovery never completes — publisher is correct, subscriber is deaf + +Across every configuration tried, **no `WIFI_EVENT_NAN_SVC_MATCH` ever fires.** Ruled out, each by direct measurement: + +| Hypothesis | Test | Result | +|---|---|---| +| Channel mismatch | Both pinned to ch 6 via `usd_chan_bitmap` | both confirm `ch=6`; no change | +| Boards started at different times / TTL expiry | Simultaneous reset (<400 ms apart), TTL 600 s | no change | +| World-mode regulatory block on TX | `set_country("GB", MANUAL)`; was `cc=01 nchan=11` | accepted; no change | +| Power save sleeping through frames | `esp_wifi_set_ps(WIFI_PS_NONE)` | no change | +| Transmission failing | Log `WIFI_EVENT_ACTION_TX_STATUS` | `status=0` then `2` (started → duration-completed), **never `FAILED`** | +| Receiver off-channel | Log `WIFI_EVENT_ROC_DONE` + `esp_wifi_get_channel()` | ROC on ch 6 every 1 s, `status=0`, home channel 6 throughout | +| Chip- or direction-specific bug | Swap roles: ESP32 publishes, S3 subscribes | **still zero matches both ways** | + +**One row removed after review: setting `.type` was a no-op.** The public `.type` field is never read on the USD path — `esp_nan_usd.c` uses fixed defaults from `esp_private/esp_nan_usd.h`: `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, .solicited = true`. That test changed nothing, so it ruled nothing out. (It does, however, mean the effective config — unsolicited publisher, passive subscriber — is a combination that *should* match, which argues against misconfiguration.) + +Then the frames were captured off the air. The classic ESP32 was temporarily reflashed as a promiscuous sniffer on channel 6 while the S3 published: + +``` +sniff: VSA src=f4:12:fa:59:64:84 dst=51:6f:9a:01:00:00 bssid=51:6f:9a:01:00:00 + oui=50:6f:9a type=13 rssi=-58 ch=6 len=62 + 04 09 50 6f 9a 13 | 03 09 00 be7d08e9ddb7 01 00 00 | 0e 0d 00 01 01 00 0800 "PUBHELLO" +``` + +Decoded: Public Action (`04`), Vendor Specific (`09`), WFA OUI `50:6f:9a`, **OUI type `0x13` = NAN SDF**; then a Service Descriptor Attribute (`0x03`, service-ID hash `be7d08e9ddb7`, instance 1) and a Service Descriptor Extension Attribute (`0x0e`) carrying the 8-byte payload. Repeating roughly every 150 ms at −58 dBm. + +**So the publisher is fully correct and the RF link is fine** — the same board, same antenna, hears the frames perfectly in promiscuous mode. The failure is squarely in the USD **receive/match** path. + +#### 13.2a The defect, localised + +Two further experiments pin it down exactly. + +**(1) The discovery engine is never called.** `wpa_printf()` maps to `ESP_LOG_LEVEL_LOCAL(level, "wpa", …)`, and `nan_de.c:1271` logs `NAN: RX SDF from …` at `MSG_DEBUG` immediately after the function's only early return. Raising that tag to `ESP_LOG_DEBUG` at runtime gives a clear **positive control** — the engine does log: + +``` +D (785) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST <-- subscriber +D (343) wpa: NAN: Publish in single channel state for 900 TU; ... <-- publisher +D (1273) wpa: NAN: TX wait for response ended (freq=2437) +``` + +and **`NAN: RX SDF from` never appears, not once.** `nan_de_rx_sdf()` is never entered. + +**(2) The frames do arrive at the receiver's own NIC.** Running the subscriber with promiscuous mode enabled *alongside* its USD subscribe, counting Public-Action/WFA/OUI-type-`0x13` frames: + +``` +coex: promisc on = ESP_OK +coex: [t= 60s] promisc NAN SDFs seen = 407 +``` + +**407 NAN SDFs received by the subscriber's own radio, and zero delivered to the USD engine.** + +That is conclusive and leaves no room for misconfiguration: the frames are transmitted correctly, reach the right board on the right channel, are demodulated by its NIC — and the closed Wi-Fi blob never hands them to the action-frame callback the USD engine registered via remain-on-channel. The open `nan_de.c` code is not at fault; it is simply never called. + +It also **weakens my own A1/A3 address-filter hypothesis**: enabling promiscuous mode (which opens the hardware address filter) did not make discovery work. Promiscuous delivery is a separate path from the ROC `rx_cb`, so this does not strictly refute the theory — but the mechanism is no longer something I can determine from outside the blob, and the bug report does not need it. + +**This is now fileable**, with a minimal reproducer that needs no NAN code at all: call `esp_wifi_remain_on_channel()` with an `rx_cb` and `allow_broadcast=true` while another board publishes, and show the callback never fires for frames a promiscuous sniffer on the same board counts in the hundreds. + +Most likely cause, not yet proven: the frames are addressed to the NAN Network ID `51:6f:9a:01:00:00` in both **A1 and A3**. That is a multicast address that is not broadcast, so a STA-mode hardware RX filter will drop it unless the receiver's BSSID filter has been set to the NAN Network ID. In NAN-Sync the device joins the cluster and that filter is set; on the USD path over a plain STA interface it appears not to be. + +**A competing explanation, equally plausible:** the Wi-Fi blob at this pin (`e12a754`) has as its HEAD commit *"fix(nan): Fix bug bounty reported and discovered vulnerabilities in NAN Rx"* (2026-07-14). A hardening regression in the RX path fits the evidence just as well as a filter that never worked. + +*(A previous version of this section offered "the subscriber never transmits either" as corroboration. It is not: the subscriber is passive by construction — see the `.active = false` default above — and only transmits a follow-up after receiving a publish. Zero `ACTION_TX` is the same fact as zero matches, not independent evidence.)* + +**Before filing upstream**, two cheap tests would make this decisive: (1) enable promiscuous mode with the MGMT filter on the subscriber while USD runs — if `SVC_MATCH` starts firing, the hardware filter is confirmed; (2) build with `CONFIG_WPA_DEBUG_PRINT=y` (off in my builds, which is why the verbose logging in run p2 showed nothing — the discovery engine logs via `wpa_printf`) and look for `NAN: RX SDF from`. Its absence proves the callback is never entered. + +**A portability quirk worth recording:** the ESP fork puts service-specific info on the wire raw, whereas upstream hostap prepends the WFA OUI and protocol type and requires them on receive. So "the publisher is fully correct" should read **"correct for ESP peers"** — a hostap/Zephyr/Android peer would discard that SSI. §7.1's `ssi=b"t=21.5"` inherits this. + +**Status: NAN-USD on ESP-IDF `v6.1-dev-6096` transmits but does not discover.** It is an experimental feature behind `CONFIG_IDF_EXPERIMENTAL_FEATURES`, and this looks like an upstream defect worth reporting. Until it is fixed, **USD cannot be the foundation of a CircuitPython `wifiaware` module** — which, combined with §13.1, is the single most important result of the hardware work. + +### 13.3 What this does to the plan + +* §8 (**DNS-SD browser in `shared-module/`**) is untouched by any of this and is unambiguously the right first step. No hardware risk, no upstream dependency, serves every port with sockets. +* The `wifiaware` module (§7.1) should **not** be started on USD against this IDF — not because USD is the wrong protocol, but because its receive path is broken (§13.2a). +* NAN-Sync was subsequently tested and works end to end: see §14. + +### 13.4 Reproduction + +All test firmware is in the session scratchpad. `coex_pub/` + `coex_sub/` is the main harness, with four build switches: `-DROLE_PUB=` (publish vs subscribe), `-DCOEX_WITH_STA=` (join an AP first), `-DUSD_PROMISC=` (run promiscuous RX alongside USD, for §13.2a) and `-DUSD_FIXED_CHAN=` (the fallback channel when no AP is associated; with one, it follows the AP). `swap_pub32/` + `swap_subs3/` is the role swap, `sniff/` the standalone promiscuous NAN SDF sniffer, `synccoex/` the four-phase Sync-vs-STA probe. Logs are on the Pi under `~/usd-test/{coex,sync,synccoex,apchan,diag}/`, and copied locally under `hil-logs/` with a manifest. Both boards' original 4 MB flash images are in `~/usd-test/backup/`. + +Board notes: the QT Py ESP32-S3 needs `CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y`, since UART0 is not wired to USB; and with native USB it re-enumerates under a different `/dev/serial/by-id` name in ROM download mode, which breaks naive by-id addressing in scripts. Serial capture needs a DTR/RTS reset toggle before any output appears. + +--- + +## 14. NAN-Sync hardware results — it works + +Tested after §13, on the two rig boards that actually have NAN silicon: **classic ESP32** (publisher) and **ESP32-S31** (subscriber). Stock IDF examples, security disabled, active subscribe, datapath + IPv6 ping enabled. + +First, a build-level signal that was missed earlier: **Sync is not an experimental feature.** It needs only `CONFIG_ESP_WIFI_NAN_SYNC_ENABLE=y`. USD additionally requires `CONFIG_IDF_EXPERIMENTAL_FEATURES` (§3.1), and §13.2 shows why. + +### 14.1 Full sequence, measured + +Subscriber (ESP32-S31): + +``` +I (265) wifi:mode : NAN (1e:29:04:81:b5:97) +I (3345) NAN: Start own Cluster, Id 50:6f:9a:01:db:dd +I (3345) nan_app: Started Subscribing to ESP-SYNC-TEST [Service ID - 5] +I (4395) nan_app: Service matched with ea:9f:6d:c6:e9:16 [Peer Publish id - 5] +I (4925) wifi:NDL for Peer ea:9f:6d:c6:e9:16 ch6: ndc=[2,2] crb1=[3,16] crb2=[0,0] +I (4925) nan_app: NDP confirmed [NDP ID - 1, Peer IPv6 - FE80::E89F:6DFF:FEC6:E916] +I (10215) subscriber: 64 bytes from FE80::E89F:6DFF:FEC6:E916 icmp_seq=1 ttl=0 time=292 ms +I (11925) subscriber: 64 bytes from FE80::E89F:6DFF:FEC6:E916 icmp_seq=3 ttl=0 time=2 ms +--- FE80::E89F:6DFF:FEC6:E916 ping statistics --- +5 packets transmitted, 5 received, 0% packet loss, time 300ms +``` + +The publisher independently confirms the same NDP from its side, and logs `NAN: Join Cluster with Id ...` rather than starting its own — the two devices genuinely formed one cluster. + +| Milestone | Time from boot | +|---|---| +| `WIFI_MODE_NAN` up | 0.27 s | +| Cluster formed | 3.35 s | +| **Service matched** | **4.40 s** | +| **IPv6 datapath confirmed (NDP)** | **4.93 s** | +| First ICMPv6 reply | 10.2 s (example waits 5 s deliberately) | +| Steady-state RTT | **2 ms**, 0 % loss | + +**This is a working, AP-less, DHCP-less IPv6 transport with real sockets on it** — exactly what issue #18 asks for, and the thing USD can never provide even when fixed (USD has no datapath at all). + +### 14.2 What it costs + +* **Exclusive radio mode, confirmed on hardware.** The log reads `wifi:mode : NAN`, a mode distinct from STA/AP, with its own **NAN Management Interface MAC**. That MAC is **randomised at every start** — only the OUI is derived (`e8:9f:6d` → `ea:9f:6d`, locally-administered bit set); the low three bytes differ on every boot (`c6:e9:16`, `80:3e:81`, `83:f6:00`, `ea:1b:bc` across four runs). **Consequence: the peer's datapath link-local IPv6 changes on every wake**, since it is the EUI-64 of that MAC — a real problem for a deep-sleeping collector, and one §7 has not accounted for. `disable_random_mac` / NVS caching exist in `wifi_nan_sync_config_t`; neither was tested. This corroborates `nan_app.c:2003`/`:2057` from §3.1. Note §13.1 showed USD imposes effectively the same cost in practice while pretending not to — so exclusivity is no longer a discriminator between the two. +* **`SOC_WIFI_NAN_SUPPORT` required** — set only for **esp32, esp32s2, esp32c5, esp32c61, esp32s31**, excluding the ESP32-S3 and the C3/C6 parts a great many CircuitPython boards use. Whether that reflects silicon is a separate question; see §14.2a. +* The datapath IPv6 is a **link-local address derived from the peer's NMI as an EUI-64**, so anything using it needs scope/zone handling — see §7.3. + +### 14.2a Is `SOC_WIFI_NAN_SUPPORT` a hardware limit? Probably not. + +Earlier drafts wrote "needs NAN silicon" and called Sync's exclusivity a hardware cost. Neither is justified, and the distinction matters: it turns the S3/C3/C6 exclusion from a law of physics into something reasonable to ask Espressif about. + +What `SOC_WIFI_NAN_SUPPORT` actually is: a macro in each chip's `soc_caps.h` — Espressif's declaration of what their Wi-Fi firmware supports on that part. It gates exactly one Kconfig symbol, `ESP_WIFI_NAN_SYNC_ENABLE`. Since the Wi-Fi MAC firmware is a closed blob, nothing outside it can distinguish "the block isn't there" from "we didn't implement it for this lineage". + +Evidence that it is a product decision rather than silicon: + +* **The chip list has the wrong shape.** ESP32 (2016) ✓, S2 ✓, S3 ✗, C3 ✗, C6 ✗, then C5 ✓, C61 ✓, S31 ✓. A physical block does not vanish for a generation and return. +* **The C6 is the awkward case.** It has `SOC_WIFI_HE_SUPPORT` — Wi-Fi 6, including TWT's negotiated scheduled wake windows, the same class of machinery NAN's Discovery Windows and NDL slot bitmaps need, and the IDF event enum carries `ITWT_SETUP`/`BTWT_SETUP`/`TWT_WAKEUP` to show the stack drives it. Yet no NAN. +* **Two timing domains on one radio already ship.** It is tempting to argue a station's TSF is slaved to its AP so a NAN cluster's timebase cannot coexist — but CircuitPython's own port sets `WIFI_MODE_APSTA` (`ports/espressif/common-hal/wifi/Radio.c:50`), where the softAP beacons its own TSF while the STA follows the upstream AP's. So "one counter cannot follow two sources" is not an available argument. +* **Other vendors ship NAN concurrently with STA.** Android phones run Wi-Fi Aware while associated as a matter of course; the spec permits concurrency and vendor firmware decides. + +The one genuinely hardware-shaped question left is the number of concurrent VIF slots, TSF counters and RX address filters — Sync wants NMI + NDI + cluster BSSID, which on top of an active STA might exceed them. That is a real question, but it is a question, not a known. + +**What survives regardless:** `nan_app.c:2003` forces `WIFI_MODE_NAN`, and `wifi_mode_t` has no combined NAN+STA value (`esp_wifi_types_generic.h:27-32`). Whether that is silicon or a product decision, CircuitPython cannot flip it — so the API conclusion (Sync owns `wifi.radio`) holds either way. + +### 14.3 The architectural consequence + +v2 §0 proposed building on USD because "both backends can do it" — espressif and zephyr-cp converging on USD. The hardware says that convergence is **on the one thing that does not work**: + +| | espressif (pinned IDF) | zephyr-cp (pinned Zephyr) | +|---|---|---| +| NAN-Sync | **works, datapath and all** (§14.1) | not available | +| NAN-USD | transmits, never discovers (§13.2) | **untested** — and reaches at most one board (below) | + +Two things weaken this table, both in the direction of "I know less than I implied": + +* **The zephyr column is unknown, not broken.** I tested no Zephyr USD at all. And "same hostap `nan_de` lineage" cuts *against* transferring the ESP result: the open `nan_de` code reads correctly, and the ESP defect appears to be in the closed blob — so the ESP failure predicts nothing about Zephyr. +* **Zephyr USD is barely available anyway.** hostap USD needs a driver exposing `remain_on_channel`/`send_action`; in the Zephyr tree only `nrf_wifi`, `nxp` and `hwsim` have them — not the Infineon AIROC driver behind Pico W / Pico 2 W. With `hal_espressif` blocklisted in `west.yml`, that leaves `frdm_rw612`, which has no hostap/NAN config today. +* **One IDF snapshot.** USD is experimental, at a `-dev` pin, possibly broken by a dated hardening commit. That is a "re-test at the next IDF bump" item, not a permanent architectural fact. + +So **there is no common working denominator today.** A portable `wifiaware` module cannot be built on USD (broken here) or on Sync (absent there, and silicon-limited). Any Wi-Fi Aware work in CircuitPython is therefore **espressif-only and Sync-based** for now, which is precisely the §7.2 shape — a port-specific module that owns the radio, not a portable one. + +That reinforces, rather than weakens, the §8 conclusion: **DNS-SD first**. It is the only part of issue #18 that is portable *and* working. + +### 14.4 Sync vs STA — measured, and it behaves *well* + +A purpose-built four-phase probe on the classic ESP32: bring STA up, start Sync on top of it, exercise STA while Sync runs, then stop Sync and try to recover. + +``` +PHASE A [A/after-sta] mode=STA sta=ASSOC chan=1 ip=192.168.1.143 disc=0 +PHASE B *** STA_DISCONNECTED reason=8 (#1) *** <-- fires immediately + ### NAN_CLUSTER_JOIN ### ### NAN_SYNC_STARTED ### + nan_sync_start() = ESP_OK + [B/after-nan-start] mode=NAN sta=ESP_ERR_WIFI_CONN chan=6 ip=0.0.0.0 disc=1 +PHASE C publish_service while NAN = id 5 <-- NAN genuinely usable + esp_wifi_connect() while NAN (no set_mode) = ESP_ERR_WIFI_MODE +PHASE D nan_sync_stop() = ESP_OK + [D/after-nan-stop] mode=NAN ... <-- stop does NOT restore the old mode + set_mode(STA)/start/connect -> STA recovery: RECOVERED in 1.5 s +``` + +`esp_wifi_nan_sync_start()` unconditionally calls `esp_wifi_set_mode(WIFI_MODE_NAN)` (`nan_app.c:2003`) with no check for a live STA, and `esp_wifi_nan_sync_stop()` calls `esp_wifi_stop()` (`:2058`). So Sync does take the radio — **but it takes it honestly**, and that is the whole difference from §13.1: + +| | NAN-USD (§13.1) | NAN-Sync (§14.4) | +|---|---|---| +| Mode reported after start | stays `STA` — misleading | `NAN` — accurate | +| `STA_DISCONNECTED` delivered | **never** | **yes, `reason=8`, immediately** | +| `esp_netif` IP | **stale address retained** | **cleared to `0.0.0.0`** | +| STA API while active | appears to work, silently dead | `esp_wifi_connect()` → **`ESP_ERR_WIFI_MODE`** | +| Recovery | n/a | `nan_sync_stop()` → `set_mode` → `connect`: **1.5 s to a new IP** | + +**This is a mode CircuitPython can model honestly.** Every transition is observable: the disconnect event fires, the address is dropped, misuse is refused with a real error code, and teardown is fast and complete. That is precisely what `wifi.radio` needs in order to keep `started`/`sta_mode`/`ap_mode` truthful (§7.2) — and precisely what USD does *not* give. + +Two sharp edges for the binding to handle: + +* **`esp_wifi_set_mode(WIFI_MODE_STA)` while Sync is running silently stops NAN.** Observed directly: `NAN_SYNC_STOPPED` fired on the `set_mode` call, and a subsequent `esp_wifi_nan_publish_service()` returned id `0`. The clobber is not symmetric — `connect()` under NAN is refused, but a mode change under NAN is not. Nothing but the binding can prevent user code from doing this. +* **`esp_wifi_nan_sync_stop()` leaves the mode at `NAN`.** The caller must restore STA explicitly; the stop alone leaves the radio in a state with no station and no NAN. + +*(Method note: the first run of this probe put `set_mode(STA)` before the publish in Phase C, which silently stopped NAN and invalidated Phases C and D — `nan_sync_stop()` then returned `ESP_FAIL` simply because NAN was already stopped. Reordered and re-run; the numbers above are from the corrected run. The discarded run is what revealed the silent-clobber edge above.)* + +### 14.5 Still open + +* **Validate the DNS-SD browser against a real responder.** It builds and its parser is unit-tested and fuzzed, but no packet of its has met an Avahi/mDNSResponder instance. Nothing should be built on it until that happens. +* **zephyr-cp's `advertise_service()` half**, plus enabling `mdns` there at all. The browser side is ready and the build wiring now emits `CIRCUITPY_MDNS_SHARED` when the port has no `common-hal/mdns`, but that path is unverified — no zephyr board on this rig. + +* **Secured NDP and pairing** (`ESP_WIFI_NAN_SECURITY`, `ESP_WIFI_NAN_PAIRING`) — untested, gated on `IDF_EXPERIMENTAL_FEATURES`, and the prerequisite for any phone interop. iOS vs Android is reportedly a compile-time choice. +* **NMI randomisation vs deep sleep** (§14.2): the peer IPv6 moves every boot unless `disable_random_mac` or NVS caching is used. Untested, and it shapes the API. +* **Flash/RAM cost** of enabling NAN-Sync on classic ESP32 and ESP32-S2 CircuitPython builds — unmeasured, and ESP32-S2 alone is ~56 boards. +* **The ESP32-S31 is a preview target** with no CircuitPython boards; the Sync result rests on a chip we do not ship. +* **An oddity to resolve before a binding exposes it:** in `t3-pub.log` the publisher prints its *own* EUI-64 as "Peer IPv6". The responder-side address in the NDP-confirm event may not be trustworthy. +* **`esp_wifi_nan_sync_start()` blocks for ~3 s** (5682 → 8692 ms in `run2.log`), of which 3.0 s is the default `scan_time`. A binding must keep background tasks running across that, and the 4.9 s figure is tunable rather than a floor. +* Secured NDP (`ESP_WIFI_NAN_SECURITY`, PMK/passphrase, ND-GTK) untested — and it is what iOS/Android interop will require. +* Power cost of cluster membership across deep sleep: unmeasured, and it is the crux of issue #18. A 4.9 s boot-to-datapath is already a meaningful number to weigh against ESP-NOW. + +### 14.6 Bench notes (cost me real time) + +* **`pyserial` asserts DTR and RTS on `open()`.** On an ESP32-S3/S31 native USB-JTAG CDC that reboots the part into the bootloader, so the console goes silent and looks like a dead firmware. Build the port object and set `dtr`/`rts` `False` *before* `open()`: + ```python + s = serial.Serial(); s.port = p; s.baudrate = 115200 + s.dtr = False; s.rts = False + s.open() + ``` + Every "no output" dead end in §13–§14 traced back to this. +* Resetting an S31 drops its native USB off the bus, so a capture must re-attach *after* re-enumeration. +* `esp32s31` needs `idf.py --preview set-target`, flashes with **`--no-stub`**, and its **bootloader goes at `0x2000`** (not `0x0`/`0x1000`). +* The CP2102N bridge on the S31 board is unreliable — it stops answering USB control transfers (`cp210x: failed set request 0x0 status: -110`) and only a host reboot brings it back. From df1672a4485f3cbfcb686d7eff16641ca4882c5c Mon Sep 17 00:00:00 2001 From: Tyeth Gundry Date: Mon, 23 Nov 2026 18:58:36 +0000 Subject: [PATCH 03/30] mdns: fix the shared browser on espressif Zero the browser's stack socketpool and socket before use. On espressif, socketpool_socket() leaves ssl_socket and connected unset, and socketpool_socket_close() treats a non-NULL ssl_socket as an SSL socket to close, so stack garbage there crashed find() intermittently (LoadProhibited in common_hal_ssl_sslsocket_close). Add a no-op mdns_server_deinit_singleton(). espressif's common_hal_wifi_radio_set_enabled() calls it unconditionally, so builds with CIRCUITPY_MDNS_SHARED=1 failed to link without it. The browser keeps no state between find() calls, so there is nothing to tear down. Tested on a Lolin S2 Mini (60 find() calls across a hard reset and three soft reloads, no crash) and a SparkFun ESP32 Thing. Co-Authored-By: Claude Opus 5.5 --- shared-module/mdns/Browser.c | 9 +++++++-- shared-module/mdns/Server.c | 6 ++++++ shared-module/mdns/Server.h | 5 +++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/shared-module/mdns/Browser.c b/shared-module/mdns/Browser.c index 4d0f08e2fec..0f1f0188a17 100644 --- a/shared-module/mdns/Browser.c +++ b/shared-module/mdns/Browser.c @@ -378,11 +378,16 @@ size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_t return 0; } - socketpool_socketpool_obj_t pool; + // Zero both objects: they live on the C stack, and socketpool_socket() does + // not set every field. On espressif it leaves ssl_socket and connected alone + // (heap and static sockets are already zeroed), and socketpool_socket_close() + // treats a non-NULL ssl_socket as an SSL socket to close, so stack garbage + // there crashed the board in close(). + socketpool_socketpool_obj_t pool = { 0 }; pool.base.type = &socketpool_socketpool_type; common_hal_socketpool_socketpool_construct(&pool, network_interface); - socketpool_socket_obj_t sock; + socketpool_socket_obj_t sock = { 0 }; if (!socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_DGRAM, 0, &sock)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); } diff --git a/shared-module/mdns/Server.c b/shared-module/mdns/Server.c index 4bcb8095662..42d262972ae 100644 --- a/shared-module/mdns/Server.c +++ b/shared-module/mdns/Server.c @@ -66,6 +66,12 @@ void common_hal_mdns_server_deinit(mdns_server_obj_t *self) { self->inited = false; } +void mdns_server_deinit_singleton(void) { + // find() opens and closes its own socket, so nothing outlives a call and + // there is nothing to tear down when the radio stops. espressif's + // common_hal_wifi_radio_set_enabled() calls this unconditionally. +} + bool common_hal_mdns_server_deinited(mdns_server_obj_t *self) { return !self->inited; } diff --git a/shared-module/mdns/Server.h b/shared-module/mdns/Server.h index 3c81ec0f8ea..398f43b8bc6 100644 --- a/shared-module/mdns/Server.h +++ b/shared-module/mdns/Server.h @@ -27,3 +27,8 @@ typedef struct { bool workflow; bool inited; } mdns_server_obj_t; + +// Called by a port's wifi code before the radio stops, as the native +// responders need. The browser holds no state between find() calls, so it has +// nothing to release; it exists so those ports still link with the browser. +void mdns_server_deinit_singleton(void); From 9446b6ef824bc08302083f1470b07d8f903f2f46 Mon Sep 17 00:00:00 2001 From: Tyeth Gundry Date: Mon, 23 Nov 2026 19:04:52 +0000 Subject: [PATCH 04/30] mdns: repeat the browse query; correct the unicast-reply comment Multicast on Wi-Fi gets no link-layer retries, so a single PTR query or a reply to it is easily lost. Repeat the query at 1 s, 3 s, 7 s, ... for as long as the timeout allows (RFC 6762 Section 5.2 spacing). Responders answer again and get_entry() merges the duplicates by instance name. The header comment said responders may multicast their answer instead. For a query from a port other than 5353, RFC 6762 Section 6.7 requires a unicast reply to that port, which is what every responder tested did. Co-Authored-By: Claude Opus 5.5 --- shared-module/mdns/Browser.c | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/shared-module/mdns/Browser.c b/shared-module/mdns/Browser.c index 0f1f0188a17..015e641f50f 100644 --- a/shared-module/mdns/Browser.c +++ b/shared-module/mdns/Browser.c @@ -9,13 +9,16 @@ // those with a native mDNS library. // // This is a "one-shot multicast DNS query" in the sense of RFC 6762 Section 5.1: -// the query goes out from an ephemeral port with the unicast-response (QU) bit -// set, so responders reply directly to us and we never have to join the -// 224.0.0.251 multicast group. That matters because socketpool exposes -// IP_MULTICAST_TTL but has no IP_ADD_MEMBERSHIP, so a group-joining browser is -// not portable today. The cost is that responses a responder chooses to -// multicast instead (RFC 6762 Section 5.4 permits this when it has not answered -// recently) are missed; a repeat find() generally picks them up. +// the query goes to 224.0.0.251 from an ephemeral port. Because that source +// port is not 5353, RFC 6762 Section 6.7 requires responders to answer by +// unicast straight back to it, so we never have to join the multicast group or +// share port 5353. That matters because socketpool exposes IP_MULTICAST_TTL but +// has no IP_ADD_MEMBERSHIP, so a group-joining browser is not portable today. +// The unicast-response (QU) bit is set as well; it asks for the same thing. +// +// Multicast on Wi-Fi gets no link-layer retries, so the query or a reply is +// easily lost. find() therefore repeats the query for as long as its timeout +// allows, at the intervals RFC 6762 Section 5.2 sets for repeated queries. // The portable DNS-SD browser. @@ -58,6 +61,10 @@ // and anything truncated is simply re-queried by calling find() again. #define MDNS_PACKET_SIZE (1460) +// When to repeat the PTR query: 1 s after the first, then with the gap doubling +// each time (RFC 6762 Section 5.2 requires at least 1 s between the first two). +#define MDNS_FIRST_REPEAT_MS (1000) + // How long to wait between polls of the socket while a browse is running. #define MDNS_POLL_INTERVAL_MS (10) @@ -439,10 +446,24 @@ size_t shared_module_mdns_find(mp_obj_t network_interface, const char *service_t // chasing those the browse returns entries with port 0 and no address, // which looks like a flaky browser. Ask once, halfway through. bool chased = false; + // Repeat the PTR query at 1 s, 3 s, 7 s, ... in case the first query or + // its replies were lost. Responders answer again, and get_entry() merges + // the duplicates by instance name. + uint64_t repeat_gap_ms = MDNS_FIRST_REPEAT_MS; + uint64_t next_repeat_ms = MDNS_FIRST_REPEAT_MS; while (supervisor_ticks_ms64() - start_ticks < timeout_ms && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; uint64_t elapsed = supervisor_ticks_ms64() - start_ticks; + if (elapsed >= next_repeat_ms) { + repeat_gap_ms *= 2; + next_repeat_ms += repeat_gap_ms; + // buf holds the last packet received, so build the query again. + query_len = build_query(buf, MDNS_PACKET_SIZE, NULL, service_type, protocol, + DNS_RRTYPE_PTR); + common_hal_socketpool_socket_sendto(&sock, MDNS_MULTICAST_IPV4, + strlen(MDNS_MULTICAST_IPV4), MDNS_PORT, buf, query_len); + } if (!chased && elapsed > timeout_ms / 2) { chased = true; for (size_t i = 0; i < state.count; i++) { From 97da7334346fc66129148fc7a42924682635d591 Mon Sep 17 00:00:00 2001 From: Tyeth Gundry Date: Mon, 23 Nov 2026 19:23:08 +0000 Subject: [PATCH 05/30] espressif: treat a select() that returns 0 as a spurious wakeup socket_select_task asserted that select() with no timeout returns at least one ready socket. lwIP checks the sockets again after it wakes, so it returns 0 when the main task has already read the datagram that woke it. The shared mDNS browser does exactly that with its system socket, and DEBUG=1 builds stopped at the assert (Socket.c:111). Release builds compile the assert out and loop, so wait again explicitly instead. Co-Authored-By: Claude Opus 5.5 --- ports/espressif/common-hal/socketpool/Socket.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ports/espressif/common-hal/socketpool/Socket.c b/ports/espressif/common-hal/socketpool/Socket.c index 4c35d9bcc45..226bace803f 100644 --- a/ports/espressif/common-hal/socketpool/Socket.c +++ b/ports/espressif/common-hal/socketpool/Socket.c @@ -108,7 +108,13 @@ static void socket_select_task(void *arg) { continue; } - assert(num_triggered > 0); + // lwIP's select() checks the sockets again after it wakes, so it can + // return 0 even with no timeout: the main task has already read the + // datagram that woke it (the shared mDNS browser reads its own system + // socket, for one). Nothing is ready, so just wait again. + if (num_triggered == 0) { + continue; + } // Notice event trigger if (FD_ISSET(socket_change_fd, &readfds)) { From 54d696b1b8cccb1c2e18a0bbe896d74b5ac018fb Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 21:48:47 +0000 Subject: [PATCH 06/30] docs: ESP-IDF issue drafts for the two NAN defects, plus capture tooling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Working drafts for two ESP-IDF reports arising from the Wi-Fi Aware investigation. Neither is filed. IDF-ISSUE-1-nan-usd-rx.md — NAN-USD discovery never completes: nan_de_rx_sdf() is never called although the subscriber's own radio counts 407 NAN SDFs in 60 s. The open-source receive path in esp_nan_usd.c should pass every one of those frames, so the leading hypothesis is that the NAN Network ID 51:6f:9a:01:00:00 — multicast but not broadcast — is absent from the hardware receive filter. That is a hypothesis, not a measurement. IDF-ISSUE-1-localise.patch is the one-line diagnostic that would settle it, also pushed as tyeth/esp-idf branch nan-usd-rx-localise at the cb73317 pin. IDF-ISSUE-2-nan-ndp-availability.md — the data path with an Android peer never completes. This one separates two distinct failures. Runs 3 and 4 have a probable cause: of six ESP unicast transmission events, the two first sent at +4.2 and +9.2 ms into the Discovery Window were delivered and the four first sent at +13.1 ms or later failed, with the same boundary on and off the AP. Runs 5 and 6 are unexplained — 88 of 123 publish SDFs in run 5 landed at or before +10 ms with no firmware match at all. Four earlier explanations were proposed and discarded along the way (Potential-only availability, a 5 GHz-only offer, the negotiation having succeeded, and a simple DW-end deadline). That history is kept in the draft rather than tidied away, because each was discarded on evidence that constrains the remaining hypotheses. nan-pcap-parse.py reads the radiotap/802.11 captures without tshark and exposes the retry bit, which is what the delivery analysis rests on: the monitor was configured with WIFI_PROMIS_FILTER_MASK_MGMT and recorded no ACK frames at all. Capture, decode and three substantive corrections came from the bench session running the hardware. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-1-localise.patch | 29 +++ IDF-ISSUE-1-nan-usd-rx.md | 168 +++++++++++++ IDF-ISSUE-2-nan-ndp-availability.md | 350 ++++++++++++++++++++++++++++ nan-pcap-parse.py | 90 +++++++ 4 files changed, 637 insertions(+) create mode 100644 IDF-ISSUE-1-localise.patch create mode 100644 IDF-ISSUE-1-nan-usd-rx.md create mode 100644 IDF-ISSUE-2-nan-ndp-availability.md create mode 100644 nan-pcap-parse.py diff --git a/IDF-ISSUE-1-localise.patch b/IDF-ISSUE-1-localise.patch new file mode 100644 index 00000000000..9f70b195059 --- /dev/null +++ b/IDF-ISSUE-1-localise.patch @@ -0,0 +1,29 @@ +Subject: [PATCH] nan_usd: log entry to the action-frame Rx callback + +Diagnostic only; not a fix. NAN-USD discovery never completes because +nan_de_rx_sdf() is never called, even though the subscriber's own radio +counts 407 NAN SDFs in 60 s. Review of esp_nan_de_rx_action() shows every +gate in it should pass for those frames, so the open question is whether the +callback is entered at all. + +Never printed -> frames are dropped below the supplicant, in the Wi-Fi + libraries or the hardware Rx filter. Note that NAN SDFs + carry the NAN Network ID 51:6f:9a:01:00:00 in A1 and A3, + which is multicast but not broadcast. +Printed -> the loss is in the gate chain below, and is fixable here. + +MSG_ERROR rather than MSG_DEBUG so the result does not depend on the +reporter's configured log level. + +--- a/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c ++++ b/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c +@@ -141,6 +141,9 @@ + + int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t channel) + { ++ wpa_printf(MSG_ERROR, "NAN-USD: rx_action entered, len=%u chan=%u", ++ (unsigned)len, (unsigned)channel); ++ + struct ieee80211_hdr *rx_hdr = (struct ieee80211_hdr *)hdr; + struct nan_de *nan_de = NULL; + int freq; diff --git a/IDF-ISSUE-1-nan-usd-rx.md b/IDF-ISSUE-1-nan-usd-rx.md new file mode 100644 index 00000000000..2789a1ea91b --- /dev/null +++ b/IDF-ISSUE-1-nan-usd-rx.md @@ -0,0 +1,168 @@ +# NAN-USD: received Service Discovery Frames never reach the discovery engine + +**Status: draft, not filed.** One measurement is still outstanding — see +[What would settle it](#what-would-settle-it). + +## Summary + +With `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, a USD publisher transmits valid NAN +Service Discovery Frames and a USD subscriber's own radio receives them, but +`nan_de_rx_sdf()` is never called, so discovery never completes. Two ESP32s +configured as publisher and subscriber never discover each other, in either +role assignment. + +The subscriber's NIC counted **407 NAN SDFs** during a 60 s window in which +`nan_de_rx_sdf()` was entered zero times. + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6096` (also reproduced on `v6.1-dev-6107`, `cb73317`) | +| Targets | ESP32 (classic, rev0) and ESP32-S3 | +| Config | `CONFIG_IDF_EXPERIMENTAL_FEATURES=y`, `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y` | +| Logging | `CONFIG_WPA_DEBUG_PRINT=y` plus `esp_log_level_set("wpa", ESP_LOG_DEBUG)` | +| Regulatory | `cc=01`, resolved to `GB` MANUAL | + +Both boards publish/subscribe the service name `ESP-USD-TEST` with +`ESP_USD_PUBLISH_DEFAULT_PARAMS()` / `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()`, +pinned to channel 6, with no STA association. + +## What was measured + +**The publisher transmits correctly.** Captured off the air with an +independent ESP32 in promiscuous mode: Public Action (category `0x04`), +Vendor Specific (`0x09`), WFA OUI `50:6f:9a`, OUI type `0x13`, carrying SDA +(`0x03`) and SDEA (`0x0e`) attributes, at −58 dBm, roughly every 150 ms. +These are well-formed NAN SDFs. + +**The subscriber's radio receives them.** Running promiscuous mode alongside +the USD subscribe on the same chip, the subscriber counted 407 NAN SDFs in +60 s. + +**The discovery engine is never invoked.** `nan_de_rx_sdf()` +(`components/wpa_supplicant/src/common/nan_de.c:1271`) logs `NAN: RX SDF from` +at `MSG_DEBUG`. That line never appears. The logging is definitely live: the +positive control + +``` +D (785) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST +``` + +is emitted from the same module at the same level in the same run. + +## Ruled out by measurement + +- **Channel.** Both ends pinned to channel 6; `esp_nan_chan_to_freq(6)` + returns 2437, which is correct. +- **Receiver off-channel.** `WIFI_EVENT_ROC_DONE` fires for channel 6 about + once a second throughout. +- **Transmit failure.** `WIFI_EVENT_ACTION_TX_STATUS` never reports `FAILED`. +- **Start-time skew.** Publisher started first, subscriber first, and both + simultaneously. +- **Regulatory domain.** Channel 6 is permitted under the active domain. +- **Power save.** Disabled. +- **Chip and direction.** Roles swapped between the ESP32 and the ESP32-S3; + zero discoveries in every combination. +- **`.type` / active-vs-passive.** Not a factor, and worth stating because it + is the obvious thing to try: the USD path ignores it. + `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and + `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, + .solicited = true`, so setting it changes nothing. + +## The open-source path looks correct + +`esp_nan_de_rx_action()` +(`components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c:142`) is +registered as `rx_cb` on both the action-TX request and the remain-on-channel +request. Reviewed against the captured frames, every gate in it should pass: + +- `len < 6` — frames are far longer. +- Category `WLAN_ACTION_PUBLIC`, action `WLAN_PA_VENDOR_SPECIFIC`, OUI + `OUI_WFA`, OUI type `NAN_OUI_TYPE` — all four match the capture exactly. +- `esp_nan_chan_to_freq(6)` returns 2437, not `-1`. +- `nan_usd_try_lock_active()` fails only if the mutex is absent or `g_nan_de` + is `NULL`; the subscribe succeeded, so `g_nan_de` is set. + +The listen path at `esp_nan_usd.c:240` also sets `req->allow_broadcast = true` +on the `wifi_roc_req_t`, which is documented as what lets broadcast/multicast +action frames from any network reach the callback. + +So nothing in the supplicant explains the loss. + +## Leading hypothesis + +NAN SDFs carry the NAN Network ID `51:6f:9a:01:00:00` in both A1 and A3. The +first octet is `0x51`, whose I/G bit is set, so this is a **multicast address +but not the broadcast address**. The hardware receive filter on a STA +interface accepts frames addressed to the station's own MAC, to broadcast, and +to multicast groups it has joined. + +The hypothesis is that the NAN Network ID is not installed in the receive +filter while USD is running, so these frames are dropped in hardware before +`rx_cb` is ever reached. The `allow_broadcast` documentation explicitly +distinguishes the two cases — "frames whose Address3/BSSID is already +broadcast are always delivered" — and `51:6f:9a:01:00:00` is not broadcast. + +This fits the central observation. Promiscuous mode counts the frames because +promiscuous delivery bypasses the MAC address filter and is a different +delivery path from the management-frame callback; it does not re-enable +`rx_cb` for them. + +**This is a hypothesis, not a measurement.** It is consistent with everything +observed, but the receive filter is inside `libnet80211.a` and cannot be +inspected from source. + +## What would settle it + +One line, in open source, at the top of `esp_nan_de_rx_action()`: + +```c +int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t channel) +{ ++ wpa_printf(MSG_ERROR, "NAN-USD: rx_action entered, len=%u chan=%u", (unsigned)len, channel); + struct ieee80211_hdr *rx_hdr = (struct ieee80211_hdr *)hdr; +``` + +- **Never printed** → the frames are dropped below the supplicant, and the + receive-filter hypothesis above is the place to look. +- **Printed, but `nan_de_rx_sdf()` still not reached** → the loss is in the + open-source gate chain after all, and the specific gate is then one more log + line away. That case is fixable in this repository. + +`MSG_ERROR` rather than `MSG_DEBUG` deliberately, so the result does not +depend on the reporter's log level. + +This is already applied on a branch, based on `cb73317` so it matches the +pin currently under test: + +``` +https://github.com/tyeth/esp-idf/tree/nan-usd-rx-localise +``` + +One commit, one file, +14/−0. + +## Reproducer + +No NAN application code is required. Two ESP32s, one calling +`esp_wifi_nan_usd_start()` with a publish, the other with a subscribe, both +pinned to channel 6, with `esp_log_level_set("wpa", ESP_LOG_DEBUG)`. The +subscriber never reports a discovery. + +## Impact + +NAN-USD is non-functional for discovery on ESP-IDF today. Since +`ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` and not +on `SOC_WIFI_NAN_SUPPORT`, USD is the only Wi-Fi Aware mode available on parts +such as the ESP32-S3, and it is the only one that can run alongside a STA +association. Both properties make it the natural foundation for a portable +Wi-Fi Aware binding, and neither is usable while discovery does not complete. + +## Asks + +1. Is the NAN Network ID `51:6f:9a:01:00:00` installed in the receive filter + when USD is active on the STA interface? +2. If not, should `allow_broadcast` cover it, or is a separate multicast + subscription needed? +3. Would you take the instrumentation line above, or is there an existing way + to trace `rx_cb` delivery that we have missed? diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md new file mode 100644 index 00000000000..3d0364b72c7 --- /dev/null +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -0,0 +1,350 @@ +# NAN: data path with an Android peer never completes — NDP Response is never acknowledged + +**Status: draft, partially ready.** There are two distinct failures here and +they need separating before anything is filed. + +- **Runs 3 and 4** (data path never completes) have a probable cause: of six + ESP unicast transmission events, the two first sent at +4.2 and +9.2 ms were + delivered and the four first sent at +13.1 ms or later all failed, with the + same boundary on and off the AP. Suggestive and graded, but **two successes + is a small sample** — a deliberate offset sweep should precede filing. +- **Runs 5 and 6** (discovery itself never happens, off-AP) are + **unexplained**. The frames are correct and in-window, and the phone's + firmware reports no match. Nothing here should be filed about them. + +Asks 2 and 3 are independent of both and stand. Four earlier explanations for +the data-path failure were proposed and discarded; that history is kept in +[What is NOT established](#what-is-not-established) deliberately. + +## Summary + +An ESP32 running NAN-Sync as a publisher discovers an Android phone, exchanges +follow-up messages, and responds to its NDP Request with an **ACCEPTED** NDP +Response. That response is never acknowledged, across ten transmit attempts in +two Discovery Windows, and the phone times out after 20 s. + +The ESP also logs `Avail: missing a conditional or committed entry` while +parsing a request that demonstrably contains a conditional entry. + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Target | ESP32 (classic, rev0), `examples/wifi/wifi_aware/nan_publisher` | +| Config | `CONFIG_ESP_WIFI_NAN_SYNC_ENABLE=y`, NAN security off (open NDP) | +| Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | +| Capture | ESP32-S2 in monitor mode on channel 6 | + +ESP-to-ESP NAN-Sync on the same build works end to end: cluster 3.35 s, match +4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT, no loss. + +**Confound, see below: during every run the phone was also associated as a STA +to an AP on channel 64 (5320 MHz).** + +## Measured facts + +### The phone's NDP Request is well formed + +NAF subtype 5, `fa:b7:34:46:4c:36` → ESP NMI `26:0a:c4:5f:d3:ca`, t = 13.342 s, +−36 dBm. DevCap; `NDP{dialog=5, type/status=0x00}`; two Availability +attributes: + +- **`attr_ctrl=0x0010`, map ID 0** — one entry, **CONDITIONAL**, pref 3, time + bitmap 16 TU slots / 512 TU period / start 0 / `ffffffff` (all 32 slots), + channel entry op class 81, **channel 6**. +- **`attr_ctrl=0x0011`, map ID 1** — two **POTENTIAL** entries: op class 128 + (5 GHz, 80 MHz, chan bitmap `0x0020`, prim `0x01`), slots `000f0000`; and a + band entry "5 GHz", slots `00f000ff`. + +Then NDC (15), NDL (4), NDL-QoS (3), attr `0x1d` (81). + +The request is neither Potential-only nor 5 GHz-only. Two earlier theories +about it are dead. + +### The ESP responded ACCEPTED, and was not acknowledged + +M2 carries status `0x11` (ACCEPTED), a committed channel-6 bitmap `feffffff`, +and NDC + NDL attributes. Transmit attempts, measured from the start of the +Discovery Window (DW = 16 TU = 16.384 ms, recurring every 524 ms): + +| ESP frame | offset into DW | acknowledged? | +|---|---|---| +| SDF | +14 ms | n/a — group-addressed, never acked | +| Follow-up "Welcome" (run 3) | +9 ms | yes | +| M2, 5 tries, 13.358–13.362 | +16 to +20 ms | no | +| M2 retry, 5 tries, 13.883–13.886 | +16 to +19 ms | no | + +Phone sent NDP-Termination at 33.266 s, the 20 s timeout. + +### The spurious parse error + +``` +E (12422) wifi:Avail: missing a conditional or committed entry +``` + +Disassembly of `nan_dp_parse_availability` (`ieee80211_nan_datapath.o`, +esp32): + +``` +19e: l32i a8, a4, 0x140 +1a1: bnez.n a8, 1e1 ; usable entry found -> continue +1a5: movi a2, 0x106 ; return 262 +1a8: l32r a13, c ; "missing a conditional or committed entry" +1b1: callx8 a8 ; log +1b4: j 41f ; -> two instructions before retw.n at 422 +``` + +The success path sets `a2 = 0` at `0x417`. `nan_parse_ndp_req` calls this +parser from inside an attribute walk (backward branch `0x442 → 0x135`, two +references to the parser), which is consistent with the error coming from a +second call on map 1 — where Potential-only entries are exactly what is +expected — rather than from map 0. + +Per-map storage and lookup exist in the blob: `nan_get_avail_by_map_id` walks +92-byte records keyed on map ID. It is called from +`nan_sched_alloc_conditional`, `nan_sched_allocate_crbs` and +`nan_dp_indicate_faw_start`, but **not** from the parser. + +## What is NOT established + +Three things, each of which a previous draft of this document got wrong. + +**1. That the ESP honoured the phone's conditional entry.** An earlier draft +argued the committed ch6 bitmap in M2 proved the ESP had parsed and used +map 0. It proves nothing of the kind. In NAN-Sync the ESP is a single-channel +device that always advertises its own committed ch6 schedule: its SDFs in the +same capture carry a committed ch6 bitmap (`fcffffff`) before any NDP exists, +and it logs its own NDC as `NDP Resp NDCA: ndc=0x2 committed=0xfffffffe`. +M2's committed entry can come wholly from the ESP's own state. The ESP may +have accepted without honouring the phone's entry at all. Both readings stay +open. + +*(One small open detail: the SDF bitmap is `fcffffff` and M2's is `feffffff`. +If M2's committed schedule were a straight copy of the ESP's own state, one +might expect them identical. That difference may be ordinary DW-slot +bookkeeping and is not offered as evidence either way, but a future capture +could check whether M2's bitmap ever varies with the peer's offer.)* + +**2. That the Discovery Window boundary is the mechanism.** The out-of-window +side is solid — ten unacknowledged M2s across two DWs. The in-window side is +**n = 1**. SDFs are addressed to the group address `51:6f:9a:01:00:00` and are +never acknowledged, so they carry no delivery information. The only in-window +unicast is the run-3 follow-up at +9 ms. One success against ten failures is +suggestive, not proof. Run 2 additionally logged `Failed to send Follow-up +message!` twice with no sniffer timing; if those attempts were in-window, the +boundary story weakens further. + +**3. That any ESP scheduling defect is involved at all.** Throughout every run +the phone was associated as a STA to an AP on **channel 64 (5320 MHz)** — its +map-1 Potential 5 GHz entries, op class 128, are consistent with exactly that. +Android time-shares the radio back to its AP channel between Discovery +Windows, and a *conditional* availability entry does not oblige the peer to +remain on channel 6 until the NDL is confirmed. So outside the DW the phone +may simply not have been listening on channel 6, which would account for every +unacknowledged M2 with no ESP defect whatsoever. + +## The off-AP rerun: the timing theory does not survive either + +Phone Wi-Fi on, not associated, verified over adb. + +**Run 4, roles reversed** (phone publishes, ESP subscribes and initiates). +The ESP discovered the phone in **0.24 s**. Its unicast follow-up went out 22 +times at +13 to +22 ms and was never acknowledged. The ESP proceeded to the +NDP regardless (`Peer datapath_reqd not set, proceeding anyway`), sent M1 +dialog 1 ×5 then dialog 2, and the phone answered **NDP Response status +`0x21` = REJECTED, reason 2 (resource limitation)**. The ESP's M1 carried +Availability map 0 with a conditional ch6 entry (`fcff0100`) plus a potential +entry on ch 1–11. + +**Run 5, original direction** (ESP publishes, phone subscribes). No discovery +across roughly 60 Discovery Windows. In every one of them the ESP's publish +SDF landed **+2 to +14 ms** after the phone's SDF — inside the 16 TU window, +and often *earlier* than a third-party NAN device at +1 to +14 ms that was +transmitting in the same windows. The phone still never matched. + +### What this does to the timing theory + +Run 5 is decisive against the *simple* version of it: the ESP transmitted +inside the 16.384 ms Discovery Window, repeatedly, and was still not heard. +"The ESP transmits too late relative to the end of the DW" cannot carry runs +5 and 6. + +It survives in a narrower form for runs 3 and 4, against a shorter effective +deadline — see [Transmit offsets, all runs](#transmit-offsets-all-runs) — and +ask 1 is written to that narrower claim only. + +### But "the phone hears nothing from the ESP" is too strong + +In run 4 the phone **answered the ESP's M1** with a properly formed NDP +Response carrying a specific reason code. It cannot have done that without +receiving M1. So the phone's receive path for ESP frames is not globally +broken, and any explanation resting on PHY rate or frame format has to +account for M1 getting through while 22 follow-ups did not. + +The reason-2 rejection itself is explained and is not an ESP fault: the test +app only called `requestNetwork()` from `onMessageReceived`, so with no +follow-up delivered Android had no pending responder request to match M1 +against. The app now arms an any-peer responder at publish time +(`WifiAwareNetworkSpecifier.Builder(publishSession)`), which removes that +dependency, and run 4 should be repeated with it. + +### Transmit offsets, measured from the captures + +Re-derived directly from the pcaps rather than from frame counts, because +counting frames overstates the evidence: retries within a burst are not +independent trials. + +**Method note.** There are **no ACK frames at all in any of the four pcaps**. +That is a property of the capture, not of the medium: the sniffer runs with +`WIFI_PROMIS_FILTER_MASK_MGMT` and keeps only NAN management frames, so +control frames are never recorded. No conclusion here may rest on "the sniffer +saw no ACK". + +Delivery is instead read from two independent signals that agree: the 802.11 +**retry bit** — a burst that stops before the retry limit was acknowledged, +one that runs to the limit was not — and the ESP's own TX-status logging. A +future capture can add `WIFI_PROMIS_CTRL_FILTER_MASK_ACK` to record ACKs by +RA directly, which would turn this inference into a measurement. + +Every unicast transmission *event* from the ESP across runs 3 and 4, with the +offset measured from the preceding group-addressed SDF from the phone: + +| run | AP | first tx | last tx | frames | outcome | +|---|---|---|---|---|---| +| 3 | on | **+9.22 ms** | **+10.22 ms** | 3 | **delivered** on the 3rd | +| 3 | on | +15.93 ms | +19.88 ms | 5 | failed | +| 3 | on | +15.93 ms | +19.61 ms | 5 | failed | +| 4 | off | +13.12 ms | +22.08 ms | 21 | failed | +| 4 | off | +17.37 ms | +20.36 ms | 5 | failed | +| 4 | off | **+4.16 ms** | — | **1** | **acked first attempt** | + +Six events: two delivered, four failed. Corroboration for both successes is +independent of the capture — the phone logged +`onMessageReceived … utf8="Welcome"` for the run-3 event, and the ESP logged +`M1 TX success: ndp_id=1` for the run-4 one, which is also the only event that +needed no retry at all. + +Two features of this table matter more than the raw counts. + +**The effect is graded.** +4.16 ms was acknowledged on the first attempt. ++9.22 ms needed three attempts and only got through at +10.22 ms. Everything +first transmitted at +13.12 ms or later failed outright, including one event +that tried 21 times. That is the shape of a receiver that stops listening part +way through the window, not of random loss. + +**The boundary is in the same place with and without the AP.** On-AP: success +at +9–10 ms, failures at +15.93 ms twice. Off-AP: success at +4.16 ms, +failures at +13.12 and +17.37 ms. If AP time-sharing on 5 GHz accounted for +the run-3 failures, the boundary would not be expected to land in the same +place off-AP. A single mechanism spanning both conditions fits better than two +different ones. + +It remains a small sample — two successes — and the retry limit is inferred +from bursts stopping at 5. A deliberate sweep of follow-up delivery against DW +offset would settle it properly. + +### What the offsets do NOT explain + +Run 4 was **off-AP**, and the phone answered a unicast at +4 ms. So off-AP the +phone is demonstrably awake and receiving early in the window. + +That rules out the simplest reading of runs 5 and 6. In those the ESP's +publish SDF landed at +2 to +14 ms after the phone's SDF, across roughly 60 +Discovery Windows. Many of those were inside the +4 to +9 band that +demonstrably works. The phone still never matched, and its HAL shows +subscribe OK (`subscribeId=1`) with **no match event from firmware at all**. + +So early termination cannot account for runs 5 and 6, and neither can the +frames: the ESP's publish SDF carries SDA service id `6f08e42b8c44` = +`SHA-256("esp-nan-test")[:6]`, exactly matching the phone's own subscribe SDF, +with publish type `0x00`, in cluster `50:6f:9a:01:db:dd` — the same cluster +all three devices are in — at 6 Mbps non-HT, the most robust rate available. + +### The remaining asymmetry: unicast works, group-addressed does not + +Putting runs 4, 5 and 6 together, off-AP: + +- A **unicast** frame to the phone's NMI at +4 ms is received and answered. +- A **group-addressed** publish SDF produces no firmware match, with the + correct service ID and cluster, **88 times out of 123 at or before +10 ms** + in run 5 alone (23 of 37 in run 6b). + +On-AP, in runs 2–3, the same group-addressed publish SDF *was* matched, in +1–23 s. + +The open question this raises is whether the phone processes group-addressed +SDFs differently when it has no AP association — a receive-filter or +power-save difference rather than anything about the ESP's transmissions. + +**A caution on that hypothesis.** It has the same shape as the one proposed +for the USD defect in issue 1, where group-addressed NAN frames also appear to +go missing. That symmetry is suggestive but it is also exactly the kind of +pattern-match that has produced four discarded theories in this +investigation. It is written down as a question, not a finding. + +### The test that would settle it + +The phone subscribes **ACTIVE**, so it transmits subscribe SDFs that the ESP +can see. A NAN publisher is expected to answer a matching active subscribe +with a **solicited publish, unicast to the subscriber's NMI**. + +Two things to check in the run 5/6 captures: + +1. **Does the ESP ever send a unicast solicited publish to the phone's NMI?** + If it does not, discovery depends entirely on the phone catching a + group-addressed broadcast, and the ESP's failure to answer an active + subscribe is itself a defect worth reporting separately. +2. **If it does, at what DW offset, and is it matched?** A unicast solicited + publish landing at +4 ms and still producing no match would clear the + unicast/broadcast hypothesis and point back at the phone's firmware. + +### Still outstanding + +The on-AP/off-AP inversion is unexplained and reproduces (runs 5 and 6). Until +it is understood, no claim about the ESP's behaviour in either direction is +safe. The alternating on/off-AP pair is the next experiment and requires the +phone to be rejoined to its AP. + +## Asks + +1. **Transmit NAF responses in the first few milliseconds of the Discovery + Window, and do not let retries drift towards its end.** Measured against a + real Android peer: every ESP unicast at +4 or +9 ms was received, and all + 37 attempts at +13 ms or later were not, across three runs and both roles. + Android can terminate the DW early (`enable_dw_early_termination`), so the + formal 16.384 ms window is not the deadline that matters. The ESP currently + retries *later* into the window, out to +22 ms, which is the worst possible + direction. + + This ask covers runs 3 and 4 only. It does **not** explain runs 5 and 6, + where **88 of 123** ESP publish SDFs in run 5, and 23 of 37 in run 6b, + landed at or before +10 ms — inside the band that demonstrably works for + unicast — and produced no match at all. That remains unexplained and is not + part of this ask. + +2. **Parse every Availability attribute and map ID in the NDP Request, and do + not raise "missing a conditional or committed entry" for a map that + legitimately carries only Potential entries.** This one is independent of + the root cause and stands regardless. Per-map storage and lookup already + exist — `nan_get_avail_by_map_id` walks 92-byte records keyed on map ID — + but it is called from `nan_sched_alloc_conditional`, + `nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the + parser. The message sent two independent investigations down the wrong path + for a day. + +3. **Do not report ACCEPTED after a parse error**, or do not return an error + for a condition that does not prevent acceptance. At present the log and + the transmitted frame disagree. Also independent of the root cause. + +## Why this matters + +Phone interoperability is the main reason to use Wi-Fi Aware on these parts, +and essentially every phone will be STA-associated while doing it. Today +NAN-Sync works ESP-to-ESP and does not establish a data path with Android. + +## Credit + +Frame capture, decode and DW timing by the bench session running the ESP32-S2 +monitor, which also identified the STA-concurrency confound and the n = 1 +weakness in the in-window evidence. diff --git a/nan-pcap-parse.py b/nan-pcap-parse.py new file mode 100644 index 00000000000..a6bd0ae32a4 --- /dev/null +++ b/nan-pcap-parse.py @@ -0,0 +1,90 @@ +import struct, sys + +def frames(path): + d = open(path, 'rb').read() + if len(d) < 24: + return + magic = d[:4] + if magic == b'\xd4\xc3\xb2\xa1': + endi, usec = '<', True + elif magic == b'\xa1\xb2\xc3\xd4': + endi, usec = '>', True + elif magic == b'\x4d\x3c\xb2\xa1': + endi, usec = '<', False + elif magic == b'\xa1\xb2\x3c\x4d': + endi, usec = '>', False + else: + print("unknown magic", magic.hex(), file=sys.stderr); return + link = struct.unpack(endi + 'I', d[20:24])[0] + off = 24 + while off + 16 <= len(d): + ts, tu, incl, orig = struct.unpack(endi + 'IIII', d[off:off + 16]) + off += 16 + pkt = d[off:off + incl] + off += incl + if len(pkt) < incl: + break + t = ts + (tu / 1e6 if usec else tu / 1e9) + body = pkt + rate = None + if link == 127 and len(pkt) >= 8: # radiotap + rtlen = struct.unpack('> 2) & 3 + sub = (fc >> 4) & 0xF + a1 = a2 = a3 = None + if ftype == 1: # control + if len(body) >= 10: + a1 = body[4:10].hex(':') + else: + if len(body) >= 10: a1 = body[4:10].hex(':') + if len(body) >= 16: a2 = body[10:16].hex(':') + if len(body) >= 22: a3 = body[16:22].hex(':') + yield dict(t=t, ftype=ftype, sub=sub, a1=a1, a2=a2, a3=a3, + rate=rate, body=body) + +NAN_OUI = bytes.fromhex('506f9a') + +def nan_info(f): + """Return a short NAF description, or None.""" + if f['ftype'] != 0 or f['sub'] != 13: + return None + b = f['body'] + if len(b) < 24 + 6: + return None + p = b[24:] + if p[0] != 0x04 or p[1] != 0x09: # public action / vendor + return None + if p[2:5] != NAN_OUI: + return None + oui_type = p[5] + if oui_type != 0x13: + return f"NAF oui_type=0x{oui_type:02x}" + # NAN attributes follow + attrs = [] + q = p[6:] + i = 0 + while i + 3 <= len(q): + aid = q[i] + alen = struct.unpack(' Date: Mon, 23 Nov 2026 21:52:38 +0000 Subject: [PATCH 07/30] docs: confirm the NAN map-0/map-1 structure is not an AP artefact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ask 2 in the NDP draft rests on the two-map Availability structure of an NDP Request captured only while the phone was associated to an AP. Decoding the attributes out of the captures with nan-pcap-parse.py settles most of that concern. The phone's map-0 SDF entry is byte-identical on-AP and off-AP, and the map-1 entries appear in both conditions. The op class is decisive: class 128 with channel bitmap 0x0020 is the 80 MHz block centred on 155, channels 149-161, which contains 149, the NAN 5 GHz discovery channel. The phone's AP was on channel 64, in the block centred on 58, which would be bit 1. So map 1 is the phone's own NAN 5 GHz availability and not its AP. An earlier reading of those entries as matching the AP channel was wrong. The AP does change the content: the 5 GHz potential time bitmap is 00f000ff on-AP and fff0ffff off-AP. The caveat that matters is recorded too. All of this is from SDFs, and the SDF map-0 entry is Potential with slots 03000000 while the on-AP NDP Request map-0 was Conditional with ffffffff — the phone upgrades its offer when it actually requests a data path. No off-AP NDP Request has ever been captured, because off-AP discovery never completes. Also corrects the count: the parse failure appears in runs 2 and 3, not run 3 alone. Both on-AP, both with the ESP as responder, zero off-AP observations. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 3d0364b72c7..75694b1a2a5 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -283,6 +283,51 @@ go missing. That symmetry is suggestive but it is also exactly the kind of pattern-match that has produced four discarded theories in this investigation. It is written down as a question, not a finding. +### Is the map-0/map-1 structure an artefact of the AP? + +Ask 2 rests on the two-map structure of an NDP Request that was only ever +captured while the phone was associated to an AP. Decoding the phone's +Availability attributes straight out of the captures answers most of that +worry. + +The phone's **map-0 entry in its SDFs is byte-identical on-AP and off-AP**: + +``` +0e00 1a12 1800 04 03000000 11 51 2000 00 potential, op class 81, ch 6 +0b00 1a12 1800 04 fcffffff 10 02 potential, band 2.4 GHz +``` + +The map-1 entries are present in both conditions too, and the op class is the +decisive detail: **op class 128, channel bitmap `0x0020`**. For class 128 the +channel set is 42, 58, 106, 122, 138, 155, so bit 5 is the 80 MHz block +centred on 155 — channels 149–161, containing **149, the NAN 5 GHz discovery +channel**. The phone's AP was on channel 64, which sits in the block centred +on 58 and would be bit 1. So map 1 is the phone's own NAN 5 GHz availability +and has nothing to do with its AP association. An earlier reading of these +entries as "matching the AP channel" was wrong. + +The two-map structure is therefore a property of the phone's NAN +configuration, not of the AP, and **ask 2 does not rest on an AP artefact**. + +Two caveats, one of which matters. + +The AP does change the *content*: the 5 GHz potential time bitmap is +`00f000ff` on-AP and `fff0ffff` off-AP, which is what one would expect from a +radio that has to serve an association. + +The caveat that matters: all of the above is from **SDFs**, and the SDF map-0 +entry is **Potential** with slots `03000000`, whereas the on-AP **NDP +Request** map-0 was **Conditional** with `ffffffff`. The phone upgrades its +offer when it actually asks for a data path. So SDFs are weak evidence for +what an off-AP NDP Request would contain, and no off-AP NDP Request has ever +been captured — off-AP discovery has never completed, so the exchange never +gets that far. + +**The availability parse failure has been observed twice, in runs 2 and 3, +both on-AP, both with the ESP as NDP responder. There are zero off-AP +observations.** Reproducing it needs either the AP back, or discovery working +off-AP so the phone initiates an NDP there. + ### The test that would settle it The phone subscribes **ACTIVE**, so it transmits subscribe SDFs that the ESP From 110a940064a1574a15a964d3b5cdfca413ac20dc Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 22:55:42 +0000 Subject: [PATCH 08/30] docs: run 7 established the data path; both asks now resolve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An IPv6 data path came up between the Note 9 and the ESP32. The draft is no longer "NAN does not work with Android"; it is two specific defects and one unexplained discovery failure. Ask 2 is settled and downgraded. "Avail: missing a conditional or committed entry" was logged in run 7 as well, and the NDP confirmed anyway, so the error never prevented anything and the open worry that it might corrupt the ESP's schedule state is answered. It is an error-level log line for a non-error. Ask 1 is sharpened and an earlier reading here is corrected. With ACK frames captured directly rather than inferred from the retry bit, the boundary is the real 16.384 ms Discovery Window end, not the ~10-13 ms early termination this document previously proposed: +15 ms acknowledged, +16 and +17 ms not. The mechanism is latency, not policy — the ESP takes about 16 ms to turn an NDP Request into an M2, which lands the response on the window edge and makes setup close to a coin flip. The within-run control did not happen: IDF refused a second publish of the same service name, so run 7 was solicited-only and the off-AP discovery question is untouched by it. New and uninvestigated: the link dropped about 20 s after confirmation, with the phone reporting eventDataPathTerminated and the ESP logging nothing. Either an idle data path is reclaimed, or the ESP's all-slots channel-6 NDL commitment cannot be honoured by a phone that is also serving an AP. The test app now sends a keepalive every 2 s to separate the two. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 139 +++++++++++++++++++++------- 1 file changed, 103 insertions(+), 36 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 75694b1a2a5..4d404a779da 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -1,20 +1,23 @@ -# NAN: data path with an Android peer never completes — NDP Response is never acknowledged - -**Status: draft, partially ready.** There are two distinct failures here and -they need separating before anything is filed. - -- **Runs 3 and 4** (data path never completes) have a probable cause: of six - ESP unicast transmission events, the two first sent at +4.2 and +9.2 ms were - delivered and the four first sent at +13.1 ms or later all failed, with the - same boundary on and off the AP. Suggestive and graded, but **two successes - is a small sample** — a deliberate offset sweep should precede filing. -- **Runs 5 and 6** (discovery itself never happens, off-AP) are - **unexplained**. The frames are correct and in-window, and the phone's - firmware reports no match. Nothing here should be filed about them. - -Asks 2 and 3 are independent of both and stand. Four earlier explanations for -the data-path failure were proposed and discarded; that history is kept in -[What is NOT established](#what-is-not-established) deliberately. +# NAN: NDP Response straddles the Discovery Window end, and a spurious availability error + +**Status: draft, two asks ready, one question still open.** The data path +*does* work — run 7 established an IPv6 data path between an Android phone and +an ESP32 — so this is no longer "NAN is broken with Android". It is two +specific defects plus an unexplained off-AP discovery failure. + +- **Ask 1 (timing) is ready.** The ESP takes ~16 ms to answer an NDP Request + and the Discovery Window is 16.384 ms, so the response lands on the edge. + Measured with direct ACK capture: +15 ms acknowledged, +16/+17 ms not. +- **Ask 2 (spurious error) is ready, and is now demonstrably cosmetic.** + `Avail: missing a conditional or committed entry` is logged on runs where + the NDP **succeeds**, so it never was a negotiation failure. +- **Off-AP discovery** never completes and is **not explained**. Nothing + about it should be filed. +- **A ~20 s data-path teardown** appeared in run 7 and is uninvestigated. + +Four earlier explanations were proposed and discarded; that history is kept in +[What is NOT established](#what-is-not-established) because each was dropped +on evidence that constrains what remains. ## Summary @@ -351,27 +354,91 @@ it is understood, no claim about the ESP's behaviour in either direction is safe. The alternating on/off-AP pair is the next experiment and requires the phone to be rejoined to its AP. +### Run 7: the data path works + +Phone back on-AP, screen awake, ESP running a SOLICITED publisher. Captured +with ACK frames recorded, so delivery is direct evidence rather than inferred +from the retry bit. + +``` +4.779 DW+1 ESP solicited publish (unicast) -> phone ACKED +5.303 DW+0 phone follow-up "Hello" -> ESP ACKED +5.306 DW+3 ESP publish + "Welcome" -> phone ACKED +5.311 DW+8 +5.826 DW+0 phone NDP Request -> ESP ACKED +5.842 DW+16..17 ESP M2 burst x5 NOT acked +6.365 DW+15 ESP M2 retry burst x3 ACKED -> confirm +6.382 phone broadcast NAF Schedule Update +``` + +The app reported `TCP connect to [fe80::240a:c4ff:fecb:7ddb%aware_data0]:7 +REFUSED => PASS` and `isReachable=true`; the ESP logged `NDP confirmed … +Peer IPv6 FE80::281B:56FF:FE14:B87C`, NDL ch6, `ndc=[1,1]`, `crb1=[2,31]`. + +**This settles ask 2.** `Avail: missing a conditional or committed entry` was +logged in this run too, and the NDP confirmed anyway. The error never +prevented anything. It is a misleading log line, and the earlier worry that it +might also corrupt the ESP's schedule state is answered: it does not prevent +setup. + +**It also sharpens ask 1 and corrects an earlier reading here.** With direct +ACK evidence the boundary is the **real 16.384 ms DW end**, not the ~10–13 ms +early termination this document previously proposed: +15 ms was acknowledged, ++16 and +17 ms were not. The mechanism is latency, not policy — the ESP takes +about 16 ms to turn an NDP Request into an M2, which deposits the response +exactly on the window edge and makes setup close to a coin flip. One earlier +data point remains unexplained by a clean 16 ms edge (an off-AP burst whose +first attempt at +13.12 ms failed); it is a single event and the direct-ACK +evidence is better. + +**The control did not happen.** IDF refused the second publish — +`Service name esp-nan-test already used!`, publish #2 id=0 — so this was +solicited-only and there is no within-run unsolicited comparison. Two +instances need different service names. The off-AP discovery question is +therefore untouched by run 7, which was on-AP and discovered via a *unicast* +solicited publish ACKed at DW+1. + +### The 20 s teardown + +About 20 s after confirmation the link dropped. The phone reported +`eventDataPathTerminated` for ndp 4 and the app logged `onLost` at 26.4 s; the +ESP logged nothing. + +Two candidates, and they are cheaply separable: + +1. **Idle teardown.** The app connected once and then sent nothing. If an + unused NAN data path is reclaimed, this is not a defect at all. +2. **An unsatisfiable NDL.** The ESP committed `crb1=[2,31]` — effectively + every slot on channel 6 — which a phone concurrently associated to an AP + on channel 64 cannot honour. If so this links back to the availability + handling: the ESP takes the peer's *conditional* offer as licence to commit + to everything, survives setup, and loses the link later. + +The test app now sends a keepalive probe every 2 s once the data path is up +and reports how long the link survived, which distinguishes the two in one +run. + ## Asks -1. **Transmit NAF responses in the first few milliseconds of the Discovery - Window, and do not let retries drift towards its end.** Measured against a - real Android peer: every ESP unicast at +4 or +9 ms was received, and all - 37 attempts at +13 ms or later were not, across three runs and both roles. - Android can terminate the DW early (`enable_dw_early_termination`), so the - formal 16.384 ms window is not the deadline that matters. The ESP currently - retries *later* into the window, out to +22 ms, which is the worst possible - direction. - - This ask covers runs 3 and 4 only. It does **not** explain runs 5 and 6, - where **88 of 123** ESP publish SDFs in run 5, and 23 of 37 in run 6b, - landed at or before +10 ms — inside the band that demonstrably works for - unicast — and produced no match at all. That remains unexplained and is not - part of this ask. - -2. **Parse every Availability attribute and map ID in the NDP Request, and do - not raise "missing a conditional or committed entry" for a map that - legitimately carries only Potential entries.** This one is independent of - the root cause and stands regardless. Per-map storage and lookup already +1. **Answer an NDP Request well inside the same Discovery Window.** The ESP + takes about 16 ms from receiving M1 to transmitting M2, and the DW is + 16.384 ms, so the response lands on the edge and whether the data path + comes up is close to chance. Measured with direct ACK capture in run 7: + a burst at +16/+17 ms was not acknowledged, a retry at +15 ms in the next + window was. Earlier runs failed the same way at +16 to +20 ms. Either cut + the response latency, or schedule the response into the peer's next + committed or conditional slot rather than emitting it late in the current + window. + + This ask covers the data-path failures only. It does **not** explain the + off-AP discovery failure, where 88 of 123 publish SDFs in run 5 landed at + or before +10 ms with no match at all. + +2. **Do not log "missing a conditional or committed entry" for a map that + legitimately carries only Potential entries.** Run 7 confirms this error is + **cosmetic** — it is logged on runs where the NDP goes on to confirm + successfully. It is an error-level message for a non-error, and it cost two + independent investigations several days. Per-map storage and lookup already exist — `nan_get_avail_by_map_id` walks 92-byte records keyed on map ID — but it is called from `nan_sched_alloc_conditional`, `nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the From 0d9dc531cf1edd9c0f3e6b7666b2d4eda7060d55 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 22:56:49 +0000 Subject: [PATCH 09/30] =?UTF-8?q?docs:=20M2=20is=20slot-anchored,=20not=20?= =?UTF-8?q?latency-bound=20=E2=80=94=20ask=201=20rewritten?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous revision blamed the NDP Response timing on processing latency, the ESP taking about 16 ms to turn M1 into M2. The capture refutes that. Run 3's two M2 bursts both start at +15.927 ms relative to the phone's SDF — the identical intra-window position, to the microsecond, separated by 524.252 ms or 0.9999 Discovery Window periods. Processing latency cannot reproduce a sub-millisecond offset a full period later. The ESP schedules M2 against the slot grid, aiming at 0.97 of a slot: the slot-0/slot-1 boundary less about 460 microseconds. That matches the ESP's own NDL, which places the NDC in slot 1 (ndc=[1,1], crb1=[2,31]). Before the NDP is confirmed the peer's slot 1 is only conditional, so a response aimed there has no guaranteed listener. It looks like an off-by-one, slot+1 rather than end-of-slot-0, though a deliberate last-moment policy with no margin is indistinguishable from outside the blob. The remedy is the same. Ask 1 now states it precisely: transmit the NDP Response, and any NAF to a peer with no confirmed NDL, early in slot 0 and never at or after the slot boundary, keeping retries inside slot 0. Measured starts as a fraction of a slot: 0.25, 0.56 and 0.85-0.90 acknowledged; 0.93-1.05 and 0.97 not. The slot-grid reading came from the bench session, prompted by Tyeth asking whether this was an off-by-one. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 60 ++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 4d404a779da..e4dc6bb4dc9 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -381,15 +381,33 @@ prevented anything. It is a misleading log line, and the earlier worry that it might also corrupt the ESP's schedule state is answered: it does not prevent setup. -**It also sharpens ask 1 and corrects an earlier reading here.** With direct -ACK evidence the boundary is the **real 16.384 ms DW end**, not the ~10–13 ms -early termination this document previously proposed: +15 ms was acknowledged, -+16 and +17 ms were not. The mechanism is latency, not policy — the ESP takes -about 16 ms to turn an NDP Request into an M2, which deposits the response -exactly on the window edge and makes setup close to a coin flip. One earlier -data point remains unexplained by a clean 16 ms edge (an off-AP burst whose -first attempt at +13.12 ms failed); it is a single event and the direct-ACK -evidence is better. +**It also sharpens ask 1, and the mechanism is not what this document said.** +An earlier version blamed processing latency — the ESP taking ~16 ms to turn +M1 into M2. The capture refutes that. Run 3's two M2 bursts, measured against +the phone's SDF: + +``` +burst 1 (5 frames) off = +15.927 ms = 0.9721 slots +burst 2 (5 frames) off = +15.927 ms = 0.9721 slots +gap between them = 524.252 ms = 0.9999 DW periods +``` + +The retry lands at the **identical intra-window position**, to the +microsecond, a full Discovery Window period later. Processing latency cannot +produce that. The ESP is scheduling M2 **against the slot grid**, aiming at +0.97 of a slot — the slot-0/slot-1 boundary, less a ~460 µs margin — rather +than transmitting as early as it can inside the window. + +That fits the ESP's own NDL, which places the NDC in slot 1 (`ndc=[1,1]`, +`crb1=[2,31]`). Before the NDP is confirmed the peer's slot 1 is only +*conditional*, so a response aimed at slot 1 has no guaranteed listener. It is +the signature of an off-by-one — slot+1 rather than end-of-slot-0 — though +from outside the blob a deliberate "last possible moment" policy with no +margin is indistinguishable, and the fix is the same either way. + +Collected starts, as a fraction of a slot: 0.25 and 0.56 acknowledged, 0.85–0.90 +acknowledged (run 7 retry), 0.93–1.05 not, 0.97 not, 0.97 not. One off-AP +follow-up burst starting at 0.80 also failed and is not explained by this. **The control did not happen.** IDF refused the second publish — `Service name esp-nan-test already used!`, publish #2 id=0 — so this was @@ -420,15 +438,21 @@ run. ## Asks -1. **Answer an NDP Request well inside the same Discovery Window.** The ESP - takes about 16 ms from receiving M1 to transmitting M2, and the DW is - 16.384 ms, so the response lands on the edge and whether the data path - comes up is close to chance. Measured with direct ACK capture in run 7: - a burst at +16/+17 ms was not acknowledged, a retry at +15 ms in the next - window was. Earlier runs failed the same way at +16 to +20 ms. Either cut - the response latency, or schedule the response into the peer's next - committed or conditional slot rather than emitting it late in the current - window. +1. **Transmit an NDP Response — and any NAF to a peer with no confirmed NDL + — early in slot 0 of the Discovery Window, never at or after the slot + 0/slot 1 boundary, and keep retries inside slot 0.** + + The ESP currently aims at 0.97 of a slot. Run 3's two M2 bursts both + started at +15.927 ms, the identical intra-window position one full DW + period apart, so this is slot-grid scheduling rather than processing + latency. The ESP's NDL places its NDC in slot 1, and before the NDP is + confirmed the peer's slot 1 is only conditional, so there is no guaranteed + listener there. Measured starts: 0.25, 0.56 and 0.85–0.90 slots + acknowledged; 0.93–1.05 and 0.97 not. + + Whether this is an off-by-one (slot+1 instead of end-of-slot-0) or a + deliberate last-moment policy with no margin cannot be told from outside + the Wi-Fi libraries, but the remedy is the same. This ask covers the data-path failures only. It does **not** explain the off-AP discovery failure, where 88 of 123 publish SDFs in run 5 landed at From 575923fc0acf50e2fdc45c116f1aed054b497fd6 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:00:30 +0000 Subject: [PATCH 10/30] docs: withdraw the slot-anchoring argument; add the Schedule Request defect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two corrections and one new issue. Withdrawn: the argument that M2 must be slot-anchored rather than latency-bound because run 3's two bursts started at the identical offset. Run 3's coincidence does not generalise — the successful retries in runs 7 and 8 started at 0.85-0.90 and 0.569 slots, nowhere near the first attempt. Only the first attempt is consistent across runs, at 0.98, 0.93 and 1.03 slots after the request, and because the phone always sends its request at DW+0 those first attempts cannot separate 16 ms of processing latency from slot-grid scheduling. Off-by-one is a hypothesis again, and ask 1 is restated so that it does not depend on which it is. New, IDF-ISSUE-3-nan-schedule-request.md: after the data path is established the phone sends a unicast NAF Schedule Request (subtype 10), the ESP ACKs it at the link layer, never sends a Schedule Response, and the phone tears the data path down. Reproduced in run 7 on-AP and run 8 off-AP. The mechanism is in the binary. nan_rx_naf in ieee80211_nan_datapath.o references exactly five parse handlers, subtypes 5 to 9, and the object contains no parse, construct or send function for subtypes 10 to 13. The "Unknown NAN Action subtype - %d" string it carries lives in .rodata_wlog_error.144, so it is error level; since the ESP reportedly logged nothing, either that line was not captured or the frame never reaches the dispatcher despite being acknowledged. Either way the handlers do not exist. This is the most likely cause of the teardown previously recorded in issue 2 as cause unknown. Also recorded: run 8 established an off-AP data path via a solicited unicast publish in 1.25 s, so the runs 5/6 discovery failure was specific to the unsolicited group-addressed publish. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 93 +++++++++++--------- IDF-ISSUE-3-nan-schedule-request.md | 132 ++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+), 43 deletions(-) create mode 100644 IDF-ISSUE-3-nan-schedule-request.md diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index e4dc6bb4dc9..a121fd7d840 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -13,7 +13,13 @@ specific defects plus an unexplained off-AP discovery failure. the NDP **succeeds**, so it never was a negotiation failure. - **Off-AP discovery** never completes and is **not explained**. Nothing about it should be filed. -- **A ~20 s data-path teardown** appeared in run 7 and is uninvestigated. +- **A ~20 s data-path teardown** appeared in runs 7 and 8. It now has a + mechanism and its own write-up: the ESP never answers the peer's NAF + Schedule Request. See `IDF-ISSUE-3-nan-schedule-request.md`. +- **Off-AP discovery works with a *solicited* (unicast) publish** — run 8 + discovered in 1.25 s. The runs 5/6 failure was specific to the + **unsolicited, group-addressed** publish, which supports the + unicast-versus-group-addressed split recorded below. Four earlier explanations were proposed and discarded; that history is kept in [What is NOT established](#what-is-not-established) because each was dropped @@ -381,33 +387,33 @@ prevented anything. It is a misleading log line, and the earlier worry that it might also corrupt the ESP's schedule state is answered: it does not prevent setup. -**It also sharpens ask 1, and the mechanism is not what this document said.** -An earlier version blamed processing latency — the ESP taking ~16 ms to turn -M1 into M2. The capture refutes that. Run 3's two M2 bursts, measured against -the phone's SDF: +**It also sharpens ask 1, though the mechanism is still open.** An earlier +revision of this document argued that because run 3's two M2 bursts started +at the identical offset (+15.927 ms, 0.9721 slots, one DW period apart to +within 0.0001 of a period), the transmission must be anchored to the slot grid +rather than to processing latency. **That argument is withdrawn.** Run 3's +coincidence does not generalise: the successful retries in later runs started +at 0.85–0.90 slots (run 7) and 0.569 slots (run 8), nowhere near the first +attempt's position. -``` -burst 1 (5 frames) off = +15.927 ms = 0.9721 slots -burst 2 (5 frames) off = +15.927 ms = 0.9721 slots -gap between them = 524.252 ms = 0.9999 DW periods -``` +What *is* consistent is the **first** attempt, across every run: -The retry lands at the **identical intra-window position**, to the -microsecond, a full Discovery Window period later. Processing latency cannot -produce that. The ESP is scheduling M2 **against the slot grid**, aiming at -0.97 of a slot — the slot-0/slot-1 boundary, less a ~460 µs margin — rather -than transmitting as early as it can inside the window. +| run | first M2 after M1 | +|---|---| +| 3 | 0.98 slots | +| 7 | 0.93 slots | +| 8 | 1.03 slots | -That fits the ESP's own NDL, which places the NDC in slot 1 (`ndc=[1,1]`, -`crb1=[2,31]`). Before the NDP is confirmed the peer's slot 1 is only -*conditional*, so a response aimed at slot 1 has no guaranteed listener. It is -the signature of an off-by-one — slot+1 rather than end-of-slot-0 — though -from outside the blob a deliberate "last possible moment" policy with no -margin is indistinguishable, and the fix is the same either way. +Because the phone always sends its NDP Request at DW+0, "about one slot after +M1" and "the slot-0/slot-1 boundary" are the same instant, so first attempts +alone **cannot** separate ~16 ms of processing latency from deliberate +slot-grid scheduling. Off-by-one remains a hypothesis. -Collected starts, as a fraction of a slot: 0.25 and 0.56 acknowledged, 0.85–0.90 -acknowledged (run 7 retry), 0.93–1.05 not, 0.97 not, 0.97 not. One off-AP -follow-up burst starting at 0.80 also failed and is not explained by this. +The defensible statement is the one that does not depend on the mechanism: the +first NDP Response consistently goes out about 16 ms after the request, which +is at or past the end of the Discovery Window, and setup only succeeds when a +retry happens to land earlier in a later window. That is a coin flip, and it +is what ask 1 asks to fix. **The control did not happen.** IDF refused the second publish — `Service name esp-nan-test already used!`, publish #2 id=0 — so this was @@ -438,25 +444,26 @@ run. ## Asks -1. **Transmit an NDP Response — and any NAF to a peer with no confirmed NDL - — early in slot 0 of the Discovery Window, never at or after the slot - 0/slot 1 boundary, and keep retries inside slot 0.** - - The ESP currently aims at 0.97 of a slot. Run 3's two M2 bursts both - started at +15.927 ms, the identical intra-window position one full DW - period apart, so this is slot-grid scheduling rather than processing - latency. The ESP's NDL places its NDC in slot 1, and before the NDP is - confirmed the peer's slot 1 is only conditional, so there is no guaranteed - listener there. Measured starts: 0.25, 0.56 and 0.85–0.90 slots - acknowledged; 0.93–1.05 and 0.97 not. - - Whether this is an off-by-one (slot+1 instead of end-of-slot-0) or a - deliberate last-moment policy with no margin cannot be told from outside - the Wi-Fi libraries, but the remedy is the same. - - This ask covers the data-path failures only. It does **not** explain the - off-AP discovery failure, where 88 of 123 publish SDFs in run 5 landed at - or before +10 ms with no match at all. +1. **Answer an NDP Request early in slot 0 of the Discovery Window, well + before the slot 0/slot 1 boundary, and keep retries there too.** + + The first NDP Response goes out about 16 ms after the request in every run + measured — 0.98, 0.93 and 1.03 slots — which places it at or past the end + of the 16.384 ms window. Setup then succeeds only when a retry happens to + land earlier in a later window, which it did in runs 7 and 8 (0.85–0.90 and + 0.569 slots) and never did in run 3 (0.97 twice). Measured starts + acknowledged: 0.25, 0.56, 0.569, 0.85–0.90. Not acknowledged: 0.93–1.05, + 0.97, 0.97. + + Whether the 16 ms is processing latency or scheduling aimed at the slot + boundary cannot be told from outside the Wi-Fi libraries — the phone sends + its request at DW+0, so the two coincide. The remedy is the same either + way. Note also that the ESP's own NDL places its NDC in slot 1 while the + peer's slot 1 is still only conditional before confirmation, so a response + arriving there has no guaranteed listener. + + This ask covers data-path setup only. It does not explain the off-AP + discovery failure in runs 5 and 6. 2. **Do not log "missing a conditional or committed entry" for a map that legitimately carries only Potential entries.** Run 7 confirms this error is diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md new file mode 100644 index 00000000000..e0cb3fade4a --- /dev/null +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -0,0 +1,132 @@ +# NAN: Schedule Request from a peer is never answered, and the peer tears the data path down + +**Status: draft, strong.** The mechanism is identified in the binary and the +behaviour is reproduced in two runs under opposite AP conditions. One +confirmation is outstanding — see [One check](#one-check). + +## Summary + +After a NAN data path is established, an Android peer sends a unicast NAN +Action Frame **Schedule Request (subtype 10)**. The ESP acknowledges it at the +link layer and then does nothing: no Schedule Response (subtype 11) is ever +transmitted, and nothing is logged. The peer retries once, waits, and then +terminates the data path locally. + +The ESP has **no handling for NAF subtypes 10–13 at all**. + +## Environment + +| | | +|---|---| +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Target | ESP32 (classic, rev0), `wifi_aware/nan_publisher`, SOLICITED | +| Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | +| Capture | ESP32-S2 monitor on channel 6, with ACK frames recorded | + +## Observed, in two runs with opposite AP state + +Run 7 (phone associated to an AP on channel 64) and run 8 (phone not +associated at all) behave identically: + +1. NDP confirms; the IPv6 data path works. A TCP probe to the peer's + link-local address over `aware_data0` is refused, which proves the peer's + stack answered. +2. About **12 s after confirm**, the phone sends a unicast NAF **Schedule + Request** to the ESP. The ESP **ACKs it** — captured directly as ACK-by-RA, + not inferred. +3. About **6 s later** the phone sends a second Schedule Request. The ESP ACKs + that too. +4. No Schedule Response (subtype 11) appears anywhere in either capture, and + the ESP logs nothing. +5. The phone terminates the data path locally — HAL + `eventDataPathTerminated`, and the app's `onLost` at 26.4 s. In run 8 there + is **no over-the-air NDP Termination from the phone at all**; it simply + gives up. + +The Schedule Request is not an unreasonable one. Its content in run 8: + +- **map 0** — potential channel 6 slot 0 (`01000000`), plus **COMMITTED** + channel 6 slots 1–31 (`feffffff`) +- **map 1** — 5 GHz potential (band `fff0ffff`, op class 128 `0x0020`, slots + `000f0000`) +- plus NDC (15), NDL (4), NDL-QoS (3) + +The phone is offering to **commit to exactly the channel-6 schedule the ESP +itself committed to** (`crb1=[2,31]`). This is the peer doing the right thing +and converting a conditional arrangement into a committed one. The ESP ignores +it. + +## Mechanism, from the binary + +`ieee80211_nan_datapath.o` in `libnet80211.a` (esp32). The receive dispatcher +`nan_rx_naf` references exactly **five** parse handlers: + +``` +nan_parse_ndp_req subtype 5 Data Path Request +nan_parse_ndp_resp subtype 6 Data Path Response +nan_parse_ndp_confirm subtype 7 Data Path Confirm +nan_parse_ndp_security_install subtype 8 Data Path Key Installment +nan_parse_ndp_terminate subtype 9 Data Path Termination +``` + +The complete function list for the object confirms there is no counterpart for +any of: + +``` +subtype 10 Schedule Request +subtype 11 Schedule Response +subtype 12 Schedule Confirm +subtype 13 Schedule Update Notification +``` + +There is no `nan_parse_sched_*`, no `nan_construct_sched_*`, and no +`nan_send_sched_*`. Every `nan_sched_*` symbol present +(`nan_sched_construct_availability`, `nan_sched_allocate_crbs`, +`nan_sched_alloc_conditional` and so on) is availability construction for the +NDP exchange, not NAF schedule negotiation. + +`nan_rx_naf` carries the string `Unknown NAN Action subtype - %d`, and that +string lives in `.rodata_wlog_error.144` — it is an **error-level** message. + +## One check + +The ESP reportedly logged nothing when the Schedule Requests arrived. If the +dispatcher were reached, an error-level `Unknown NAN Action subtype - 10` +should have appeared. So either that line was simply not captured, or the +frame is dropped before `nan_rx_naf`, even though the MAC acknowledged it. + +Grepping an ESP log from a run that reaches this point for +`Unknown NAN Action subtype` distinguishes the two, and should be done before +filing. It does not change the conclusion — the handlers do not exist either +way — but it changes whether the report says "unhandled and logged" or +"silently discarded". + +## Impact + +A NAN data path with an Android peer is **torn down roughly 20 s after it is +established**, in both AP conditions. Schedule renegotiation after setup is +normal behaviour for a peer whose availability changes, and on Android it +appears to be routine rather than exceptional. Any long-lived use of Wi-Fi +Aware between an ESP32 and a phone is therefore not possible today, even once +the data path comes up. + +This is also the most likely explanation for the teardown previously recorded +as "cause unknown" in `IDF-ISSUE-2-nan-ndp-availability.md`. + +## Asks + +1. **Handle NAF Schedule Request (subtype 10) and reply with a Schedule + Response (subtype 11).** At minimum, accept a request that proposes a + schedule compatible with the one already committed, which is what the peer + sent here. +2. **Handle Schedule Update Notification (subtype 13)**, which the phone also + broadcasts after confirm and which is likewise unhandled. +3. **Do not silently discard unknown NAF subtypes on an active NDL.** If the + `Unknown NAN Action subtype` path is not being reached, something upstream + is dropping acknowledged frames. + +## Credit + +Captures, decode and the observation that the Schedule Requests go unanswered +come from the bench session running the hardware; the binary analysis is from +the captures it supplied. From 90a0ec94a81c1eb22e9b327fa8212ce5ebb4fad1 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:04:21 +0000 Subject: [PATCH 11/30] docs: narrow issue 3's impact to idle data paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Run 9 ran the data path with a keepalive probe every 2 s and it stayed up for the full 100 s capture — no teardown, no eventDataPathTerminated — against the roughly 20 s teardown seen on idle links in runs 7 and 8. Traffic also changes the peer's behaviour: Schedule Requests arrived about 6 s apart on an idle link and about 30-36 s apart with traffic, and the phone tolerated them going unanswered for at least 100 s. So the teardown needs both conditions, an idle link and an unanswered Schedule Request, and the write-up now states that as an observed correlation rather than as cause. Whether a compliant Schedule Response would by itself prevent the idle teardown cannot be known without a peer that answers one. The part that does not change: there is no code to answer a Schedule Request, so the ESP cannot participate in schedule renegotiation at all. The logging question is also settled as far as it can be from outside. There are zero occurrences of "Unknown NAN Action subtype" across runs 2, 3, 7, 8 and 9, while error-level wifi: lines such as the Avail message print in the same logs, and run 9 captured 100 s of silence after NDP confirm while three Schedule Requests arrived. Worded as "no log emitted although error-level logs are visible", since a path into nan_rx_naf that skips the log cannot be ruled out from here. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 7 +-- IDF-ISSUE-3-nan-schedule-request.md | 71 +++++++++++++++++++---------- 2 files changed, 50 insertions(+), 28 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index a121fd7d840..6fa403f9a6c 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -13,9 +13,10 @@ specific defects plus an unexplained off-AP discovery failure. the NDP **succeeds**, so it never was a negotiation failure. - **Off-AP discovery** never completes and is **not explained**. Nothing about it should be filed. -- **A ~20 s data-path teardown** appeared in runs 7 and 8. It now has a - mechanism and its own write-up: the ESP never answers the peer's NAF - Schedule Request. See `IDF-ISSUE-3-nan-schedule-request.md`. +- **A ~20 s data-path teardown** appeared in runs 7 and 8, on *idle* links + only; run 9 with keepalive traffic stayed up for 100 s. It has its own + write-up: the ESP never answers the peer's NAF Schedule Request. See + `IDF-ISSUE-3-nan-schedule-request.md`. - **Off-AP discovery works with a *solicited* (unicast) publish** — run 8 discovered in 1.25 s. The runs 5/6 failure was specific to the **unsolicited, group-addressed** publish, which supports the diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index e0cb3fade4a..fe375a836e2 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -1,8 +1,9 @@ # NAN: Schedule Request from a peer is never answered, and the peer tears the data path down -**Status: draft, strong.** The mechanism is identified in the binary and the -behaviour is reproduced in two runs under opposite AP conditions. One -confirmation is outstanding — see [One check](#one-check). +**Status: draft, ready.** The mechanism is identified in the binary and the +behaviour is reproduced in three runs under both AP conditions. The impact is +narrower than first thought: idle data paths are torn down, data paths +carrying traffic survive. ## Summary @@ -88,30 +89,49 @@ NDP exchange, not NAF schedule negotiation. `nan_rx_naf` carries the string `Unknown NAN Action subtype - %d`, and that string lives in `.rodata_wlog_error.144` — it is an **error-level** message. -## One check +## No log is emitted -The ESP reportedly logged nothing when the Schedule Requests arrived. If the -dispatcher were reached, an error-level `Unknown NAN Action subtype - 10` -should have appeared. So either that line was simply not captured, or the -frame is dropped before `nan_rx_naf`, even though the MAC acknowledged it. - -Grepping an ESP log from a run that reaches this point for -`Unknown NAN Action subtype` distinguishes the two, and should be done before -filing. It does not change the conclusion — the handlers do not exist either -way — but it changes whether the report says "unhandled and logged" or -"silently discarded". +`nan_rx_naf` carries the string `Unknown NAN Action subtype - %d`, and that +string sits in `.rodata_wlog_error.144` — **error level**. If the dispatcher's +default case were reached, that line should appear. + +It does not. Across runs 2, 3, 7, 8 and 9 there are **zero** occurrences of +`Unknown NAN Action subtype` in any ESP log. In run 9 the console was captured +continuously for about 110 s: the last line is `NDP confirmed` at 12.8 s, +followed by 100 s of silence while three Schedule Requests arrived, at least +the first of them MAC-acknowledged. Error-level `wifi:` lines are plainly not +suppressed in these logs — `Avail: missing a conditional or committed entry` +prints in the same runs. + +So the frames appear to be discarded somewhere before the dispatcher's default +case, despite the MAC acknowledging them. This cannot be proved from outside +the libraries — there may be a path into `nan_rx_naf` that skips the log — so +the accurate statement is: **no log is emitted, although error-level `wifi:` +logs are visible in the same capture.** ## Impact -A NAN data path with an Android peer is **torn down roughly 20 s after it is -established**, in both AP conditions. Schedule renegotiation after setup is -normal behaviour for a peer whose availability changes, and on Android it -appears to be routine rather than exceptional. Any long-lived use of Wi-Fi -Aware between an ESP32 and a phone is therefore not possible today, even once -the data path comes up. +**An idle NAN data path is torn down about 20 s after it is established.** A +data path carrying traffic is not: in run 9, with the peer sending a probe +every 2 s, the link stayed up for the full 100 s capture with no teardown and +no `eventDataPathTerminated`. + +Traffic also changes how often the peer asks. On an idle link the Schedule +Requests came about 6 s apart (runs 7 and 8); with traffic they came about +30–36 s apart (run 9). The phone tolerates unanswered requests for at least +100 s when the link is in use. + +So the teardown observed in runs 7 and 8 required **both** conditions: an idle +link *and* an unanswered Schedule Request. State that as the observed +correlation, not as cause. Whether a spec-compliant Schedule Response would +by itself prevent the idle teardown cannot be known without a peer that +answers one, and no such peer was available. -This is also the most likely explanation for the teardown previously recorded -as "cause unknown" in `IDF-ISSUE-2-nan-ndp-availability.md`. +What is certain either way is the first half: there is no code to answer a +Schedule Request, so the ESP cannot participate in schedule renegotiation at +all. The user-visible consequence today is that an idle data path does not +survive, and that a peer's attempts to adjust the schedule are silently +ignored however often it tries. ## Asks @@ -121,9 +141,10 @@ as "cause unknown" in `IDF-ISSUE-2-nan-ndp-availability.md`. sent here. 2. **Handle Schedule Update Notification (subtype 13)**, which the phone also broadcasts after confirm and which is likewise unhandled. -3. **Do not silently discard unknown NAF subtypes on an active NDL.** If the - `Unknown NAN Action subtype` path is not being reached, something upstream - is dropping acknowledged frames. +3. **Do not silently discard unknown NAF subtypes on an active NDL.** A + MAC-acknowledged frame that produces no log at all, while error-level + `wifi:` logging is demonstrably working, suggests something upstream of + `nan_rx_naf` is dropping it. ## Credit From 23d4a7a91de532f31d5e7e1e32d91a035ab5ee0f Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:04:43 +0000 Subject: [PATCH 12/30] docs: issue 3 title and run count follow the narrowed impact The title claimed the peer tears the data path down; run 9 showed that only happens on idle links, so it now says so. The observation section covered two runs and there are three, the third being the keepalive run where the ESP likewise never answered but the link survived. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-3-nan-schedule-request.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index fe375a836e2..e04b62f46e1 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -1,4 +1,4 @@ -# NAN: Schedule Request from a peer is never answered, and the peer tears the data path down +# NAN: Schedule Request from a peer is never answered, and idle data paths are torn down **Status: draft, ready.** The mechanism is identified in the binary and the behaviour is reproduced in three runs under both AP conditions. The impact is @@ -24,10 +24,11 @@ The ESP has **no handling for NAF subtypes 10–13 at all**. | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | | Capture | ESP32-S2 monitor on channel 6, with ACK frames recorded | -## Observed, in two runs with opposite AP state +## Observed, in three runs under both AP conditions -Run 7 (phone associated to an AP on channel 64) and run 8 (phone not -associated at all) behave identically: +Run 7 (phone associated to an AP on channel 64), run 8 (phone not associated +at all) and run 9 (not associated, with keepalive traffic) all show the ESP +never answering. Runs 7 and 8 were idle and both ended in a teardown: 1. NDP confirms; the IPv6 data path works. A TCP probe to the peer's link-local address over `aware_data0` is refused, which proves the peer's From a28b03c7b2315c7a534471da5deda364972fa058 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:12:03 +0000 Subject: [PATCH 13/30] docs: no slot threshold exists; ask 1 becomes a reliability claim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runs 10 and 11 both failed to establish a data path, with retries at 0.81-0.91 and 0.76 slots — positions where earlier runs succeeded. Acknowledged retries at 0.57 and 0.85-0.90 sit inside the range of unacknowledged ones at 0.76 to 0.91, so the ranges overlap and the "late equals lost" boundary this document carried is not supportable. Every enumerated accepted/rejected position list is removed. Before accepting that, the anchor was checked, since every offset here is measured from the phone's SDF rather than a true timebase. In run 3 the phone's SDF falls within 1.31 ms of a beacon at Discovery Window start, median 0.00 and standard deviation 0.40 ms over 593 windows. The proxy is sound, the measurements are not drifting, and the erratic outcomes are real. What survives is stronger for being simpler: the first NDP Response goes out about 16 ms after the request in every run measured, 0.93 to 1.03 slots, and the first attempt has never been acknowledged in any run. Setup succeeds only when a retry happens to be heard — 3 runs in 5 with the solicited publisher. The ask is now about that unreliability rather than about a position threshold. Two things constrain what remains. In run 10 the ESP failed to acknowledge the phone's M1 seven times in one window before accepting it in the next, so intermittent in-window deafness is not one-sided. And runs 10 and 11 carried a confound: an Android ANR dialog may have taken the test app out of the foreground. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 66 ++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 21 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 6fa403f9a6c..88c339d7334 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -5,9 +5,11 @@ an ESP32 — so this is no longer "NAN is broken with Android". It is two specific defects plus an unexplained off-AP discovery failure. -- **Ask 1 (timing) is ready.** The ESP takes ~16 ms to answer an NDP Request - and the Discovery Window is 16.384 ms, so the response lands on the edge. - Measured with direct ACK capture: +15 ms acknowledged, +16/+17 ms not. +- **Ask 1 (timing) is ready, as a reliability claim rather than a boundary.** + The ESP takes ~16 ms to answer an NDP Request and the Discovery Window is + 16.384 ms, so the first response always lands at or past the edge and has + never been acknowledged. Setup succeeds only when a retry is heard: 3 runs + in 5. Retry positions overlap across outcomes, so there is no threshold. - **Ask 2 (spurious error) is ready, and is now demonstrably cosmetic.** `Avail: missing a conditional or committed entry` is logged on runs where the NDP **succeeds**, so it never was a negotiation failure. @@ -423,6 +425,28 @@ instances need different service names. The off-AP discovery question is therefore untouched by run 7, which was on-AP and discovered via a *unicast* solicited publish ACKed at DW+1. +### Why there is no boundary, and a check on the measurements + +Runs 10 and 11 both failed to establish a data path, with retries at 0.81–0.91 +and 0.76 slots — positions where earlier runs had succeeded. Collected across +every run with the solicited publisher: **runs 7, 8 and 9 succeeded, runs 10 +and 11 failed.** Acknowledged retries at 0.57 and 0.85–0.90 sit *inside* the +range of unacknowledged ones at 0.76 to 0.91. The ranges overlap, so the +earlier "late equals lost" boundary is not supportable. + +Before concluding that, the anchor itself was checked, because every offset in +this document is measured from the phone's SDF rather than from a true +timebase. In run 3 the phone's SDF falls within **1.31 ms** of a beacon at +Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across +593 windows. The proxy anchor is sound and the measurements are not drifting; +the erratic outcomes are real. + +Two observations constrain what is left. Run 10 saw the **ESP** fail to +acknowledge the phone's M1 seven times in one window before accepting it in +the next, so intermittent in-window deafness is not one-sided. And runs 10 and +11 carried a confound: a "Google Play isn't responding" dialog may have taken +the test app out of the foreground for part of them. + ### The 20 s teardown About 20 s after confirmation the link dropped. The phone reported @@ -445,26 +469,26 @@ run. ## Asks -1. **Answer an NDP Request early in slot 0 of the Discovery Window, well - before the slot 0/slot 1 boundary, and keep retries there too.** +1. **Answer an NDP Request promptly, well before the end of the Discovery + Window in which it arrived.** The first NDP Response goes out about 16 ms after the request in every run - measured — 0.98, 0.93 and 1.03 slots — which places it at or past the end - of the 16.384 ms window. Setup then succeeds only when a retry happens to - land earlier in a later window, which it did in runs 7 and 8 (0.85–0.90 and - 0.569 slots) and never did in run 3 (0.97 twice). Measured starts - acknowledged: 0.25, 0.56, 0.569, 0.85–0.90. Not acknowledged: 0.93–1.05, - 0.97, 0.97. - - Whether the 16 ms is processing latency or scheduling aimed at the slot - boundary cannot be told from outside the Wi-Fi libraries — the phone sends - its request at DW+0, so the two coincide. The remedy is the same either - way. Note also that the ESP's own NDL places its NDC in slot 1 while the - peer's slot 1 is still only conditional before confirmation, so a response - arriving there has no guaranteed listener. - - This ask covers data-path setup only. It does not explain the off-AP - discovery failure in runs 5 and 6. + measured — 0.93, 0.95, 0.97, 1.03 slots — which places it at or past the + end of the 16.384 ms window, where the peer is not reliably listening. The + first attempt has **never** been acknowledged in any run. Setup succeeds + only when one of the retries happens to be heard, which makes it erratic: + **3 successes in 5 runs** with the solicited publisher. + + **There is no clean position threshold, and this document previously + claimed one.** Retry positions overlap across outcomes: retries at 0.57 and + 0.85–0.90 slots were acknowledged, while retries at 0.76 and 0.81–0.91 were + not. Position within the window does not by itself determine whether a + frame is heard. + + The ask therefore rests on the first attempt being consistently too late + and on the resulting unreliability, not on a boundary. Reducing the + response latency so M2 lands early in the window it belongs to would make + setup deterministic instead of depending on a retry being lucky. 2. **Do not log "missing a conditional or committed entry" for a map that legitimately carries only Potential entries.** Run 7 confirms this error is From 070703f795e7d548e296768e1c9c05cecd06fb92 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:16:29 +0000 Subject: [PATCH 14/30] docs: correct the setup success count and record the capture caveat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The success rate was stated as 3 runs in 5; run 12 makes it 3 in 6 — runs 7, 8 and 9 succeeded, runs 10, 11 and 12 failed. It is also not AP-driven, which an earlier reading of mine suggested in passing. Runs 8 and 9 succeeded off-AP, so off-AP is 2 of 5 and on-AP 1 of 1 for the solicited build. Drift or a plain low success rate remains the working explanation. Run 12 also sharpens the point that no position threshold exists: its retry at 0.575 slots failed where run 8 succeeded at 0.569. Added the caveat that the monitor drops frames — run 12's window-0 M2 burst is absent from the capture although the ESP's logs imply it was sent — so absence from a capture is never read as absence from the air, and the ESP's own NDP TX Confirm logging is treated as authoritative for acknowledgement. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 88c339d7334..e0db5e0c70b 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -8,8 +8,9 @@ specific defects plus an unexplained off-AP discovery failure. - **Ask 1 (timing) is ready, as a reliability claim rather than a boundary.** The ESP takes ~16 ms to answer an NDP Request and the Discovery Window is 16.384 ms, so the first response always lands at or past the edge and has - never been acknowledged. Setup succeeds only when a retry is heard: 3 runs - in 5. Retry positions overlap across outcomes, so there is no threshold. + never been acknowledged. Setup succeeds only when a retry is heard: **3 runs + in 6** (7, 8, 9 succeeded; 10, 11, 12 failed). Retry positions overlap + across outcomes, so there is no threshold. - **Ask 2 (spurious error) is ready, and is now demonstrably cosmetic.** `Avail: missing a conditional or committed entry` is logged on runs where the NDP **succeeds**, so it never was a negotiation failure. @@ -427,8 +428,9 @@ solicited publish ACKed at DW+1. ### Why there is no boundary, and a check on the measurements -Runs 10 and 11 both failed to establish a data path, with retries at 0.81–0.91 -and 0.76 slots — positions where earlier runs had succeeded. Collected across +Runs 10, 11 and 12 all failed to establish a data path, with retries at +0.81–0.91, 0.76 and 0.575 slots — positions where earlier runs had succeeded. +Run 12's 0.575 is the sharpest: run 8 succeeded at 0.569. Collected across every run with the solicited publisher: **runs 7, 8 and 9 succeeded, runs 10 and 11 failed.** Acknowledged retries at 0.57 and 0.85–0.90 sit *inside* the range of unacknowledged ones at 0.76 to 0.91. The ranges overlap, so the @@ -441,6 +443,12 @@ Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across 593 windows. The proxy anchor is sound and the measurements are not drifting; the erratic outcomes are real. +A caution on absent frames: in run 12 the monitor did not capture a window-0 +M2 burst that the ESP's own logs imply was sent, so the sniffer drops frames. +Nothing here treats "not in the capture" as "not transmitted"; the ESP's +`NDP TX Confirm` logging is the authoritative signal for whether a +transmission was acknowledged. + Two observations constrain what is left. Run 10 saw the **ESP** fail to acknowledge the phone's M1 seven times in one window before accepting it in the next, so intermittent in-window deafness is not one-sided. And runs 10 and @@ -477,7 +485,9 @@ run. end of the 16.384 ms window, where the peer is not reliably listening. The first attempt has **never** been acknowledged in any run. Setup succeeds only when one of the retries happens to be heard, which makes it erratic: - **3 successes in 5 runs** with the solicited publisher. + **3 successes in 6 runs** with the solicited publisher — runs 7, 8 and 9 + succeeded, runs 10, 11 and 12 failed. This is not AP-driven: runs 8 and 9 + succeeded off-AP, so off-AP is 2 of 5 and on-AP 1 of 1. **There is no clean position threshold, and this document previously claimed one.** Retry positions overlap across outcomes: retries at 0.57 and From 96bc8ac15a6f621a27b3bdddda4042fef3f81e49 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:21:15 +0000 Subject: [PATCH 15/30] docs: sniffer dropped frames from run 7 on; central claim survives on retry bits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The monitor began recording ACK frames from run 7, which overflowed its 24-entry queue with neighbouring-BSS traffic. Drops per run: run 3 zero, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 1203. Run 3 is the only fully reliable capture, and for every other run a missing frame or ACK is not evidence of non-transmission, burst sizes are lower bounds, and per-frame acknowledgement columns are unsafe. That would sink the central claim if it depended on seeing ACKs. It does not. The 802.11 retry bit is carried in the transmitted frames themselves and no amount of ACK loss touches it. In run 3, the drop-free capture, the bursts decode as 011 for the follow-up the phone confirmed receiving, and 01111 twice for the two M2 bursts that failed. Frames 2..n carry the retry bit, so attempts 1..n-1 were unacknowledged by the ESP's own MAC; a burst stopping below the limit was acked on its last frame, and a burst running to five exhausted the limit. Dropped entries can only hide frames, so "five frames seen" is reliable evidence of failure while "one frame seen" is not evidence of success. The window-0 M2 burst is five frames in runs 3, 7, 8, 9, 10 and 11, so all six went unacknowledged — including the three runs that later succeeded. Run 12's window-0 burst is simply missing, which its 1203 drops explain. This also resolves a logging ambiguity: successful runs emit no "NDP TX Confirm ... transmission failed" for a window-0 burst that the retry bits show did fail, so that line is logged only when the NDP finally gives up. Absence of it is not evidence a burst succeeded. Drop counters and the diagnosis of their cause come from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 52 +++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index e0db5e0c70b..0cc11d5e4a3 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -443,11 +443,49 @@ Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across 593 windows. The proxy anchor is sound and the measurements are not drifting; the erratic outcomes are real. -A caution on absent frames: in run 12 the monitor did not capture a window-0 -M2 burst that the ESP's own logs imply was sent, so the sniffer drops frames. -Nothing here treats "not in the capture" as "not transmitted"; the ESP's -`NDP TX Confirm` logging is the authoritative signal for whether a -transmission was acknowledged. +### A capture caveat, and why the central claim survives it + +From run 7 onward the monitor also recorded ACK frames, which overflowed its +24-entry queue with neighbouring-BSS traffic. Its own drop counter per run: +run 3 **0**, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 +1203. **Run 3 is the only fully reliable capture.** For every other run, a +missing frame or a missing ACK is not evidence that it never happened, burst +sizes are lower bounds, and any per-frame "not acknowledged" column is +unsafe. + +That would be fatal to the central claim if the claim depended on observing +ACKs. It does not. The evidence is the **802.11 retry bit, carried in the +transmitted frames themselves**, which no amount of ACK loss can affect. + +In run 3, the drop-free capture, the ESP's unicast bursts decode as: + +``` +0 1 1 3 frames — the follow-up. Phone logged it received "Welcome". +0 1 1 1 1 5 frames — M2, first window +0 1 1 1 1 5 frames — M2, retry window +``` + +Frames 2..n carry the retry bit, so attempts 1..n−1 were each unacknowledged +by the ESP's own MAC. A burst that **stops below the limit** was acknowledged +on its last frame; a burst that runs to **five** exhausted the retry limit and +was never acknowledged at all. For M2 every observed burst is five or fewer, +and the failing ones are exactly five. + +The asymmetry matters: dropped capture entries can only *hide* frames, never +invent them. So **"five frames seen" is reliable evidence of failure**, while +"one frame seen" is not evidence of success. + +Applying that to the per-run table, the window-0 M2 burst is five frames in +runs 3, 7, 8, 9, 10 and 11. All six therefore exhausted their retries and went +unacknowledged — including in runs 7, 8 and 9, which went on to succeed on a +later window. Run 12's window-0 burst was not captured at all, which its 1203 +drops amply explain. + +This also resolves an ambiguity in the ESP's logging. Successful runs emit no +`NDP TX Confirm: msg_type=2 transmission failed` for their window-0 burst even +though the retry bits show that burst failed, so the ESP logs that line only +when the NDP finally gives up, not per burst. **Absence of the log is not +evidence that a burst succeeded.** Two observations constrain what is left. Run 10 saw the **ESP** fail to acknowledge the phone's M1 seven times in one window before accepting it in @@ -483,7 +521,9 @@ run. The first NDP Response goes out about 16 ms after the request in every run measured — 0.93, 0.95, 0.97, 1.03 slots — which places it at or past the end of the 16.384 ms window, where the peer is not reliably listening. The - first attempt has **never** been acknowledged in any run. Setup succeeds + first attempt has **never** been acknowledged in any run — established from + retry bits in the transmitted frames, not from captured ACKs, so it is + unaffected by the monitor's frame loss. Setup succeeds only when one of the retries happens to be heard, which makes it erratic: **3 successes in 6 runs** with the solicited publisher — runs 7, 8 and 9 succeeded, runs 10, 11 and 12 failed. This is not AP-driven: runs 8 and 9 From c1d485b0751a337d02bb79b8c087a609750cfd4c Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:23:32 +0000 Subject: [PATCH 16/30] =?UTF-8?q?docs:=20runs=2013-16=20=E2=80=94=20app=20?= =?UTF-8?q?version=20ruled=20out,=20retry=20limit=20evidenced,=20tally=204?= =?UTF-8?q?/10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A/B block settles the app-version question empirically as well as by reasoning: two builds differing only by the probe guard went 0 of 2 and 1 of 2. Solicited-publisher setup is now 4 successes in 10 runs, off-AP 3 of 9 and on-AP 1 of 1. Ask 1's first-M2 figure is widened. It is not constant at about one slot; runs 13 and 16 started at 1.17-1.22, so the measured range is 0.93 to 1.22 slots after the request. Always at or past the window end, and never acknowledged on the first attempt in any run. The "five frames means the retry limit was exhausted" step was an unstated assumption and is now argued. Runs 3 to 6 all predate ACK capture and so are drop-free, not just run 3, which gives a clean comparison: every failing NDP burst runs to exactly five across two frame types and two runs, at about 0.99 ms per frame, while the follow-up path in run 4 ran to 21 frames at about 0.45 ms per frame. Five is specific to the NDP path rather than a universal ceiling. Not proof — the limit lives in the Wi-Fi libraries — but better than coincidence. Issue 3 gains run 16, which answers the question the duplicate-keepalive bug had invalidated: a single keepalive series every 2 s keeps the data path up to the end of a 55 s capture. Run data and the drop-counter diagnosis come from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 44 +++++++++++++++++++++-------- IDF-ISSUE-3-nan-schedule-request.md | 7 +++-- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 0cc11d5e4a3..18e43061881 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -448,7 +448,8 @@ the erratic outcomes are real. From run 7 onward the monitor also recorded ACK frames, which overflowed its 24-entry queue with neighbouring-BSS traffic. Its own drop counter per run: run 3 **0**, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 -1203. **Run 3 is the only fully reliable capture.** For every other run, a +1203. **Runs 3 to 6 are fully reliable**, predating ACK capture; runs 7 onward are +not. For every other run, a missing frame or a missing ACK is not evidence that it never happened, burst sizes are lower bounds, and any per-frame "not acknowledged" column is unsafe. @@ -471,6 +472,25 @@ on its last frame; a burst that runs to **five** exhausted the retry limit and was never acknowledged at all. For M2 every observed burst is five or fewer, and the failing ones are exactly five. +**Is five really the limit?** It is inferred from bursts stopping there, so +it is worth testing. Two drop-free captures give the comparison — runs 3 to 6 +all predate ACK capture and so have no queue loss: + +``` +run 3 M2 5 frames 3.96 ms 0.99 ms/frame +run 3 M2 retry 5 frames 3.68 ms +run 4 M1 dialog 1 5 frames 2.99 ms +run 4 follow-up 21 frames 8.96 ms 0.45 ms/frame +run 3 follow-up 3 frames 1.00 ms (acknowledged, phone confirmed) +``` + +Every NDP-frame burst that failed ran to exactly five, across two different +frame types (M2 and M1) and two runs. The follow-up path demonstrably uses a +different limit — 21 frames, at roughly twice the transmission rate — so five +is not a universal ceiling that happens to be hit, it is specific to the NDP +path. That is not proof of a hardcoded limit of five, which lives in the +Wi-Fi libraries, but it is considerably better than coincidence. + The asymmetry matters: dropped capture entries can only *hide* frames, never invent them. So **"five frames seen" is reliable evidence of failure**, while "one frame seen" is not evidence of success. @@ -518,16 +538,18 @@ run. 1. **Answer an NDP Request promptly, well before the end of the Discovery Window in which it arrived.** - The first NDP Response goes out about 16 ms after the request in every run - measured — 0.93, 0.95, 0.97, 1.03 slots — which places it at or past the - end of the 16.384 ms window, where the peer is not reliably listening. The - first attempt has **never** been acknowledged in any run — established from - retry bits in the transmitted frames, not from captured ACKs, so it is - unaffected by the monitor's frame loss. Setup succeeds - only when one of the retries happens to be heard, which makes it erratic: - **3 successes in 6 runs** with the solicited publisher — runs 7, 8 and 9 - succeeded, runs 10, 11 and 12 failed. This is not AP-driven: runs 8 and 9 - succeeded off-AP, so off-AP is 2 of 5 and on-AP 1 of 1. + The first NDP Response goes out **0.93 to 1.22 slots** after the request in + every run measured — always at or past the end of the 16.384 ms window, + where the peer is not reliably listening. The first attempt has **never** + been acknowledged in any run, established from retry bits in the + transmitted frames rather than from captured ACKs, so it is unaffected by + the monitor's frame loss. + + Setup succeeds only when one of the retries happens to be heard, which + makes it erratic: **4 successes in 10 runs** with the solicited publisher + (8, 9, 16 succeeded off-AP; 7 succeeded on-AP; 10–15 failed). It is not + AP-driven and not app-version driven — an A/B of two app builds differing + by one guard went 0 of 2 and 1 of 2. **There is no clean position threshold, and this document previously claimed one.** Retry positions overlap across outcomes: retries at 0.57 and diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index e04b62f46e1..b5473d30d48 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -113,9 +113,10 @@ logs are visible in the same capture.** ## Impact **An idle NAN data path is torn down about 20 s after it is established.** A -data path carrying traffic is not: in run 9, with the peer sending a probe -every 2 s, the link stayed up for the full 100 s capture with no teardown and -no `eventDataPathTerminated`. +data path carrying traffic is not: in run 9 the link stayed up for the full +100 s capture, and in run 16 — with the duplicate-probe bug fixed, so a +single keepalive series every 2 s rather than two — it stayed up to the end +of a 55 s capture. No teardown and no `eventDataPathTerminated` in either. Traffic also changes how often the peer asks. On an idle link the Schedule Requests came about 6 s apart (runs 7 and 8); with traffic they came about From b092ce0264fafcfce6a2ae57795041a7b1ab40d2 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:31:29 +0000 Subject: [PATCH 17/30] docs: decode every M2 and NAF subtype from the raw captures Analysis from the pcaps for runs 8 to 16 rather than from relayed summaries. NAN Action Frames use OUI type 0x18 with the subtype in the next byte; the Service Discovery Frame uses 0x13 and carries attributes directly, which is what an earlier pass of mine misread. Issue 3 gains the strongest evidence yet. Counting NAF subtypes by sender across all ten captures, the phone sends M1, NDP-Term, Schedule Request and Schedule Update Notification, while the ESP sends M2 and nothing else in any run. Subtype 0x0b, Schedule Response, appears zero times anywhere. Schedule Requests appear only in the three runs that established a data path, and run 9's 17 frames against three logical requests suggests the phone retries each about five or six times before giving up. Issue 2 gains the full M2 burst table. Six independently captured first-window bursts are exactly five frames, never four or six, which supports the retry limit of five far better than the earlier inference; the three short first bursts are all from runs with heavy capture loss. Every fully captured first burst exhausts its attempts, so the first M2 is never acknowledged in any run. Success tracks the second burst being acknowledged on its first frame, but position still does not predict it: run 11 failed at 0.740 where run 9 succeeded at 0.724, and run 13 failed at 0.548 where run 8 succeeded at 0.581. Also recorded: the phone retransmits its own M1 when the ESP fails to acknowledge it, 8 frames in run 10 and 3 in run 9 against 1 elsewhere, so the ESP's receive side misses in-window frames too. That is uncharacterised. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 43 +++++++++++++++++++++++++++++ IDF-ISSUE-3-nan-schedule-request.md | 28 +++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 18e43061881..718f1a5c9a9 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -443,6 +443,49 @@ Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across 593 windows. The proxy anchor is sound and the measurements are not drifting; the erratic outcomes are real. +### Every M2 burst, decoded from the raw captures + +Read directly from the pcaps for runs 8 to 16 rather than from summaries, +filtering on NAF OUI type `0x18` subtype `0x06`. Offsets are in slots from the +preceding group-addressed frame from the phone. + +| run | first M2 | second M2 | outcome | +|---|---|---|---| +| 8 | 5 fr @ 1.027 | 1 fr @ 0.581 | OK | +| 9 | 5 fr @ 1.028 | 1 fr @ 0.724 | OK | +| 10 | 5 fr @ 0.924 | 5 fr @ 0.803 | FAIL | +| 11 | 5 fr @ 1.001 | 5 fr @ 0.740 | FAIL | +| 12 | 1 fr @ 0.554 *(w0 burst dropped)* | — | FAIL | +| 13 | 3 fr @ 1.208 *(truncated)* | 5 fr @ 0.548 | FAIL | +| 14 | 1 fr @ 0.899 *(truncated)* | — | FAIL | +| 15 | 5 fr @ 0.925 | 2 fr @ 0.816 | FAIL | +| 16 | 5 fr @ 1.165 | 1 fr @ 0.395 | OK | + +Three things fall out of this that the summaries did not show. + +**The retry limit of five is now well supported.** Six independently captured +first-window bursts — runs 8, 9, 10, 11, 15, 16 — are *exactly* five frames. +Never four, never six. Adding the second-window bursts in runs 10, 11 and 13 +gives nine bursts of exactly five. Runs 12, 13 and 14 show short first bursts +and all three had heavy capture loss. + +**The first M2 is never acknowledged, in any run.** Every fully captured +first burst exhausts its five attempts. Measured first-M2 offsets: 0.924, +0.925, 1.001, 1.027, 1.028, 1.165 slots, plus truncated bursts at 0.899 and +1.208. + +**Success tracks the second burst being acknowledged immediately.** Runs 8, 9 +and 16 each have a single-frame second burst — acknowledged first try. Runs +10, 11 and 13 run to five again and fail. But position still does not explain +which: run 11's second burst at 0.740 failed while run 9's at 0.724 succeeded, +and run 13's at 0.548 failed while run 8's at 0.581 succeeded. Adjacent +offsets, opposite outcomes. **The threshold stays dead.** + +One further observation from the same decode: the phone retransmits its own +M1 when the ESP does not acknowledge it — 8 frames in run 10 and 3 in run 9 +against 1 elsewhere. The ESP's receive side misses frames in the window too, +and that is not characterised at all. + ### A capture caveat, and why the central claim survives it From run 7 onward the monitor also recorded ACK frames, which overflowed its diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index b5473d30d48..d90699a026e 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -58,6 +58,34 @@ itself committed to** (`crb1=[2,31]`). This is the peer doing the right thing and converting a conditional arrangement into a committed one. The ESP ignores it. +## Confirmed across every capture + +NAN Action Frames are Public Action / Vendor Specific / WFA OUI with **OUI +type `0x18`** and the subtype in the following byte. (The Service Discovery +Frame uses OUI type `0x13` instead, and carries attributes directly.) +Counting subtypes by sender across all ten captures — runs 3 and 8 to 16: + +| sender | subtypes ever transmitted | +|---|---| +| phone | `0x05` M1, `0x09` NDP-Term, **`0x0a` Schedule Request**, `0x0d` Schedule Update Notification | +| ESP | **`0x06` M2 — and nothing else, in any run** | + +**Subtype `0x0b`, Schedule Response, appears zero times in any capture.** The +ESP transmits exactly one NAF subtype across every run: the NDP Response. It +never sends a Schedule Response, never a Schedule Confirm, and never an NDP +Termination of its own. + +Schedule Requests appear only in the three runs that established a data path, +which is expected — runs 8 (2 frames), 9 (17) and 16 (1). The phone also sends +Schedule Update Notifications in all three: 3, 5 and 5 frames. None is ever +answered. + +Run 9's 17 frames are worth a note. The bench session reports three *logical* +Schedule Requests in that run, so the phone appears to retry each one roughly +five or six times before giving up — the same shape as the ESP's own M2 +bursts. The phone is not asking once and forgetting; it is asking +insistently and being ignored. + ## Mechanism, from the binary `ieee80211_nan_datapath.o` in `libnet80211.a` (esp32). The receive dispatcher From 91e41bac35e74e98c43afa329a7c8f2e1a8ca084 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:33:02 +0000 Subject: [PATCH 18/30] docs: correct the ESP's NAF subtype set in issue 3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The draft said the ESP transmits exactly one NAF subtype ever, M2. That was true only of the subset examined — runs 3 and 8 to 16, where the ESP was always the NDP responder — and overstated what the captures show. Run 4, where the ESP ran as subscriber and initiated, has it sending M1 six times, and run 7 has it sending one NDP Termination. Verified for run 4 from the capture, which was in hand and simply missing from the earlier tally; run 7 is from the bench session. Runs 5 and 6b contain no NAFs at all, since discovery never completed. The accurate statement is stronger anyway: the ESP sends only NDP setup and teardown frames, subtypes 5, 6 and 9, and never anything in 0x0a to 0x0d. That is exactly the set the binary has handlers for — nan_rx_naf parses 5 to 9, and the object carries construct and send functions for the same range — so the on-air behaviour and the binary agree precisely about what this implementation can do. Schedule Response still appears zero times in any capture while the phone sends Schedule Requests repeatedly, which is the point the section exists to make. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-3-nan-schedule-request.md | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index d90699a026e..68d55b3954e 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -63,17 +63,24 @@ it. NAN Action Frames are Public Action / Vendor Specific / WFA OUI with **OUI type `0x18`** and the subtype in the following byte. (The Service Discovery Frame uses OUI type `0x13` instead, and carries attributes directly.) -Counting subtypes by sender across all ten captures — runs 3 and 8 to 16: +Counting subtypes by sender across every capture — runs 3 to 16: | sender | subtypes ever transmitted | |---|---| -| phone | `0x05` M1, `0x09` NDP-Term, **`0x0a` Schedule Request**, `0x0d` Schedule Update Notification | -| ESP | **`0x06` M2 — and nothing else, in any run** | +| phone | `0x05` M1, `0x06` M2, `0x09` NDP-Term, **`0x0a` Schedule Request**, `0x0d` Schedule Update Notification | +| ESP | `0x05` M1, `0x06` M2, `0x09` NDP-Term — **and nothing else, in any run** | -**Subtype `0x0b`, Schedule Response, appears zero times in any capture.** The -ESP transmits exactly one NAF subtype across every run: the NDP Response. It -never sends a Schedule Response, never a Schedule Confirm, and never an NDP -Termination of its own. +The ESP sends only NDP **setup and teardown** frames: M1 when it initiates +(run 4, as subscriber), M2 when it responds, and one NDP Termination (run 7). +**It never transmits any subtype in the range `0x0a`–`0x0d`.** + +That set — 5, 6, 9 — is exactly the set the binary has handlers for. The +dispatcher `nan_rx_naf` parses 5 to 9 and the object carries construct and +send functions for the same range, so the on-air behaviour and the binary +agree precisely about what this implementation can do. + +**Subtype `0x0b`, Schedule Response, appears zero times in any capture**, +while the phone sends Schedule Requests repeatedly. Schedule Requests appear only in the three runs that established a data path, which is expected — runs 8 (2 frames), 9 (17) and 16 (1). The phone also sends From dfcb21bda085a00b21b6049f3df8fb9d45766a89 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:40:05 +0000 Subject: [PATCH 19/30] docs: withdraw the burst-length oracle; six clean runs change three claims MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runs 17-22 used a rebuilt sniffer with zero drops in every run, which refutes an argument this document carried and sharpens two others. Withdrawn: that a five-frame burst means the retry limit was exhausted and the frame went unacknowledged, while a shorter burst was acknowledged on its last frame. Run 22's second window is five frames with the fifth acknowledged, and run 18's first window is two frames with no acknowledgement and no success, both in zero-drop captures. Burst length is not an outcome oracle. It was a reasonable inference when loss made it the only signal immune to the drops, and it is wrong. ACK-by-RA is now the oracle. Corrected: "the first window never succeeds". Run 21's retry at 0.972 slots was acknowledged and the data path came up without a second window, so the ESP can close the exchange inside the window the request arrived in. What survives is narrower — the first transmission attempt has never been acknowledged in any of sixteen runs, including run 21. Corrected: the first-window M2 offset. It is not fixed near one slot but spans 0.92 to 2.12 slots, with runs 17 and 22 landing past slot 1 entirely. The earlier 0.93-1.22 figure came from too few runs. New and uncharacterised: in runs 18, 20 and 22 the ESP acknowledged the phone's M1 and the phone retransmitted anyway. A station is necessarily receiving during the SIFS after its own transmission, so the phone did not receive or decode the ESP's ACK — which is not a "not listening at that instant" effect and suggests a different model for the missed M2s and follow-ups seen throughout. New defect candidate: run 19 failed with no M2 on the air at all despite zero capture drops, while the ESP logged building it twice. It transmitted unicast SDF retries to the phone instead. Single observation, needs repeats. Setup is now 9 successes in 16 runs. All run data from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 155 ++++++++++++++++++++-------- 1 file changed, 112 insertions(+), 43 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 718f1a5c9a9..f6d21438dc3 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -515,28 +515,105 @@ on its last frame; a burst that runs to **five** exhausted the retry limit and was never acknowledged at all. For M2 every observed burst is five or fewer, and the failing ones are exactly five. -**Is five really the limit?** It is inferred from bursts stopping there, so -it is worth testing. Two drop-free captures give the comparison — runs 3 to 6 -all predate ACK capture and so have no queue loss: +**The burst-length oracle is withdrawn.** An earlier revision of this +document argued that a burst running to five meant the retry limit was +exhausted and the frame was never acknowledged, while a burst stopping short +had been acknowledged on its last frame. Six clean runs with a zero-drop +capture refute both halves: + +- **Run 22, second window:** five frames, and the **fifth was acknowledged**. + A five-frame burst can succeed. +- **Run 18, first window:** two frames, **no acknowledgement**, no success, + in a capture with zero drops. A burst can stop short without being + acknowledged. + +Burst length is not an outcome oracle. It was a reasonable inference from the +drop-afflicted captures, where it was the only signal immune to the loss, and +it is simply wrong. Why the ESP sometimes stops at two and sometimes runs to +five is not known. + +With a zero-drop sniffer filtering ACKs to known NAN NMIs, **ACK-by-RA is now +the oracle**, corroborated by the ESP and phone logs. Everything below that +depends on burst length has been restated accordingly. + +### The clean runs + +Runs 17 to 22 used a rebuilt sniffer — PSRAM queue, ACKs filtered to known +NAN NMIs — and recorded **zero drops in every run**. Five of six established +a data path. + +| run | first-window M2 | second-window M2 | outcome | +|---|---|---|---| +| 17 | 5 fr @ 1.59–1.69, no ACK | 2 fr @ 0.44–0.47, **ACK** | OK | +| 18 | 2 fr @ 1.03–1.11, no ACK | 3 fr @ 0.66–0.74, **ACK** | OK | +| 19 | **no M2 on air at all** | — | FAIL | +| 20 | 5 fr @ 0.92–1.17, no ACK | 1 fr @ 0.26, **ACK** | OK | +| 21 | 2 fr @ 0.93–0.97, **ACK** | — | OK | +| 22 | 5 fr @ 2.02–2.12, no ACK | 5 fr @ 0.23–0.33, **ACK on the 5th** | OK | + +**Run 21 refutes "the first window never succeeds".** Its retry at 0.972 +slots — about 0.45 ms before the end of slot 0 — was acknowledged, and the +data path came up without ever needing a second window. The ESP *can* close +the exchange inside the Discovery Window the request arrived in. + +The first *transmission attempt* has still never been acknowledged in any +run, including run 21, where the frame at 0.934 went unacknowledged and only +the retry at 0.972 was taken. That is the narrow claim ask 1 now rests on. + +**The first-window offset is not fixed near one slot.** Across all runs it +spans **0.92 to 2.12 slots** — run 17 at 1.59 and run 22 at 2.02 land well +past slot 1 entirely. An earlier figure of 0.93–1.22 here was taken from too +few runs. + +### A capture caveat, and why the central claim survives it + +From run 7 onward the monitor also recorded ACK frames, which overflowed its +24-entry queue with neighbouring-BSS traffic. Its own drop counter per run: +run 3 **0**, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 +1203. **Runs 3 to 6 are fully reliable**, predating ACK capture; runs 7 onward are +not. For every other run, a +missing frame or a missing ACK is not evidence that it never happened, burst +sizes are lower bounds, and any per-frame "not acknowledged" column is +unsafe. + +That would be fatal to the central claim if the claim depended on observing +ACKs. It does not. The evidence is the **802.11 retry bit, carried in the +transmitted frames themselves**, which no amount of ACK loss can affect. + +In run 3, the drop-free capture, the ESP's unicast bursts decode as: ``` -run 3 M2 5 frames 3.96 ms 0.99 ms/frame -run 3 M2 retry 5 frames 3.68 ms -run 4 M1 dialog 1 5 frames 2.99 ms -run 4 follow-up 21 frames 8.96 ms 0.45 ms/frame -run 3 follow-up 3 frames 1.00 ms (acknowledged, phone confirmed) +0 1 1 3 frames — the follow-up. Phone logged it received "Welcome". +0 1 1 1 1 5 frames — M2, first window +0 1 1 1 1 5 frames — M2, retry window ``` -Every NDP-frame burst that failed ran to exactly five, across two different -frame types (M2 and M1) and two runs. The follow-up path demonstrably uses a -different limit — 21 frames, at roughly twice the transmission rate — so five -is not a universal ceiling that happens to be hit, it is specific to the NDP -path. That is not proof of a hardcoded limit of five, which lives in the -Wi-Fi libraries, but it is considerably better than coincidence. +Frames 2..n carry the retry bit, so attempts 1..n−1 were each unacknowledged +by the ESP's own MAC. A burst that **stops below the limit** was acknowledged +on its last frame; a burst that runs to **five** exhausted the retry limit and +was never acknowledged at all. For M2 every observed burst is five or fewer, +and the failing ones are exactly five. + +**The burst-length oracle is withdrawn.** An earlier revision of this +document argued that a burst running to five meant the retry limit was +exhausted and the frame was never acknowledged, while a burst stopping short +had been acknowledged on its last frame. Six clean runs with a zero-drop +capture refute both halves: + +- **Run 22, second window:** five frames, and the **fifth was acknowledged**. + A five-frame burst can succeed. +- **Run 18, first window:** two frames, **no acknowledgement**, no success, + in a capture with zero drops. A burst can stop short without being + acknowledged. -The asymmetry matters: dropped capture entries can only *hide* frames, never -invent them. So **"five frames seen" is reliable evidence of failure**, while -"one frame seen" is not evidence of success. +Burst length is not an outcome oracle. It was a reasonable inference from the +drop-afflicted captures, where it was the only signal immune to the loss, and +it is simply wrong. Why the ESP sometimes stops at two and sometimes runs to +five is not known. + +With a zero-drop sniffer filtering ACKs to known NAN NMIs, **ACK-by-RA is now +the oracle**, corroborated by the ESP and phone logs. Everything below that +depends on burst length has been restated accordingly. Applying that to the per-run table, the window-0 M2 burst is five frames in runs 3, 7, 8, 9, 10 and 11. All six therefore exhausted their retries and went @@ -578,32 +655,24 @@ run. ## Asks -1. **Answer an NDP Request promptly, well before the end of the Discovery - Window in which it arrived.** - - The first NDP Response goes out **0.93 to 1.22 slots** after the request in - every run measured — always at or past the end of the 16.384 ms window, - where the peer is not reliably listening. The first attempt has **never** - been acknowledged in any run, established from retry bits in the - transmitted frames rather than from captured ACKs, so it is unaffected by - the monitor's frame loss. - - Setup succeeds only when one of the retries happens to be heard, which - makes it erratic: **4 successes in 10 runs** with the solicited publisher - (8, 9, 16 succeeded off-AP; 7 succeeded on-AP; 10–15 failed). It is not - AP-driven and not app-version driven — an A/B of two app builds differing - by one guard went 0 of 2 and 1 of 2. - - **There is no clean position threshold, and this document previously - claimed one.** Retry positions overlap across outcomes: retries at 0.57 and - 0.85–0.90 slots were acknowledged, while retries at 0.76 and 0.81–0.91 were - not. Position within the window does not by itself determine whether a - frame is heard. - - The ask therefore rests on the first attempt being consistently too late - and on the resulting unreliability, not on a boundary. Reducing the - response latency so M2 lands early in the window it belongs to would make - setup deterministic instead of depending on a retry being lucky. +1. **Answer an NDP Request on the first attempt, early enough in the + Discovery Window to leave room for retries.** + + The first transmission attempt has **never** been acknowledged in any of + the sixteen runs measured. The ESP's first-window M2 starts anywhere from + 0.92 to 2.12 slots after the request, sometimes past slot 1 entirely, so + it routinely arrives where the peer is not reliably receiving. Setup then + depends on a retry being taken, and across sixteen runs it succeeded + **9 times** — 5 of 6 in the clean zero-drop block, 4 of 10 before it. + + Run 21 shows the exchange *can* complete inside the request's own window: + a retry at 0.972 slots was acknowledged and the data path came up without + a second window. So this is a latency and margin problem, not an + impossibility. + + **There is no position threshold.** Acknowledged and unacknowledged + attempts overlap throughout the range, in both directions, across all + sixteen runs. 2. **Do not log "missing a conditional or committed entry" for a map that legitimately carries only Potential entries.** Run 7 confirms this error is From d093e30567cad995607bbd22a686d9ee35241a98 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:41:27 +0000 Subject: [PATCH 20/30] docs: finish the clean-run rewrite and deduplicate the section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous commit, dfcb21bda0, has a message describing changes that were not in it. Two of three edits failed on an assertion while the commit went ahead regardless, so it landed the ask 1 rewrite alone and left the document carrying the refuted claims its message said had been removed, plus a duplicated "capture caveat" heading from an earlier slice edit. This commit finishes the job and removes the duplicate. Now actually present: the burst-length oracle is withdrawn, with run 22's five-frame burst whose fifth frame was acknowledged and run 18's two-frame burst with no acknowledgement and no success, both from zero-drop captures. The runs 8-16 table keeps only what survives — position does not predict outcome — and the stale "retry limit of five is well supported" and "first M2 is never acknowledged in any run" paragraphs are gone. Added: the clean runs 17-22 table; run 21 acknowledging inside the request's own window, which refutes "the first window never succeeds"; the first-window offset range widened to 0.92-2.12 slots; the observation that the phone retransmits M1 after the ESP has acknowledged it, which cannot be a wake-state effect since a station receives during the SIFS after its own transmission; and run 19, where no M2 reached the air at all despite zero drops while the ESP logged building it twice and sent unicast SDF retries instead. Setup is 9 successes in 16 runs. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 235 ++++++++++------------------ 1 file changed, 81 insertions(+), 154 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index f6d21438dc3..9292e4e95e6 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -6,11 +6,11 @@ an ESP32 — so this is no longer "NAN is broken with Android". It is two specific defects plus an unexplained off-AP discovery failure. - **Ask 1 (timing) is ready, as a reliability claim rather than a boundary.** - The ESP takes ~16 ms to answer an NDP Request and the Discovery Window is - 16.384 ms, so the first response always lands at or past the edge and has - never been acknowledged. Setup succeeds only when a retry is heard: **3 runs - in 6** (7, 8, 9 succeeded; 10, 11, 12 failed). Retry positions overlap - across outcomes, so there is no threshold. + The ESP's first NDP Response attempt has never been acknowledged in any of + 16 runs, and it starts anywhere from 0.92 to 2.12 slots after the request. + Setup therefore depends on a retry being taken, and succeeded **9 times in + 16** — 5 of 6 in the zero-drop block. Acknowledged and unacknowledged + attempts overlap throughout the range, so there is no threshold. - **Ask 2 (spurious error) is ready, and is now demonstrably cosmetic.** `Avail: missing a conditional or committed entry` is logged on runs where the NDP **succeeds**, so it never was a negotiation failure. @@ -443,11 +443,25 @@ Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across 593 windows. The proxy anchor is sound and the measurements are not drifting; the erratic outcomes are real. -### Every M2 burst, decoded from the raw captures +### Capture reliability -Read directly from the pcaps for runs 8 to 16 rather than from summaries, -filtering on NAF OUI type `0x18` subtype `0x06`. Offsets are in slots from the -preceding group-addressed frame from the phone. +From run 7 the monitor also recorded ACK frames, which overflowed its +24-entry queue with neighbouring-BSS traffic. Drops per run: run 3 **0**, +run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 1203. **Runs 3 +to 6 are reliable**, predating ACK capture; runs 7 to 16 are not — a missing +frame or ACK there is not evidence it never happened, and burst sizes are +lower bounds. + +Runs 17 to 22 used a rebuilt sniffer, PSRAM queue with ACKs filtered to known +NAN NMIs, and recorded **zero drops in every run**. Those are the runs to +trust. + +### Every M2 burst, runs 8 to 16 + +Decoded from the pcaps rather than from summaries, filtering on NAF OUI type +`0x18` subtype `0x06`. Offsets in slots from the preceding group-addressed +frame from the phone. These runs all have capture loss, so burst sizes are +lower bounds. | run | first M2 | second M2 | outcome | |---|---|---|---| @@ -455,92 +469,41 @@ preceding group-addressed frame from the phone. | 9 | 5 fr @ 1.028 | 1 fr @ 0.724 | OK | | 10 | 5 fr @ 0.924 | 5 fr @ 0.803 | FAIL | | 11 | 5 fr @ 1.001 | 5 fr @ 0.740 | FAIL | -| 12 | 1 fr @ 0.554 *(w0 burst dropped)* | — | FAIL | +| 12 | 1 fr @ 0.554 *(w0 dropped)* | — | FAIL | | 13 | 3 fr @ 1.208 *(truncated)* | 5 fr @ 0.548 | FAIL | | 14 | 1 fr @ 0.899 *(truncated)* | — | FAIL | | 15 | 5 fr @ 0.925 | 2 fr @ 0.816 | FAIL | | 16 | 5 fr @ 1.165 | 1 fr @ 0.395 | OK | -Three things fall out of this that the summaries did not show. - -**The retry limit of five is now well supported.** Six independently captured -first-window bursts — runs 8, 9, 10, 11, 15, 16 — are *exactly* five frames. -Never four, never six. Adding the second-window bursts in runs 10, 11 and 13 -gives nine bursts of exactly five. Runs 12, 13 and 14 show short first bursts -and all three had heavy capture loss. - -**The first M2 is never acknowledged, in any run.** Every fully captured -first burst exhausts its five attempts. Measured first-M2 offsets: 0.924, -0.925, 1.001, 1.027, 1.028, 1.165 slots, plus truncated bursts at 0.899 and -1.208. - -**Success tracks the second burst being acknowledged immediately.** Runs 8, 9 -and 16 each have a single-frame second burst — acknowledged first try. Runs -10, 11 and 13 run to five again and fail. But position still does not explain -which: run 11's second burst at 0.740 failed while run 9's at 0.724 succeeded, -and run 13's at 0.548 failed while run 8's at 0.581 succeeded. Adjacent -offsets, opposite outcomes. **The threshold stays dead.** - -One further observation from the same decode: the phone retransmits its own -M1 when the ESP does not acknowledge it — 8 frames in run 10 and 3 in run 9 -against 1 elsewhere. The ESP's receive side misses frames in the window too, -and that is not characterised at all. - -### A capture caveat, and why the central claim survives it +Position does not predict outcome: run 11's second burst at 0.740 failed +where run 9's at 0.724 succeeded, and run 13's at 0.548 failed where run 8's +at 0.581 succeeded. Adjacent offsets, opposite outcomes. -From run 7 onward the monitor also recorded ACK frames, which overflowed its -24-entry queue with neighbouring-BSS traffic. Its own drop counter per run: -run 3 **0**, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 -1203. **Runs 3 to 6 are fully reliable**, predating ACK capture; runs 7 onward are -not. For every other run, a -missing frame or a missing ACK is not evidence that it never happened, burst -sizes are lower bounds, and any per-frame "not acknowledged" column is -unsafe. +Also visible here: the phone retransmits its own M1 when the ESP does not +acknowledge it — 8 frames in run 10 and 3 in run 9 against 1 elsewhere. -That would be fatal to the central claim if the claim depended on observing -ACKs. It does not. The evidence is the **802.11 retry bit, carried in the -transmitted frames themselves**, which no amount of ACK loss can affect. +### The burst-length oracle is withdrawn -In run 3, the drop-free capture, the ESP's unicast bursts decode as: - -``` -0 1 1 3 frames — the follow-up. Phone logged it received "Welcome". -0 1 1 1 1 5 frames — M2, first window -0 1 1 1 1 5 frames — M2, retry window -``` - -Frames 2..n carry the retry bit, so attempts 1..n−1 were each unacknowledged -by the ESP's own MAC. A burst that **stops below the limit** was acknowledged -on its last frame; a burst that runs to **five** exhausted the retry limit and -was never acknowledged at all. For M2 every observed burst is five or fewer, -and the failing ones are exactly five. - -**The burst-length oracle is withdrawn.** An earlier revision of this -document argued that a burst running to five meant the retry limit was -exhausted and the frame was never acknowledged, while a burst stopping short -had been acknowledged on its last frame. Six clean runs with a zero-drop -capture refute both halves: +An earlier revision argued that a burst running to five meant the retry limit +was exhausted and the frame went unacknowledged, while a burst stopping short +had been acknowledged on its last frame. The zero-drop runs refute both +halves: - **Run 22, second window:** five frames, and the **fifth was acknowledged**. A five-frame burst can succeed. - **Run 18, first window:** two frames, **no acknowledgement**, no success, - in a capture with zero drops. A burst can stop short without being + with zero drops in that capture. A burst can stop short without being acknowledged. -Burst length is not an outcome oracle. It was a reasonable inference from the -drop-afflicted captures, where it was the only signal immune to the loss, and -it is simply wrong. Why the ESP sometimes stops at two and sometimes runs to -five is not known. - -With a zero-drop sniffer filtering ACKs to known NAN NMIs, **ACK-by-RA is now -the oracle**, corroborated by the ESP and phone logs. Everything below that -depends on burst length has been restated accordingly. +Burst length is not an outcome oracle. It was a reasonable inference when +capture loss made it the only signal immune to the drops, and it is wrong. +Why the ESP sometimes stops at two and sometimes runs to five is unknown. +**ACK-by-RA from the rebuilt sniffer is the oracle**, corroborated by the ESP +and phone logs. -### The clean runs +### The clean runs, 17 to 22 -Runs 17 to 22 used a rebuilt sniffer — PSRAM queue, ACKs filtered to known -NAN NMIs — and recorded **zero drops in every run**. Five of six established -a data path. +Zero drops in every run; five of six established a data path. | run | first-window M2 | second-window M2 | outcome | |---|---|---|---| @@ -552,86 +515,50 @@ a data path. | 22 | 5 fr @ 2.02–2.12, no ACK | 5 fr @ 0.23–0.33, **ACK on the 5th** | OK | **Run 21 refutes "the first window never succeeds".** Its retry at 0.972 -slots — about 0.45 ms before the end of slot 0 — was acknowledged, and the -data path came up without ever needing a second window. The ESP *can* close -the exchange inside the Discovery Window the request arrived in. +slots, about 0.45 ms before the end of slot 0, was acknowledged and the data +path came up without a second window ever being needed. The ESP *can* close +the exchange inside the window the request arrived in. The first *transmission attempt* has still never been acknowledged in any run, including run 21, where the frame at 0.934 went unacknowledged and only -the retry at 0.972 was taken. That is the narrow claim ask 1 now rests on. +the retry at 0.972 was taken. That is the narrow claim ask 1 rests on. **The first-window offset is not fixed near one slot.** Across all runs it -spans **0.92 to 2.12 slots** — run 17 at 1.59 and run 22 at 2.02 land well -past slot 1 entirely. An earlier figure of 0.93–1.22 here was taken from too -few runs. - -### A capture caveat, and why the central claim survives it - -From run 7 onward the monitor also recorded ACK frames, which overflowed its -24-entry queue with neighbouring-BSS traffic. Its own drop counter per run: -run 3 **0**, run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 -1203. **Runs 3 to 6 are fully reliable**, predating ACK capture; runs 7 onward are -not. For every other run, a -missing frame or a missing ACK is not evidence that it never happened, burst -sizes are lower bounds, and any per-frame "not acknowledged" column is -unsafe. - -That would be fatal to the central claim if the claim depended on observing -ACKs. It does not. The evidence is the **802.11 retry bit, carried in the -transmitted frames themselves**, which no amount of ACK loss can affect. - -In run 3, the drop-free capture, the ESP's unicast bursts decode as: - -``` -0 1 1 3 frames — the follow-up. Phone logged it received "Welcome". -0 1 1 1 1 5 frames — M2, first window -0 1 1 1 1 5 frames — M2, retry window -``` - -Frames 2..n carry the retry bit, so attempts 1..n−1 were each unacknowledged -by the ESP's own MAC. A burst that **stops below the limit** was acknowledged -on its last frame; a burst that runs to **five** exhausted the retry limit and -was never acknowledged at all. For M2 every observed burst is five or fewer, -and the failing ones are exactly five. - -**The burst-length oracle is withdrawn.** An earlier revision of this -document argued that a burst running to five meant the retry limit was -exhausted and the frame was never acknowledged, while a burst stopping short -had been acknowledged on its last frame. Six clean runs with a zero-drop -capture refute both halves: - -- **Run 22, second window:** five frames, and the **fifth was acknowledged**. - A five-frame burst can succeed. -- **Run 18, first window:** two frames, **no acknowledgement**, no success, - in a capture with zero drops. A burst can stop short without being - acknowledged. - -Burst length is not an outcome oracle. It was a reasonable inference from the -drop-afflicted captures, where it was the only signal immune to the loss, and -it is simply wrong. Why the ESP sometimes stops at two and sometimes runs to -five is not known. - -With a zero-drop sniffer filtering ACKs to known NAN NMIs, **ACK-by-RA is now -the oracle**, corroborated by the ESP and phone logs. Everything below that -depends on burst length has been restated accordingly. - -Applying that to the per-run table, the window-0 M2 burst is five frames in -runs 3, 7, 8, 9, 10 and 11. All six therefore exhausted their retries and went -unacknowledged — including in runs 7, 8 and 9, which went on to succeed on a -later window. Run 12's window-0 burst was not captured at all, which its 1203 -drops amply explain. - -This also resolves an ambiguity in the ESP's logging. Successful runs emit no -`NDP TX Confirm: msg_type=2 transmission failed` for their window-0 burst even -though the retry bits show that burst failed, so the ESP logs that line only -when the NDP finally gives up, not per burst. **Absence of the log is not -evidence that a burst succeeded.** - -Two observations constrain what is left. Run 10 saw the **ESP** fail to -acknowledge the phone's M1 seven times in one window before accepting it in -the next, so intermittent in-window deafness is not one-sided. And runs 10 and -11 carried a confound: a "Google Play isn't responding" dialog may have taken -the test app out of the foreground for part of them. +spans **0.92 to 2.12 slots** — runs 17 at 1.59 and 22 at 2.02 land past slot +1 entirely. An earlier figure of 0.93–1.22 came from too few runs. + +### The peer misses the ESP's frames, including its ACKs + +In runs 18 (second window), 20 and 22 the **ESP acknowledged the phone's M1 +and the phone retransmitted it anyway**. A station is necessarily receiving +during the SIFS immediately after its own transmission — that is when an ACK +must arrive — so this cannot be the phone "not listening at that instant". +The phone did not receive, or did not decode, the ESP's acknowledgement. + +The converse also happens: in run 18's first window the phone sent M1 seven +times and the ESP acknowledged none, then acknowledged four copies in the +next window. + +So **both ends intermittently fail to receive in-window frames from the +other**, and on the phone's side it is demonstrably not a wake-state effect. +That is a materially different model from "the ESP transmits too late and the +peer has stopped listening", and it may underlie the unacknowledged M2s and +follow-ups seen throughout. It is not characterised and nothing should be +filed about it yet. + +### Run 19: M2 constructed and never transmitted + +The only failure in the clean block failed differently. With **zero capture +drops** there is **no M2 on the air at all**, while the ESP's own log says it +built M2 twice, reported `TX Confirm failed`, and rejected the request. In +its place the ESP transmitted **unicast Service Discovery Frames** to the +phone: 14 frames at roughly M1 + 529–548 ms, all retries after the first, +none acknowledged, then 3 more at about +1050 ms. + +A response constructed and then never transmitted is a different defect from +one transmitted too late, and substituting SDF retries for it is stranger +still. Single observation; it needs repeats. It is only visible because the +capture had no losses. ### The 20 s teardown From e2dde4b3e5ef085fd461628013c7f2c995c6009f Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:44:16 +0000 Subject: [PATCH 21/30] docs: withdraw "the phone misses the ESP's ACKs"; verify the rest from the pcaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decoded runs 17-22 directly rather than working from summaries, matching each ACK to the frame it immediately follows. Withdrawn: that the phone fails to receive the ESP's acknowledgements. It rests on a single instance — run 18's second window, where M1 #10 was acknowledged and the phone sent #11 about 180 microseconds later. In runs 20 and 22 the phone stopped transmitting the moment it was acknowledged, which is correct. One extra frame at 180 us is better explained as a retry already queued in hardware than as a reception failure, so the model built on it is not supported. The other half holds and is kept: the ESP misses M1 repeatedly. Run 18's first window has seven M1 transmissions with no ESP acknowledgement at all, run 20's first goes unacknowledged, run 22's first three do. Confirmed directly, no longer by inference: the first M2 transmission attempt is unacknowledged in all five clean runs that transmitted one. In run 21 the opening frame at 0.946 slots is followed 617 us later by its own retry, and the retry at 0.984 is what gets acknowledged. A methodological note is included because it caused the error. An ACK is the frame immediately following the one it acknowledges; matching any ACK to the transmitter within a 1 ms window credits one ACK to two frames of a burst, which initially made run 21's first attempt look acknowledged. Table offsets re-derived from the captures. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 67 ++++++++++++++++++----------- 1 file changed, 41 insertions(+), 26 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 9292e4e95e6..1dbf3990054 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -507,12 +507,15 @@ Zero drops in every run; five of six established a data path. | run | first-window M2 | second-window M2 | outcome | |---|---|---|---| -| 17 | 5 fr @ 1.59–1.69, no ACK | 2 fr @ 0.44–0.47, **ACK** | OK | -| 18 | 2 fr @ 1.03–1.11, no ACK | 3 fr @ 0.66–0.74, **ACK** | OK | +| 17 | 5 fr @ 1.58–1.68, none acked | 2 fr @ 0.42–0.46, **1st acked** | OK | +| 18 | 2 fr @ 0.96–1.04, none acked | 3 fr @ 0.75–0.83, **3rd acked** | OK | | 19 | **no M2 on air at all** | — | FAIL | -| 20 | 5 fr @ 0.92–1.17, no ACK | 1 fr @ 0.26, **ACK** | OK | -| 21 | 2 fr @ 0.93–0.97, **ACK** | — | OK | -| 22 | 5 fr @ 2.02–2.12, no ACK | 5 fr @ 0.23–0.33, **ACK on the 5th** | OK | +| 20 | 5 fr @ 0.96–1.21, none acked | 1 fr @ 0.24, **acked** | OK | +| 21 | 2 fr @ 0.95–0.98, **2nd acked** | — | OK | +| 22 | 5 fr @ 2.05–2.15, none acked | 5 fr @ 0.22–0.33, **5th acked** | OK | + +Offsets and acknowledgements re-derived from the pcaps, with each ACK matched +to the frame it immediately follows. **Run 21 refutes "the first window never succeeds".** Its retry at 0.972 slots, about 0.45 ms before the end of slot 0, was acknowledged and the data @@ -520,32 +523,44 @@ path came up without a second window ever being needed. The ESP *can* close the exchange inside the window the request arrived in. The first *transmission attempt* has still never been acknowledged in any -run, including run 21, where the frame at 0.934 went unacknowledged and only -the retry at 0.972 was taken. That is the narrow claim ask 1 rests on. +run. That is now **direct** evidence rather than inference: in all five clean +runs that put an M2 on the air, the opening frame of the first burst has no +ACK immediately following it. In run 21 the frame at 0.946 slots is followed +617 µs later by its own retry, and it is that retry, at 0.984, which the +phone acknowledges. This is the narrow claim ask 1 rests on. **The first-window offset is not fixed near one slot.** Across all runs it spans **0.92 to 2.12 slots** — runs 17 at 1.59 and 22 at 2.02 land past slot 1 entirely. An earlier figure of 0.93–1.22 came from too few runs. -### The peer misses the ESP's frames, including its ACKs - -In runs 18 (second window), 20 and 22 the **ESP acknowledged the phone's M1 -and the phone retransmitted it anyway**. A station is necessarily receiving -during the SIFS immediately after its own transmission — that is when an ACK -must arrive — so this cannot be the phone "not listening at that instant". -The phone did not receive, or did not decode, the ESP's acknowledgement. - -The converse also happens: in run 18's first window the phone sent M1 seven -times and the ESP acknowledged none, then acknowledged four copies in the -next window. - -So **both ends intermittently fail to receive in-window frames from the -other**, and on the phone's side it is demonstrably not a wake-state effect. -That is a materially different model from "the ESP transmits too late and the -peer has stopped listening", and it may underlie the unacknowledged M2s and -follow-ups seen throughout. It is not characterised and nothing should be -filed about it yet. - +### The ESP misses M1; the phone missing ACKs is not established + +This section previously claimed that the phone fails to receive the ESP's +acknowledgements. Decoding the zero-drop captures directly, matching each ACK +to the frame it immediately follows, that claim does not hold up and is +withdrawn. Half of it does hold. + +**The ESP does miss M1, repeatedly.** In run 18's first window the phone sent +M1 seven times and the ESP acknowledged **none** of them; it acknowledged the +third and fourth copies in the next window. Run 20's first M1 went +unacknowledged and the second was taken; run 22's first three went +unacknowledged and the fourth was taken. The ESP's receive side genuinely +drops in-window frames, and that is not characterised. + +**The phone retransmitting after an acknowledgement is a single instance.** +It happens once, in run 18's second window, where M1 #10 was acknowledged and +the phone still sent #11 about 180 µs later. In runs 20 and 22 the phone +stopped transmitting immediately on receiving an acknowledgement, which is +correct behaviour. One extra frame at 180 µs is far better explained as a +retry already queued in hardware and no longer cancellable than as a +reception failure, so the "the phone cannot decode the ESP's frames" model +built on it is not supported. + +A methodological note, because it produced the error. An ACK must be the +frame *immediately* following the one it acknowledges. Matching "any ACK to +this transmitter within 1 ms" credits a single ACK to two frames of a burst, +and in run 21 that made the first M2 attempt appear acknowledged when the +frame actually following it, 617 µs later, was its own retry. ### Run 19: M2 constructed and never transmitted The only failure in the clean block failed differently. With **zero capture From dc60907ae9bcdd199c156d61da6606b4698112df Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:47:16 +0000 Subject: [PATCH 22/30] docs: restructure issue 2 so it can actually be filed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The draft had grown to 644 lines and twenty-odd sections, most of it a chronological record of theories raised and withdrawn. It was complete but unreadable, and no upstream maintainer would get through it. Reorganised around the three asks, each with the evidence that supports it and nothing else: the first M2 transmission never being acknowledged, with the zero-drop run table; the error-level log that fires on successful runs; and the ACCEPTED status reported after the parse returned 262. The seven discarded explanations are compressed into an appendix, kept rather than deleted because each was dropped on evidence that constrains what remains — Potential-only availability, the 5 GHz exclusion, the negotiation having succeeded, the Discovery Window deadline, slot-anchored scheduling, burst length as an oracle, and the phone missing ACKs. Three observations are now explicitly separated as not part of any ask, because they rest on too little: the ESP missing M1 up to seven times in a row, run 19 building an M2 it never transmitted, and off-AP discovery failing with an unsolicited publish while a solicited one works. The method note is promoted to the top, since the ACK matching rule is what the whole evidence base depends on. No evidence removed; nothing changed but structure and the removal of superseded narrative. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 755 ++++++---------------------- 1 file changed, 144 insertions(+), 611 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 1dbf3990054..a1e2b00d21e 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -1,644 +1,177 @@ -# NAN: NDP Response straddles the Discovery Window end, and a spurious availability error - -**Status: draft, two asks ready, one question still open.** The data path -*does* work — run 7 established an IPv6 data path between an Android phone and -an ESP32 — so this is no longer "NAN is broken with Android". It is two -specific defects plus an unexplained off-AP discovery failure. - -- **Ask 1 (timing) is ready, as a reliability claim rather than a boundary.** - The ESP's first NDP Response attempt has never been acknowledged in any of - 16 runs, and it starts anywhere from 0.92 to 2.12 slots after the request. - Setup therefore depends on a retry being taken, and succeeded **9 times in - 16** — 5 of 6 in the zero-drop block. Acknowledged and unacknowledged - attempts overlap throughout the range, so there is no threshold. -- **Ask 2 (spurious error) is ready, and is now demonstrably cosmetic.** - `Avail: missing a conditional or committed entry` is logged on runs where - the NDP **succeeds**, so it never was a negotiation failure. -- **Off-AP discovery** never completes and is **not explained**. Nothing - about it should be filed. -- **A ~20 s data-path teardown** appeared in runs 7 and 8, on *idle* links - only; run 9 with keepalive traffic stayed up for 100 s. It has its own - write-up: the ESP never answers the peer's NAF Schedule Request. See - `IDF-ISSUE-3-nan-schedule-request.md`. -- **Off-AP discovery works with a *solicited* (unicast) publish** — run 8 - discovered in 1.25 s. The runs 5/6 failure was specific to the - **unsolicited, group-addressed** publish, which supports the - unicast-versus-group-addressed split recorded below. - -Four earlier explanations were proposed and discarded; that history is kept in -[What is NOT established](#what-is-not-established) because each was dropped -on evidence that constrains what remains. +# NAN: NDP Response is never acknowledged on its first attempt, and a spurious availability error + +**Status: draft, not filed.** Asks 1–3 are evidenced and ready. Two further +observations are recorded but deliberately not asked about, because they rest +on too little. ## Summary -An ESP32 running NAN-Sync as a publisher discovers an Android phone, exchanges -follow-up messages, and responds to its NDP Request with an **ACCEPTED** NDP -Response. That response is never acknowledged, across ten transmit attempts in -two Discovery Windows, and the phone times out after 20 s. +An ESP32 running NAN-Sync establishes a Wi-Fi Aware data path with an Android +phone in **9 of 16 runs**. The failures share a mechanism: the ESP's first +NDP Response transmission is *never* acknowledged, in any run, and setup +depends on one of its retries being taken. -The ESP also logs `Avail: missing a conditional or committed entry` while -parsing a request that demonstrably contains a conditional entry. +Two smaller defects accompany it: an error-level log that fires on successful +runs, and an M2 that reports ACCEPTED after the parse that built it returned +an error. ## Environment | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Target | ESP32 (classic, rev0), `examples/wifi/wifi_aware/nan_publisher` | -| Config | `CONFIG_ESP_WIFI_NAN_SYNC_ENABLE=y`, NAN security off (open NDP) | +| Target | ESP32 (classic, rev0), `wifi_aware/nan_publisher`, SOLICITED | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | -| Capture | ESP32-S2 in monitor mode on channel 6 | - -ESP-to-ESP NAN-Sync on the same build works end to end: cluster 3.35 s, match -4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT, no loss. - -**Confound, see below: during every run the phone was also associated as a STA -to an AP on channel 64 (5320 MHz).** - -## Measured facts - -### The phone's NDP Request is well formed - -NAF subtype 5, `fa:b7:34:46:4c:36` → ESP NMI `26:0a:c4:5f:d3:ca`, t = 13.342 s, -−36 dBm. DevCap; `NDP{dialog=5, type/status=0x00}`; two Availability -attributes: +| Capture | ESP32-S2 monitor on channel 6 with ACK frames recorded | -- **`attr_ctrl=0x0010`, map ID 0** — one entry, **CONDITIONAL**, pref 3, time - bitmap 16 TU slots / 512 TU period / start 0 / `ffffffff` (all 32 slots), - channel entry op class 81, **channel 6**. -- **`attr_ctrl=0x0011`, map ID 1** — two **POTENTIAL** entries: op class 128 - (5 GHz, 80 MHz, chan bitmap `0x0020`, prim `0x01`), slots `000f0000`; and a - band entry "5 GHz", slots `00f000ff`. +ESP-to-ESP NAN-Sync on the same build works end to end — cluster 3.35 s, +match 4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT. Only the Android +data path is unreliable. -Then NDC (15), NDL (4), NDL-QoS (3), attr `0x1d` (81). +### Method -The request is neither Potential-only nor 5 GHz-only. Two earlier theories -about it are dead. +Delivery is read from **ACK-by-RA**, with each ACK matched to the frame it +*immediately* follows. A wider match window credits one ACK to two frames of +a retry burst and produces false positives. -### The ESP responded ACCEPTED, and was not acknowledged +Runs 17–22 used a sniffer with a PSRAM queue and ACKs filtered to known NAN +NMIs, and recorded **zero drops**. Runs 3–6 predate ACK capture and are also +drop-free. Runs 7–16 overflowed a 24-entry queue (up to 1761 drops), so for +those, burst sizes are lower bounds and a missing frame proves nothing. -M2 carries status `0x11` (ACCEPTED), a committed channel-6 bitmap `feffffff`, -and NDC + NDL attributes. Transmit attempts, measured from the start of the -Discovery Window (DW = 16 TU = 16.384 ms, recurring every 524 ms): - -| ESP frame | offset into DW | acknowledged? | -|---|---|---| -| SDF | +14 ms | n/a — group-addressed, never acked | -| Follow-up "Welcome" (run 3) | +9 ms | yes | -| M2, 5 tries, 13.358–13.362 | +16 to +20 ms | no | -| M2 retry, 5 tries, 13.883–13.886 | +16 to +19 ms | no | - -Phone sent NDP-Termination at 33.266 s, the 20 s timeout. - -### The spurious parse error - -``` -E (12422) wifi:Avail: missing a conditional or committed entry -``` - -Disassembly of `nan_dp_parse_availability` (`ieee80211_nan_datapath.o`, -esp32): - -``` -19e: l32i a8, a4, 0x140 -1a1: bnez.n a8, 1e1 ; usable entry found -> continue -1a5: movi a2, 0x106 ; return 262 -1a8: l32r a13, c ; "missing a conditional or committed entry" -1b1: callx8 a8 ; log -1b4: j 41f ; -> two instructions before retw.n at 422 -``` - -The success path sets `a2 = 0` at `0x417`. `nan_parse_ndp_req` calls this -parser from inside an attribute walk (backward branch `0x442 → 0x135`, two -references to the parser), which is consistent with the error coming from a -second call on map 1 — where Potential-only entries are exactly what is -expected — rather than from map 0. - -Per-map storage and lookup exist in the blob: `nan_get_avail_by_map_id` walks -92-byte records keyed on map ID. It is called from -`nan_sched_alloc_conditional`, `nan_sched_allocate_crbs` and -`nan_dp_indicate_faw_start`, but **not** from the parser. - -## What is NOT established - -Three things, each of which a previous draft of this document got wrong. - -**1. That the ESP honoured the phone's conditional entry.** An earlier draft -argued the committed ch6 bitmap in M2 proved the ESP had parsed and used -map 0. It proves nothing of the kind. In NAN-Sync the ESP is a single-channel -device that always advertises its own committed ch6 schedule: its SDFs in the -same capture carry a committed ch6 bitmap (`fcffffff`) before any NDP exists, -and it logs its own NDC as `NDP Resp NDCA: ndc=0x2 committed=0xfffffffe`. -M2's committed entry can come wholly from the ESP's own state. The ESP may -have accepted without honouring the phone's entry at all. Both readings stay -open. - -*(One small open detail: the SDF bitmap is `fcffffff` and M2's is `feffffff`. -If M2's committed schedule were a straight copy of the ESP's own state, one -might expect them identical. That difference may be ordinary DW-slot -bookkeeping and is not offered as evidence either way, but a future capture -could check whether M2's bitmap ever varies with the peer's offer.)* - -**2. That the Discovery Window boundary is the mechanism.** The out-of-window -side is solid — ten unacknowledged M2s across two DWs. The in-window side is -**n = 1**. SDFs are addressed to the group address `51:6f:9a:01:00:00` and are -never acknowledged, so they carry no delivery information. The only in-window -unicast is the run-3 follow-up at +9 ms. One success against ten failures is -suggestive, not proof. Run 2 additionally logged `Failed to send Follow-up -message!` twice with no sniffer timing; if those attempts were in-window, the -boundary story weakens further. - -**3. That any ESP scheduling defect is involved at all.** Throughout every run -the phone was associated as a STA to an AP on **channel 64 (5320 MHz)** — its -map-1 Potential 5 GHz entries, op class 128, are consistent with exactly that. -Android time-shares the radio back to its AP channel between Discovery -Windows, and a *conditional* availability entry does not oblige the peer to -remain on channel 6 until the NDL is confirmed. So outside the DW the phone -may simply not have been listening on channel 6, which would account for every -unacknowledged M2 with no ESP defect whatsoever. - -## The off-AP rerun: the timing theory does not survive either - -Phone Wi-Fi on, not associated, verified over adb. - -**Run 4, roles reversed** (phone publishes, ESP subscribes and initiates). -The ESP discovered the phone in **0.24 s**. Its unicast follow-up went out 22 -times at +13 to +22 ms and was never acknowledged. The ESP proceeded to the -NDP regardless (`Peer datapath_reqd not set, proceeding anyway`), sent M1 -dialog 1 ×5 then dialog 2, and the phone answered **NDP Response status -`0x21` = REJECTED, reason 2 (resource limitation)**. The ESP's M1 carried -Availability map 0 with a conditional ch6 entry (`fcff0100`) plus a potential -entry on ch 1–11. - -**Run 5, original direction** (ESP publishes, phone subscribes). No discovery -across roughly 60 Discovery Windows. In every one of them the ESP's publish -SDF landed **+2 to +14 ms** after the phone's SDF — inside the 16 TU window, -and often *earlier* than a third-party NAN device at +1 to +14 ms that was -transmitting in the same windows. The phone still never matched. - -### What this does to the timing theory - -Run 5 is decisive against the *simple* version of it: the ESP transmitted -inside the 16.384 ms Discovery Window, repeatedly, and was still not heard. -"The ESP transmits too late relative to the end of the DW" cannot carry runs -5 and 6. - -It survives in a narrower form for runs 3 and 4, against a shorter effective -deadline — see [Transmit offsets, all runs](#transmit-offsets-all-runs) — and -ask 1 is written to that narrower claim only. - -### But "the phone hears nothing from the ESP" is too strong - -In run 4 the phone **answered the ESP's M1** with a properly formed NDP -Response carrying a specific reason code. It cannot have done that without -receiving M1. So the phone's receive path for ESP frames is not globally -broken, and any explanation resting on PHY rate or frame format has to -account for M1 getting through while 22 follow-ups did not. - -The reason-2 rejection itself is explained and is not an ESP fault: the test -app only called `requestNetwork()` from `onMessageReceived`, so with no -follow-up delivered Android had no pending responder request to match M1 -against. The app now arms an any-peer responder at publish time -(`WifiAwareNetworkSpecifier.Builder(publishSession)`), which removes that -dependency, and run 4 should be repeated with it. - -### Transmit offsets, measured from the captures - -Re-derived directly from the pcaps rather than from frame counts, because -counting frames overstates the evidence: retries within a burst are not -independent trials. - -**Method note.** There are **no ACK frames at all in any of the four pcaps**. -That is a property of the capture, not of the medium: the sniffer runs with -`WIFI_PROMIS_FILTER_MASK_MGMT` and keeps only NAN management frames, so -control frames are never recorded. No conclusion here may rest on "the sniffer -saw no ACK". - -Delivery is instead read from two independent signals that agree: the 802.11 -**retry bit** — a burst that stops before the retry limit was acknowledged, -one that runs to the limit was not — and the ESP's own TX-status logging. A -future capture can add `WIFI_PROMIS_CTRL_FILTER_MASK_ACK` to record ACKs by -RA directly, which would turn this inference into a measurement. - -Every unicast transmission *event* from the ESP across runs 3 and 4, with the -offset measured from the preceding group-addressed SDF from the phone: - -| run | AP | first tx | last tx | frames | outcome | -|---|---|---|---|---|---| -| 3 | on | **+9.22 ms** | **+10.22 ms** | 3 | **delivered** on the 3rd | -| 3 | on | +15.93 ms | +19.88 ms | 5 | failed | -| 3 | on | +15.93 ms | +19.61 ms | 5 | failed | -| 4 | off | +13.12 ms | +22.08 ms | 21 | failed | -| 4 | off | +17.37 ms | +20.36 ms | 5 | failed | -| 4 | off | **+4.16 ms** | — | **1** | **acked first attempt** | - -Six events: two delivered, four failed. Corroboration for both successes is -independent of the capture — the phone logged -`onMessageReceived … utf8="Welcome"` for the run-3 event, and the ESP logged -`M1 TX success: ndp_id=1` for the run-4 one, which is also the only event that -needed no retry at all. - -Two features of this table matter more than the raw counts. - -**The effect is graded.** +4.16 ms was acknowledged on the first attempt. -+9.22 ms needed three attempts and only got through at +10.22 ms. Everything -first transmitted at +13.12 ms or later failed outright, including one event -that tried 21 times. That is the shape of a receiver that stops listening part -way through the window, not of random loss. - -**The boundary is in the same place with and without the AP.** On-AP: success -at +9–10 ms, failures at +15.93 ms twice. Off-AP: success at +4.16 ms, -failures at +13.12 and +17.37 ms. If AP time-sharing on 5 GHz accounted for -the run-3 failures, the boundary would not be expected to land in the same -place off-AP. A single mechanism spanning both conditions fits better than two -different ones. - -It remains a small sample — two successes — and the retry limit is inferred -from bursts stopping at 5. A deliberate sweep of follow-up delivery against DW -offset would settle it properly. - -### What the offsets do NOT explain - -Run 4 was **off-AP**, and the phone answered a unicast at +4 ms. So off-AP the -phone is demonstrably awake and receiving early in the window. - -That rules out the simplest reading of runs 5 and 6. In those the ESP's -publish SDF landed at +2 to +14 ms after the phone's SDF, across roughly 60 -Discovery Windows. Many of those were inside the +4 to +9 band that -demonstrably works. The phone still never matched, and its HAL shows -subscribe OK (`subscribeId=1`) with **no match event from firmware at all**. - -So early termination cannot account for runs 5 and 6, and neither can the -frames: the ESP's publish SDF carries SDA service id `6f08e42b8c44` = -`SHA-256("esp-nan-test")[:6]`, exactly matching the phone's own subscribe SDF, -with publish type `0x00`, in cluster `50:6f:9a:01:db:dd` — the same cluster -all three devices are in — at 6 Mbps non-HT, the most robust rate available. - -### The remaining asymmetry: unicast works, group-addressed does not - -Putting runs 4, 5 and 6 together, off-AP: - -- A **unicast** frame to the phone's NMI at +4 ms is received and answered. -- A **group-addressed** publish SDF produces no firmware match, with the - correct service ID and cluster, **88 times out of 123 at or before +10 ms** - in run 5 alone (23 of 37 in run 6b). - -On-AP, in runs 2–3, the same group-addressed publish SDF *was* matched, in -1–23 s. - -The open question this raises is whether the phone processes group-addressed -SDFs differently when it has no AP association — a receive-filter or -power-save difference rather than anything about the ESP's transmissions. - -**A caution on that hypothesis.** It has the same shape as the one proposed -for the USD defect in issue 1, where group-addressed NAN frames also appear to -go missing. That symmetry is suggestive but it is also exactly the kind of -pattern-match that has produced four discarded theories in this -investigation. It is written down as a question, not a finding. - -### Is the map-0/map-1 structure an artefact of the AP? - -Ask 2 rests on the two-map structure of an NDP Request that was only ever -captured while the phone was associated to an AP. Decoding the phone's -Availability attributes straight out of the captures answers most of that -worry. - -The phone's **map-0 entry in its SDFs is byte-identical on-AP and off-AP**: - -``` -0e00 1a12 1800 04 03000000 11 51 2000 00 potential, op class 81, ch 6 -0b00 1a12 1800 04 fcffffff 10 02 potential, band 2.4 GHz -``` +--- -The map-1 entries are present in both conditions too, and the op class is the -decisive detail: **op class 128, channel bitmap `0x0020`**. For class 128 the -channel set is 42, 58, 106, 122, 138, 155, so bit 5 is the 80 MHz block -centred on 155 — channels 149–161, containing **149, the NAN 5 GHz discovery -channel**. The phone's AP was on channel 64, which sits in the block centred -on 58 and would be bit 1. So map 1 is the phone's own NAN 5 GHz availability -and has nothing to do with its AP association. An earlier reading of these -entries as "matching the AP channel" was wrong. +## Ask 1 — answer the NDP Request on the first attempt -The two-map structure is therefore a property of the phone's NAN -configuration, not of the AP, and **ask 2 does not rest on an AP artefact**. +**The first M2 transmission is never acknowledged.** Across the five +zero-drop runs that put an M2 on the air, the opening frame of the first +burst has no ACK immediately following it, every time. -Two caveats, one of which matters. - -The AP does change the *content*: the 5 GHz potential time bitmap is -`00f000ff` on-AP and `fff0ffff` off-AP, which is what one would expect from a -radio that has to serve an association. - -The caveat that matters: all of the above is from **SDFs**, and the SDF map-0 -entry is **Potential** with slots `03000000`, whereas the on-AP **NDP -Request** map-0 was **Conditional** with `ffffffff`. The phone upgrades its -offer when it actually asks for a data path. So SDFs are weak evidence for -what an off-AP NDP Request would contain, and no off-AP NDP Request has ever -been captured — off-AP discovery has never completed, so the exchange never -gets that far. - -**The availability parse failure has been observed twice, in runs 2 and 3, -both on-AP, both with the ESP as NDP responder. There are zero off-AP -observations.** Reproducing it needs either the AP back, or discovery working -off-AP so the phone initiates an NDP there. - -### The test that would settle it +| run | first-window M2 | second-window M2 | outcome | +|---|---|---|---| +| 17 | 5 fr @ 1.58–1.68, none acked | 2 fr @ 0.42–0.46, 1st acked | OK | +| 18 | 2 fr @ 0.96–1.04, none acked | 3 fr @ 0.75–0.83, 3rd acked | OK | +| 19 | **no M2 on air at all** | — | FAIL | +| 20 | 5 fr @ 0.96–1.21, none acked | 1 fr @ 0.24, acked | OK | +| 21 | 2 fr @ 0.95–0.98, **2nd acked** | — | OK | +| 22 | 5 fr @ 2.05–2.15, none acked | 5 fr @ 0.22–0.33, 5th acked | OK | -The phone subscribes **ACTIVE**, so it transmits subscribe SDFs that the ESP -can see. A NAN publisher is expected to answer a matching active subscribe -with a **solicited publish, unicast to the subscriber's NMI**. +Offsets are in slots (1 slot = 16 TU = 16.384 ms) from the preceding +group-addressed frame from the phone, which sits within 1.31 ms of a +Discovery Window start beacon — median 0.00 ms, sigma 0.40 ms over 593 +windows, so it is a sound anchor. -Two things to check in the run 5/6 captures: +The first-window M2 starts anywhere from **0.92 to 2.12 slots** after the +request, frequently past slot 1 entirely, which is where the peer is not +reliably receiving. -1. **Does the ESP ever send a unicast solicited publish to the phone's NMI?** - If it does not, discovery depends entirely on the phone catching a - group-addressed broadcast, and the ESP's failure to answer an active - subscribe is itself a defect worth reporting separately. -2. **If it does, at what DW offset, and is it matched?** A unicast solicited - publish landing at +4 ms and still producing no match would clear the - unicast/broadcast hypothesis and point back at the phone's firmware. +**It is not a position threshold.** Acknowledged and unacknowledged attempts +overlap throughout the range: run 11's second burst at 0.740 failed where +run 9's at 0.724 succeeded; run 13's at 0.548 failed where run 8's at 0.581 +succeeded. -### Still outstanding +**It is not impossible to get right.** Run 21's retry at 0.984 slots was +acknowledged and the data path came up without a second window ever being +needed. The ESP *can* close the exchange inside the window the request +arrived in. -The on-AP/off-AP inversion is unexplained and reproduces (runs 5 and 6). Until -it is understood, no claim about the ESP's behaviour in either direction is -safe. The alternating on/off-AP pair is the next experiment and requires the -phone to be rejoined to its AP. +**The ask:** transmit the NDP Response early enough in the Discovery Window +that the first attempt has a chance, and leave room for retries within that +window. At present the first attempt never lands and setup is 9 in 16. -### Run 7: the data path works +## Ask 2 — do not log an error for a map carrying only Potential entries -Phone back on-AP, screen awake, ESP running a SOLICITED publisher. Captured -with ACK frames recorded, so delivery is direct evidence rather than inferred -from the retry bit. +The ESP logs ``` -4.779 DW+1 ESP solicited publish (unicast) -> phone ACKED -5.303 DW+0 phone follow-up "Hello" -> ESP ACKED -5.306 DW+3 ESP publish + "Welcome" -> phone ACKED -5.311 DW+8 -5.826 DW+0 phone NDP Request -> ESP ACKED -5.842 DW+16..17 ESP M2 burst x5 NOT acked -6.365 DW+15 ESP M2 retry burst x3 ACKED -> confirm -6.382 phone broadcast NAF Schedule Update +E (12422) wifi:Avail: missing a conditional or committed entry ``` -The app reported `TCP connect to [fe80::240a:c4ff:fecb:7ddb%aware_data0]:7 -REFUSED => PASS` and `isReachable=true`; the ESP logged `NDP confirmed … -Peer IPv6 FE80::281B:56FF:FE14:B87C`, NDL ch6, `ndc=[1,1]`, `crb1=[2,31]`. - -**This settles ask 2.** `Avail: missing a conditional or committed entry` was -logged in this run too, and the NDP confirmed anyway. The error never -prevented anything. It is a misleading log line, and the earlier worry that it -might also corrupt the ESP's schedule state is answered: it does not prevent -setup. - -**It also sharpens ask 1, though the mechanism is still open.** An earlier -revision of this document argued that because run 3's two M2 bursts started -at the identical offset (+15.927 ms, 0.9721 slots, one DW period apart to -within 0.0001 of a period), the transmission must be anchored to the slot grid -rather than to processing latency. **That argument is withdrawn.** Run 3's -coincidence does not generalise: the successful retries in later runs started -at 0.85–0.90 slots (run 7) and 0.569 slots (run 8), nowhere near the first -attempt's position. - -What *is* consistent is the **first** attempt, across every run: - -| run | first M2 after M1 | -|---|---| -| 3 | 0.98 slots | -| 7 | 0.93 slots | -| 8 | 1.03 slots | - -Because the phone always sends its NDP Request at DW+0, "about one slot after -M1" and "the slot-0/slot-1 boundary" are the same instant, so first attempts -alone **cannot** separate ~16 ms of processing latency from deliberate -slot-grid scheduling. Off-by-one remains a hypothesis. - -The defensible statement is the one that does not depend on the mechanism: the -first NDP Response consistently goes out about 16 ms after the request, which -is at or past the end of the Discovery Window, and setup only succeeds when a -retry happens to land earlier in a later window. That is a coin flip, and it -is what ask 1 asks to fix. - -**The control did not happen.** IDF refused the second publish — -`Service name esp-nan-test already used!`, publish #2 id=0 — so this was -solicited-only and there is no within-run unsolicited comparison. Two -instances need different service names. The off-AP discovery question is -therefore untouched by run 7, which was on-AP and discovered via a *unicast* -solicited publish ACKed at DW+1. - -### Why there is no boundary, and a check on the measurements - -Runs 10, 11 and 12 all failed to establish a data path, with retries at -0.81–0.91, 0.76 and 0.575 slots — positions where earlier runs had succeeded. -Run 12's 0.575 is the sharpest: run 8 succeeded at 0.569. Collected across -every run with the solicited publisher: **runs 7, 8 and 9 succeeded, runs 10 -and 11 failed.** Acknowledged retries at 0.57 and 0.85–0.90 sit *inside* the -range of unacknowledged ones at 0.76 to 0.91. The ranges overlap, so the -earlier "late equals lost" boundary is not supportable. - -Before concluding that, the anchor itself was checked, because every offset in -this document is measured from the phone's SDF rather than from a true -timebase. In run 3 the phone's SDF falls within **1.31 ms** of a beacon at -Discovery Window start, median 0.00 ms and standard deviation 0.40 ms across -593 windows. The proxy anchor is sound and the measurements are not drifting; -the erratic outcomes are real. - -### Capture reliability - -From run 7 the monitor also recorded ACK frames, which overflowed its -24-entry queue with neighbouring-BSS traffic. Drops per run: run 3 **0**, -run 7 55, run 8 84, run 9 1761, run 10 141, run 11 8, run 12 1203. **Runs 3 -to 6 are reliable**, predating ACK capture; runs 7 to 16 are not — a missing -frame or ACK there is not evidence it never happened, and burst sizes are -lower bounds. - -Runs 17 to 22 used a rebuilt sniffer, PSRAM queue with ACKs filtered to known -NAN NMIs, and recorded **zero drops in every run**. Those are the runs to -trust. - -### Every M2 burst, runs 8 to 16 - -Decoded from the pcaps rather than from summaries, filtering on NAF OUI type -`0x18` subtype `0x06`. Offsets in slots from the preceding group-addressed -frame from the phone. These runs all have capture loss, so burst sizes are -lower bounds. - -| run | first M2 | second M2 | outcome | -|---|---|---|---| -| 8 | 5 fr @ 1.027 | 1 fr @ 0.581 | OK | -| 9 | 5 fr @ 1.028 | 1 fr @ 0.724 | OK | -| 10 | 5 fr @ 0.924 | 5 fr @ 0.803 | FAIL | -| 11 | 5 fr @ 1.001 | 5 fr @ 0.740 | FAIL | -| 12 | 1 fr @ 0.554 *(w0 dropped)* | — | FAIL | -| 13 | 3 fr @ 1.208 *(truncated)* | 5 fr @ 0.548 | FAIL | -| 14 | 1 fr @ 0.899 *(truncated)* | — | FAIL | -| 15 | 5 fr @ 0.925 | 2 fr @ 0.816 | FAIL | -| 16 | 5 fr @ 1.165 | 1 fr @ 0.395 | OK | - -Position does not predict outcome: run 11's second burst at 0.740 failed -where run 9's at 0.724 succeeded, and run 13's at 0.548 failed where run 8's -at 0.581 succeeded. Adjacent offsets, opposite outcomes. - -Also visible here: the phone retransmits its own M1 when the ESP does not -acknowledge it — 8 frames in run 10 and 3 in run 9 against 1 elsewhere. - -### The burst-length oracle is withdrawn - -An earlier revision argued that a burst running to five meant the retry limit -was exhausted and the frame went unacknowledged, while a burst stopping short -had been acknowledged on its last frame. The zero-drop runs refute both -halves: - -- **Run 22, second window:** five frames, and the **fifth was acknowledged**. - A five-frame burst can succeed. -- **Run 18, first window:** two frames, **no acknowledgement**, no success, - with zero drops in that capture. A burst can stop short without being - acknowledged. - -Burst length is not an outcome oracle. It was a reasonable inference when -capture loss made it the only signal immune to the drops, and it is wrong. -Why the ESP sometimes stops at two and sometimes runs to five is unknown. -**ACK-by-RA from the rebuilt sniffer is the oracle**, corroborated by the ESP -and phone logs. - -### The clean runs, 17 to 22 - -Zero drops in every run; five of six established a data path. - -| run | first-window M2 | second-window M2 | outcome | -|---|---|---|---| -| 17 | 5 fr @ 1.58–1.68, none acked | 2 fr @ 0.42–0.46, **1st acked** | OK | -| 18 | 2 fr @ 0.96–1.04, none acked | 3 fr @ 0.75–0.83, **3rd acked** | OK | -| 19 | **no M2 on air at all** | — | FAIL | -| 20 | 5 fr @ 0.96–1.21, none acked | 1 fr @ 0.24, **acked** | OK | -| 21 | 2 fr @ 0.95–0.98, **2nd acked** | — | OK | -| 22 | 5 fr @ 2.05–2.15, none acked | 5 fr @ 0.22–0.33, **5th acked** | OK | - -Offsets and acknowledgements re-derived from the pcaps, with each ACK matched -to the frame it immediately follows. - -**Run 21 refutes "the first window never succeeds".** Its retry at 0.972 -slots, about 0.45 ms before the end of slot 0, was acknowledged and the data -path came up without a second window ever being needed. The ESP *can* close -the exchange inside the window the request arrived in. - -The first *transmission attempt* has still never been acknowledged in any -run. That is now **direct** evidence rather than inference: in all five clean -runs that put an M2 on the air, the opening frame of the first burst has no -ACK immediately following it. In run 21 the frame at 0.946 slots is followed -617 µs later by its own retry, and it is that retry, at 0.984, which the -phone acknowledges. This is the narrow claim ask 1 rests on. - -**The first-window offset is not fixed near one slot.** Across all runs it -spans **0.92 to 2.12 slots** — runs 17 at 1.59 and 22 at 2.02 land past slot -1 entirely. An earlier figure of 0.93–1.22 came from too few runs. - -### The ESP misses M1; the phone missing ACKs is not established - -This section previously claimed that the phone fails to receive the ESP's -acknowledgements. Decoding the zero-drop captures directly, matching each ACK -to the frame it immediately follows, that claim does not hold up and is -withdrawn. Half of it does hold. - -**The ESP does miss M1, repeatedly.** In run 18's first window the phone sent -M1 seven times and the ESP acknowledged **none** of them; it acknowledged the -third and fourth copies in the next window. Run 20's first M1 went -unacknowledged and the second was taken; run 22's first three went -unacknowledged and the fourth was taken. The ESP's receive side genuinely -drops in-window frames, and that is not characterised. - -**The phone retransmitting after an acknowledgement is a single instance.** -It happens once, in run 18's second window, where M1 #10 was acknowledged and -the phone still sent #11 about 180 µs later. In runs 20 and 22 the phone -stopped transmitting immediately on receiving an acknowledgement, which is -correct behaviour. One extra frame at 180 µs is far better explained as a -retry already queued in hardware and no longer cancellable than as a -reception failure, so the "the phone cannot decode the ESP's frames" model -built on it is not supported. - -A methodological note, because it produced the error. An ACK must be the -frame *immediately* following the one it acknowledges. Matching "any ACK to -this transmitter within 1 ms" credits a single ACK to two frames of a burst, -and in run 21 that made the first M2 attempt appear acknowledged when the -frame actually following it, 617 µs later, was its own retry. -### Run 19: M2 constructed and never transmitted - -The only failure in the clean block failed differently. With **zero capture -drops** there is **no M2 on the air at all**, while the ESP's own log says it -built M2 twice, reported `TX Confirm failed`, and rejected the request. In -its place the ESP transmitted **unicast Service Discovery Frames** to the -phone: 14 frames at roughly M1 + 529–548 ms, all retries after the first, -none acknowledged, then 3 more at about +1050 ms. - -A response constructed and then never transmitted is a different defect from -one transmitted too late, and substituting SDF retries for it is stranger -still. Single observation; it needs repeats. It is only visible because the -capture had no losses. - -### The 20 s teardown - -About 20 s after confirmation the link dropped. The phone reported -`eventDataPathTerminated` for ndp 4 and the app logged `onLost` at 26.4 s; the -ESP logged nothing. - -Two candidates, and they are cheaply separable: - -1. **Idle teardown.** The app connected once and then sent nothing. If an - unused NAN data path is reclaimed, this is not a defect at all. -2. **An unsatisfiable NDL.** The ESP committed `crb1=[2,31]` — effectively - every slot on channel 6 — which a phone concurrently associated to an AP - on channel 64 cannot honour. If so this links back to the availability - handling: the ESP takes the peer's *conditional* offer as licence to commit - to everything, survives setup, and loses the link later. - -The test app now sends a keepalive probe every 2 s once the data path is up -and reports how long the link survived, which distinguishes the two in one -run. - -## Asks - -1. **Answer an NDP Request on the first attempt, early enough in the - Discovery Window to leave room for retries.** - - The first transmission attempt has **never** been acknowledged in any of - the sixteen runs measured. The ESP's first-window M2 starts anywhere from - 0.92 to 2.12 slots after the request, sometimes past slot 1 entirely, so - it routinely arrives where the peer is not reliably receiving. Setup then - depends on a retry being taken, and across sixteen runs it succeeded - **9 times** — 5 of 6 in the clean zero-drop block, 4 of 10 before it. - - Run 21 shows the exchange *can* complete inside the request's own window: - a retry at 0.972 slots was acknowledged and the data path came up without - a second window. So this is a latency and margin problem, not an - impossibility. - - **There is no position threshold.** Acknowledged and unacknowledged - attempts overlap throughout the range, in both directions, across all - sixteen runs. - -2. **Do not log "missing a conditional or committed entry" for a map that - legitimately carries only Potential entries.** Run 7 confirms this error is - **cosmetic** — it is logged on runs where the NDP goes on to confirm - successfully. It is an error-level message for a non-error, and it cost two - independent investigations several days. Per-map storage and lookup already - exist — `nan_get_avail_by_map_id` walks 92-byte records keyed on map ID — - but it is called from `nan_sched_alloc_conditional`, - `nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the - parser. The message sent two independent investigations down the wrong path - for a day. - -3. **Do not report ACCEPTED after a parse error**, or do not return an error - for a condition that does not prevent acceptance. At present the log and - the transmitted frame disagree. Also independent of the root cause. - -## Why this matters - -Phone interoperability is the main reason to use Wi-Fi Aware on these parts, -and essentially every phone will be STA-associated while doing it. Today -NAN-Sync works ESP-to-ESP and does not establish a data path with Android. +on runs where the NDP **confirms successfully**, so it never indicated a +negotiation failure. It is an error-level message for a non-error. + +The peer's NDP Request carries two Availability attributes: map 0 with a +**conditional** channel-6 entry covering all 32 slots, and map 1 with +**potential** 5 GHz entries (op class 128, bitmap `0x0020` — the block +centred on 155, containing the NAN 5 GHz discovery channel 149). +Potential-only is exactly what a map-1 entry is for. + +`nan_parse_ndp_req` calls `nan_dp_parse_availability` from an attribute walk +(backward branch `0x442 -> 0x135`), consistent with the error coming from the +map-1 pass. Per-map storage exists — `nan_get_avail_by_map_id` walks 92-byte +records keyed on map ID — but it is called from `nan_sched_alloc_conditional`, +`nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the +parser. + +This cost two independent investigations several days. + +## Ask 3 — do not report ACCEPTED after the parse returned an error + +`nan_dp_parse_availability` logs and returns 262 at `0x1a8`, jumping to +`0x41f`, two instructions before `retw.n` at `0x422`; the success path returns +0 at `0x417`. The M2 the ESP then transmits carries status `0x11`, ACCEPTED. +The log and the frame disagree. + +--- + +## Further observations, not asked about + +**The ESP misses M1 repeatedly.** In run 18's first window the phone sent M1 +seven times and the ESP acknowledged none; it took the third copy in the next +window. Run 20's first M1 went unacknowledged, run 22's first three did. This +is an ESP receive-side problem and it is uncharacterised. + +**Run 19: M2 constructed and never transmitted.** With zero capture drops +there is no M2 on the air at all, although the ESP acknowledged the phone's +M1 — so it received the request — and its log records building M2 twice, +then `TX Confirm failed`, then rejecting. In its place it sent 14 unicast +Service Discovery Frames to the phone at roughly M1 + 529-548 ms, none +acknowledged, and 3 more at about +1050 ms. One observation; needs repeats. + +**Off-AP discovery fails with an unsolicited publish.** Runs 5 and 6 saw 88 +of 123 group-addressed publish SDFs land at or before +10 ms with the correct +service ID and cluster, and the phone's firmware reported no match at all. A +*solicited* (unicast) publish discovered in 1.25-1.6 s in the same +conditions. Unexplained. + +**A ~20 s teardown of idle data paths** has its own write-up in +`IDF-ISSUE-3-nan-schedule-request.md`. + +## No workaround exists in the public API + +All 23 public `esp_wifi_nan_*` functions, both `wifi_nan_sync_config_t` and +`wifi_nan_datapath_resp_t`, and the four NAN Kconfig options were checked. +None exposes availability, scheduling or transmit timing. `nan_app.c:1634` +only reports the TX failure after the fact. This needs a change inside the +Wi-Fi libraries. + +## Appendix: explanations considered and discarded + +Kept because each was dropped on evidence that constrains what remains. + +1. **Android offers Potential-only availability.** No — the decoded NDP + Request carries a conditional all-slot channel-6 entry in map 0. +2. **A 5 GHz-only offer, excluded because the "no 2.4GHz channel overlap" + string was absent.** Invalid — that check sits at `0x2bd`, downstream of + the early return at `0x1a8`, and is unreachable once the first check + fails. +3. **The negotiation succeeded, proved by the committed ch6 bitmap in M2.** + No — the ESP always advertises its own committed ch6 schedule; its SDFs + carry one before any NDP exists. +4. **A Discovery Window deadline, early termination at ~10-13 ms.** No — + acknowledged and unacknowledged attempts overlap across the whole range. +5. **Slot-anchored scheduling, from run 3's two bursts starting at the + identical offset one period apart.** Run 3's coincidence does not + generalise; later retries started at 0.43-0.90 slots. +6. **Burst length as an outcome oracle — five means exhausted.** No — run 22 + succeeded on the fifth frame of a five-frame burst, and run 18's + two-frame burst was never acknowledged. +7. **The phone fails to receive the ESP's ACKs.** Rests on one frame in run + 18 sent 180 us after an ACK, better explained as an already-queued retry; + runs 20 and 22 show the phone stopping immediately on acknowledgement. ## Credit -Frame capture, decode and DW timing by the bench session running the ESP32-S2 -monitor, which also identified the STA-concurrency confound and the n = 1 -weakness in the in-window evidence. +Hardware, captures and decode by the bench session running the ESP32-S2 +monitor, which also supplied corrections to items 3, 5, 6 and the capture +reliability analysis. From 76569f71ae55691a3d8f6fda3bbf0a956af42d88 Mon Sep 17 00:00:00 2001 From: tyeth Date: Mon, 23 Nov 2026 23:48:57 +0000 Subject: [PATCH 23/30] docs: state the ESP32 chip revision prominently in all three issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ESP under test is a SparkFun ESP32 Thing with an ESP32-D0WDQ6 revision v0.0 (ECO0), 26 MHz crystal — first silicon. Espressif will reasonably ask whether that accounts for timing or receive anomalies before treating them as firmware defects, so it belongs next to the environment table in every report rather than buried. Two things worth saying alongside it, both checked against this IDF. Rev v0.0 is still supported: CONFIG_ESP32_REV_MIN defaults to ESP32_REV_MIN_0, so the build boots on it by design rather than by accident. And esp_wifi, esp_phy and esp_coex contain no revision-conditional code at all — the only rev-0 workaround anywhere in IDF is the brownout interrupt. The Wi-Fi stack does not branch on chip revision, so a software-side cause would not be revision-specific. That does not exclude an analogue or RF difference in first silicon, which cannot be assessed from here, and reproduction on current silicon remains the right thing to do. Raised by the bench session, which is arranging a run on an ESP32-S2 for a second chip family on the same phone. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-1-nan-usd-rx.md | 13 ++++++++++++- IDF-ISSUE-2-nan-ndp-availability.md | 13 ++++++++++++- IDF-ISSUE-3-nan-schedule-request.md | 13 ++++++++++++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/IDF-ISSUE-1-nan-usd-rx.md b/IDF-ISSUE-1-nan-usd-rx.md index 2789a1ea91b..60c4b01002c 100644 --- a/IDF-ISSUE-1-nan-usd-rx.md +++ b/IDF-ISSUE-1-nan-usd-rx.md @@ -19,11 +19,22 @@ The subscriber's NIC counted **407 NAN SDFs** during a 60 s window in which | | | |---|---| | ESP-IDF | `v6.1-dev-6096` (also reproduced on `v6.1-dev-6107`, `cb73317`) | -| Targets | ESP32 (classic, rev0) and ESP32-S3 | +| Targets | ESP32-D0WDQ6 **rev v0.0 (ECO0)** and ESP32-S3 | | Config | `CONFIG_IDF_EXPERIMENTAL_FEATURES=y`, `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y` | | Logging | `CONFIG_WPA_DEBUG_PRINT=y` plus `esp_log_level_set("wpa", ESP_LOG_DEBUG)` | | Regulatory | `cc=01`, resolved to `GB` MANUAL | +> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying +> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. +> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to +> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no +> revision-conditional code at all** — the only rev-0 workaround anywhere in +> IDF is the brownout interrupt. So a software-side cause would not be +> revision-specific. An analogue or RF difference in first silicon cannot be +> excluded from here, and reproduction on current silicon (v3.x) is a +> reasonable thing to ask for before treating timing or receive anomalies as +> firmware defects. + Both boards publish/subscribe the service name `ESP-USD-TEST` with `ESP_USD_PUBLISH_DEFAULT_PARAMS()` / `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()`, pinned to channel 6, with no STA association. diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index a1e2b00d21e..a5d2fdb412d 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -20,10 +20,21 @@ an error. | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Target | ESP32 (classic, rev0), `wifi_aware/nan_publisher`, SOLICITED | +| Target | ESP32-D0WDQ6 **rev v0.0 (ECO0)**, `wifi_aware/nan_publisher`, SOLICITED | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | | Capture | ESP32-S2 monitor on channel 6 with ACK frames recorded | +> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying +> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. +> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to +> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no +> revision-conditional code at all** — the only rev-0 workaround anywhere in +> IDF is the brownout interrupt. So a software-side cause would not be +> revision-specific. An analogue or RF difference in first silicon cannot be +> excluded from here, and reproduction on current silicon (v3.x) is a +> reasonable thing to ask for before treating timing or receive anomalies as +> firmware defects. + ESP-to-ESP NAN-Sync on the same build works end to end — cluster 3.35 s, match 4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT. Only the Android data path is unreliable. diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index 68d55b3954e..e8a611cc857 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -20,10 +20,21 @@ The ESP has **no handling for NAF subtypes 10–13 at all**. | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Target | ESP32 (classic, rev0), `wifi_aware/nan_publisher`, SOLICITED | +| Target | ESP32-D0WDQ6 **rev v0.0 (ECO0)**, `wifi_aware/nan_publisher`, SOLICITED | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | | Capture | ESP32-S2 monitor on channel 6, with ACK frames recorded | +> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying +> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. +> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to +> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no +> revision-conditional code at all** — the only rev-0 workaround anywhere in +> IDF is the brownout interrupt. So a software-side cause would not be +> revision-specific. An analogue or RF difference in first silicon cannot be +> excluded from here, and reproduction on current silicon (v3.x) is a +> reasonable thing to ask for before treating timing or receive anomalies as +> firmware defects. + ## Observed, in three runs under both AP conditions Run 7 (phone associated to an AP on channel 64), run 8 (phone not associated From 2033727d35b307adeb0bafba038e4dd4c70d8012 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 00:28:00 +0000 Subject: [PATCH 24/30] docs: rescope ask 1 to the esp32 target; esp32s2 already does it right The hardware swap we agreed to follow wherever it led has landed, and it moves ask 1 rather than reinforcing it. An ESP32-S2 as solicited publisher established the data path in 6 of 6 runs against the same phone, same IDF, same application config, where the ESP32 manages 9 of 16. The mechanism differs: the S2 logs one M2 construction, puts no M2 on the air in the request's own Discovery Window, and sends a single M2 in the next window at 0.47-0.57 slots, first attempt, acknowledged. The ESP32 builds M2 twice, transmits at 0.92-2.12 slots in the request's own window where it is never acknowledged, and depends on a retry. So the behaviour ask 1 was requesting already exists in the esp32s2 Wi-Fi library. The ask is now "adopt the esp32s2 behaviour on esp32", with a working reference implementation beside it, which is a far better report than the one it replaces. libnet80211.a is per-target, so this is either the esp32 library or rev-0 silicon; a current-revision ESP32 would separate them. Ask 2 strengthens: the S2 logs "Avail: missing a conditional or committed entry" in all six of its successful runs, so the spurious error spans both targets. The M1 receive misses gain a candidate explanation that is not NAN-specific. Verified from the capture metadata, the phone sends NAFs at bg:48M around -38 dBm while the ESP answers at bg:6M; and a rev-0 ESP32 used as sniffer heard the 6 Mbps reference at 93-97% of an S2 sniffer's rate but the phone's 48 Mbps frames at about 5/s against 7.6/s, missing M1 entirely in three runs. Recorded with the caveat that promiscuous reception may not represent station reception. Also noted for anyone re-analysing the pcaps: the radiotap headers carry only Channel and signal strength, with no Rate field. Rates come from the sniffer's text output. Runs and the swap from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 103 ++++++++++++++++++++-------- 1 file changed, 75 insertions(+), 28 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index a5d2fdb412d..7b2508126c6 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -1,4 +1,4 @@ -# NAN: NDP Response is never acknowledged on its first attempt, and a spurious availability error +# NAN (esp32 target): NDP Response is transmitted in the wrong Discovery Window; the esp32s2 library gets it right **Status: draft, not filed.** Asks 1–3 are evidenced and ready. Two further observations are recorded but deliberately not asked about, because they rest @@ -6,14 +6,24 @@ on too little. ## Summary -An ESP32 running NAN-Sync establishes a Wi-Fi Aware data path with an Android -phone in **9 of 16 runs**. The failures share a mechanism: the ESP's first -NDP Response transmission is *never* acknowledged, in any run, and setup -depends on one of its retries being taken. +On the **esp32** target an ESP32 running NAN-Sync establishes a Wi-Fi Aware +data path with an Android phone in **9 of 16 runs**. Its NDP Response is +transmitted late in the Discovery Window the request arrived in, its first +attempt is *never* acknowledged, and setup depends on a retry being taken in +a later window. -Two smaller defects accompany it: an error-level log that fires on successful -runs, and an M2 that reports ACCEPTED after the parse that built it returned -an error. +On the **esp32s2** target, same IDF, same application config, same phone: +**6 of 6**. The S2 builds M2 once, does not transmit it in the request's own +window at all, and sends it in the next window at 0.47–0.57 slots, first +attempt, acknowledged. + +So the behaviour ask 1 requests already exists in one Espressif Wi-Fi +library. This is an esp32-target report with a working reference +implementation alongside it. + +Two smaller defects accompany it on both targets: an error-level log that +fires on successful runs, and an M2 that reports ACCEPTED after the parse +that built it returned an error. ## Environment @@ -45,6 +55,10 @@ Delivery is read from **ACK-by-RA**, with each ACK matched to the frame it *immediately* follows. A wider match window credits one ACK to two frames of a retry burst and produces false positives. +PHY rates quoted here come from the sniffer's own text output; the pcap +radiotap headers carry only Channel and signal strength, with **no Rate +field**, so rates cannot be recovered from the captures alone. + Runs 17–22 used a sniffer with a PSRAM queue and ACKs filtered to known NAN NMIs, and recorded **zero drops**. Runs 3–6 predate ACK capture and are also drop-free. Runs 7–16 overflowed a 24-entry queue (up to 1761 drops), so for @@ -52,11 +66,24 @@ those, burst sizes are lower bounds and a missing frame proves nothing. --- -## Ask 1 — answer the NDP Request on the first attempt +## Ask 1 — on esp32, defer the NDP Response to the next Discovery Window and send it early, as esp32s2 already does + +### The two targets behave differently -**The first M2 transmission is never acknowledged.** Across the five -zero-drop runs that put an M2 on the air, the opening frame of the first -burst has no ACK immediately following it, every time. +| | esp32 (D0WDQ6 rev v0.0) | esp32s2 (Lolin S2 Mini) | +|---|---|---| +| M2 constructions logged | **two** per exchange | **one** per exchange | +| M2 in the request's own DW | yes, at 0.92–2.12 slots | **none** | +| M2 in the next DW | retry, position varies | one, at 0.47–0.57 slots | +| first attempt acknowledged | **never**, 5 of 5 clean runs | **always**, first try | +| data path established | 9 of 16 | **6 of 6** | + +Same IDF (`cb73317`), same application configuration, same phone, same +channel. `libnet80211.a` is per-target, so the difference lies in the esp32 +Wi-Fi library or in rev-0 silicon; a current-revision ESP32 as publisher +would separate those two. + +### esp32: the measurements | run | first-window M2 | second-window M2 | outcome | |---|---|---|---| @@ -72,23 +99,21 @@ group-addressed frame from the phone, which sits within 1.31 ms of a Discovery Window start beacon — median 0.00 ms, sigma 0.40 ms over 593 windows, so it is a sound anchor. -The first-window M2 starts anywhere from **0.92 to 2.12 slots** after the -request, frequently past slot 1 entirely, which is where the peer is not -reliably receiving. - **It is not a position threshold.** Acknowledged and unacknowledged attempts overlap throughout the range: run 11's second burst at 0.740 failed where run 9's at 0.724 succeeded; run 13's at 0.548 failed where run 8's at 0.581 succeeded. -**It is not impossible to get right.** Run 21's retry at 0.984 slots was -acknowledged and the data path came up without a second window ever being -needed. The ESP *can* close the exchange inside the window the request -arrived in. +**The esp32 can occasionally get it right.** Run 21's retry at 0.984 slots +was acknowledged and the data path came up without a second window. It is a +reliability problem, not an impossibility. -**The ask:** transmit the NDP Response early enough in the Discovery Window -that the first attempt has a chance, and leave room for retries within that -window. At present the first attempt never lands and setup is 9 in 16. +### The ask + +On the esp32 target, adopt the esp32s2 behaviour: construct the NDP Response +once, and transmit it early in the next Discovery Window rather than late in +the current one. The esp32s2 library demonstrates this works against the same +peer with a 6-of-6 success rate. ## Ask 2 — do not log an error for a map carrying only Potential entries @@ -99,7 +124,9 @@ E (12422) wifi:Avail: missing a conditional or committed entry ``` on runs where the NDP **confirms successfully**, so it never indicated a -negotiation failure. It is an error-level message for a non-error. +negotiation failure. It is an error-level message for a non-error, and it +appears on **both targets** — the esp32s2 logs it in all 6 of its 6 +successful runs. The peer's NDP Request carries two Availability attributes: map 0 with a **conditional** channel-6 entry covering all 32 slots, and map 1 with @@ -127,10 +154,30 @@ The log and the frame disagree. ## Further observations, not asked about -**The ESP misses M1 repeatedly.** In run 18's first window the phone sent M1 -seven times and the ESP acknowledged none; it took the third copy in the next -window. Run 20's first M1 went unacknowledged, run 22's first three did. This -is an ESP receive-side problem and it is uncharacterised. +**The esp32 misses M1 repeatedly — possibly a high-rate OFDM reception +weakness.** In run 18's first window the phone sent M1 seven times and the +ESP acknowledged none; it took the third copy in the next window. Run 20's +first M1 went unacknowledged, run 22's first three did. + +There is now a candidate explanation that is not NAN-specific. The two ends +transmit at very different PHY rates, confirmed from the capture metadata: + +``` +phone NDP-Request, SchedReq bg:48M -37 to -38 dBm +ESP NDP-Response bg:6M -10 to -11 dBm +``` + +When an ESP32 rev v0.0 was used as the *sniffer*, it heard the 6 Mbps +reference transmitter at 93–97 % of the rate an ESP32-S2 sniffer recorded, +but the phone's 48 Mbps frames at only about 5/s against 7.6/s, and in three +runs it missed the phone's M1 entirely. So that part is a weak receiver for +high-rate OFDM, and the frames the ESP32-as-publisher misses are exactly the +48 Mbps ones. + +**Caveat:** promiscuous-mode reception is not necessarily representative of +normal station reception, so this is a hypothesis rather than a measurement +of the publisher's receive path. It would also be a silicon or +target-library property rather than a NAN defect. **Run 19: M2 constructed and never transmitted.** With zero capture drops there is no M2 on the air at all, although the ESP acknowledged the phone's From af00b68b250356837fbc1b4c852b96896b8d1fcd Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 00:29:31 +0000 Subject: [PATCH 25/30] docs: scope the missing-radiotap-Rate note to runs 3-28 The sniffer now emits the radiotap Rate field for non-HT frames and MCS for HT frames alongside Channel and signal strength, so captures taken from here on are self-contained. Only runs 3-28 keep their rates solely in the sniff.txt output, and for those the capture and its text log have to travel together. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 7b2508126c6..924151b9bf8 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -55,9 +55,11 @@ Delivery is read from **ACK-by-RA**, with each ACK matched to the frame it *immediately* follows. A wider match window credits one ACK to two frames of a retry burst and produces false positives. -PHY rates quoted here come from the sniffer's own text output; the pcap -radiotap headers carry only Channel and signal strength, with **no Rate -field**, so rates cannot be recovered from the captures alone. +PHY rates quoted here come from the sniffer's own text output. For runs 3–28 +the pcap radiotap headers carry only Channel and signal strength and **no +Rate field**, so those captures and their `*-sniff.txt` must travel together. +The sniffer has since been changed to emit radiotap Rate for non-HT frames +and MCS for HT frames, so later captures are self-contained. Runs 17–22 used a sniffer with a PSRAM queue and ACKs filtered to known NAN NMIs, and recorded **zero drops**. Runs 3–6 predate ACK capture and are also From d4079ab4682b07cfdd5fa59166883119bf69dda1 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 01:00:53 +0000 Subject: [PATCH 26/30] docs: the v3.1 run splits library from hardware; ask 1 reframed again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An ESP32-U4WDH rev v3.1 running the identical esp32 nan_publisher_sol binary established the data path 6 of 6, where the rev-0 board manages 9 of 16. That settles the question the previous revision left open: it is not the esp32 Wi-Fi library. The reframing the result forces. The esp32 library answers inside the Discovery Window the request arrived in, and on v3.1 that works — M2 at 0.884-0.892 slots, 14.48-14.61 ms into a 16.384 ms slot, 1.77 ms of margin, acknowledged first try every time, with a spread across six runs of 0.13 ms. The rev-0 board running the same binary spreads over 19.7 ms, 150 times wider, and its best case at 0.92 slots is later than v3.1's worst at 0.892. So the defect is a strategy with almost no margin rather than a wrong one, and the ask becomes: adopt the esp32s2 approach, which defers M2 to the next window and sends it early, and therefore does not depend on how fast the chip turns a request around. Failing that, give the same-window path enough margin for the slowest silicon the build supports, which is still rev v0.0. Two things kept honest. The rev-0 board differs from the v3.1 board in crystal (26 MHz with XTAL_FREQ_AUTO, versus 40 MHz) and flash (external versus embedded) as well as revision, so "rev 0" means "this rev-0 board"; of the three the crystal is the one most worth suspecting for a timing defect, and that is untested. And it is still not a position cutoff, since a rev-0 retry at 0.984 was acknowledged where first attempts at 0.92 were not. Ask 2 now holds on three targets. The M1 receive misses also vanish on v3.1 with no phone retransmissions at all, which fits the rev-0 board's weak 48 Mbps OFDM reception rather than anything in the code. Runs and the board swap from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 151 +++++++++++++++------------- 1 file changed, 82 insertions(+), 69 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 924151b9bf8..51654fb5119 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -1,4 +1,4 @@ -# NAN (esp32 target): NDP Response is transmitted in the wrong Discovery Window; the esp32s2 library gets it right +# NAN: the esp32 NDP Response strategy has ~1.8 ms of margin and fails on slower supported hardware **Status: draft, not filed.** Asks 1–3 are evidenced and ready. Two further observations are recorded but deliberately not asked about, because they rest @@ -6,44 +6,48 @@ on too little. ## Summary -On the **esp32** target an ESP32 running NAN-Sync establishes a Wi-Fi Aware -data path with an Android phone in **9 of 16 runs**. Its NDP Response is -transmitted late in the Discovery Window the request arrived in, its first -attempt is *never* acknowledged, and setup depends on a retry being taken in -a later window. +The esp32 Wi-Fi library answers an NDP Request **inside the Discovery Window +the request arrived in**. On current silicon that works: an ESP32-U4WDH +rev v3.1 transmits M2 at 0.884–0.892 slots, about **1.8 ms before the window +closes**, acknowledged first try, and establishes the data path in **6 of 6** +runs. -On the **esp32s2** target, same IDF, same application config, same phone: -**6 of 6**. The S2 builds M2 once, does not transmit it in the request's own -window at all, and sends it in the next window at 0.47–0.57 slots, first -attempt, acknowledged. +The same binary on an ESP32-D0WDQ6 **rev v0.0** board transmits anywhere from +0.92 to 2.12 slots — a spread **150 times wider** — overshoots the window, +is never acknowledged on the first attempt, and establishes the data path in +**9 of 16** runs. Rev v0.0 is a supported target +(`CONFIG_ESP32_REV_MIN` defaults to `ESP32_REV_MIN_0`). -So the behaviour ask 1 requests already exists in one Espressif Wi-Fi -library. This is an esp32-target report with a working reference -implementation alongside it. +The **esp32s2** library uses a different strategy — defer M2 to the *next* +Discovery Window and send it early in slot 0 — which does not depend on +processing latency at all. It is **6 of 6**. -Two smaller defects accompany it on both targets: an error-level log that -fires on successful runs, and an M2 that reports ACCEPTED after the parse -that built it returned an error. +So this is not "esp32 does it wrong". It is a strategy with very little +margin, which holds on fast hardware and fails on slow hardware that the +build still supports, next to a sibling library whose strategy has no such +dependency. + +Two smaller defects accompany it on all three targets: an error-level log +that fires on successful runs, and an M2 that reports ACCEPTED after the +parse that built it returned an error. ## Environment | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Target | ESP32-D0WDQ6 **rev v0.0 (ECO0)**, `wifi_aware/nan_publisher`, SOLICITED | +| Targets | ESP32-D0WDQ6 **rev v0.0**, ESP32-U4WDH **rev v3.1**, ESP32-S2 (Lolin S2 Mini) | +| Example | `wifi_aware/nan_publisher`, SOLICITED, identical config on all three | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | | Capture | ESP32-S2 monitor on channel 6 with ACK frames recorded | -> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying -> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. -> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to -> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no -> revision-conditional code at all** — the only rev-0 workaround anywhere in -> IDF is the brownout interrupt. So a software-side cause would not be -> revision-specific. An analogue or RF difference in first silicon cannot be -> excluded from here, and reproduction on current silicon (v3.x) is a -> reasonable thing to ask for before treating timing or receive anomalies as -> firmware defects. +> **Chip revision.** Rev v0.0 is a supported target — `CONFIG_ESP32_REV_MIN` +> defaults to `ESP32_REV_MIN_0` — and `esp_wifi`, `esp_phy` and `esp_coex` +> contain **no revision-conditional code at all**; the only rev-0 workaround +> anywhere in IDF is the brownout interrupt. So the library is byte-identical +> across revisions, which the v3.1 run confirms directly: the *same binary* +> succeeds 6 of 6 there and manages 9 of 16 on the rev-0 board. The +> difference is in the hardware or its timing, not in branching code. ESP-to-ESP NAN-Sync on the same build works end to end — cluster 3.35 s, match 4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT. Only the Android @@ -68,54 +72,59 @@ those, burst sizes are lower bounds and a missing frame proves nothing. --- -## Ask 1 — on esp32, defer the NDP Response to the next Discovery Window and send it early, as esp32s2 already does +## Ask 1 — adopt the esp32s2 defer-to-next-window strategy on esp32 -### The two targets behave differently +### Three targets, two strategies -| | esp32 (D0WDQ6 rev v0.0) | esp32s2 (Lolin S2 Mini) | -|---|---|---| -| M2 constructions logged | **two** per exchange | **one** per exchange | -| M2 in the request's own DW | yes, at 0.92–2.12 slots | **none** | -| M2 in the next DW | retry, position varies | one, at 0.47–0.57 slots | -| first attempt acknowledged | **never**, 5 of 5 clean runs | **always**, first try | -| data path established | 9 of 16 | **6 of 6** | +| | ESP32 rev v0.0 | ESP32 rev v3.1 | ESP32-S2 | +|---|---|---|---| +| Wi-Fi library | esp32 | esp32 (**identical binary**) | esp32s2 | +| M2 constructions logged | two | one | one | +| M2 in the request's own DW | yes, 0.92–2.12 slots | yes, 0.884–0.892 slots | **none** | +| M2 in the next DW | retry, position varies | — | one, 0.47–0.57 slots | +| first attempt acknowledged | **never** | **always** | **always** | +| phone M1 retransmissions | up to 7 | none | none | +| data path established | **9 of 16** | **6 of 6** | **6 of 6** | -Same IDF (`cb73317`), same application configuration, same phone, same -channel. `libnet80211.a` is per-target, so the difference lies in the esp32 -Wi-Fi library or in rev-0 silicon; a current-revision ESP32 as publisher -would separate those two. +### The margin is the problem -### esp32: the measurements +A Discovery Window slot is 16.384 ms. The v3.1 board transmits M2 at +**14.48–14.61 ms** into it, leaving **1.77 ms**. Its spread across six runs +is 0.008 slots — **0.13 ms**. -| run | first-window M2 | second-window M2 | outcome | -|---|---|---|---| -| 17 | 5 fr @ 1.58–1.68, none acked | 2 fr @ 0.42–0.46, 1st acked | OK | -| 18 | 2 fr @ 0.96–1.04, none acked | 3 fr @ 0.75–0.83, 3rd acked | OK | -| 19 | **no M2 on air at all** | — | FAIL | -| 20 | 5 fr @ 0.96–1.21, none acked | 1 fr @ 0.24, acked | OK | -| 21 | 2 fr @ 0.95–0.98, **2nd acked** | — | OK | -| 22 | 5 fr @ 2.05–2.15, none acked | 5 fr @ 0.22–0.33, 5th acked | OK | - -Offsets are in slots (1 slot = 16 TU = 16.384 ms) from the preceding -group-addressed frame from the phone, which sits within 1.31 ms of a -Discovery Window start beacon — median 0.00 ms, sigma 0.40 ms over 593 -windows, so it is a sound anchor. - -**It is not a position threshold.** Acknowledged and unacknowledged attempts -overlap throughout the range: run 11's second burst at 0.740 failed where -run 9's at 0.724 succeeded; run 13's at 0.548 failed where run 8's at 0.581 -succeeded. - -**The esp32 can occasionally get it right.** Run 21's retry at 0.984 slots -was acknowledged and the data path came up without a second window. It is a -reliability problem, not an impossibility. +The rev-0 board, running the *same binary*, spreads over 1.200 slots — +**19.7 ms**, 150 times wider — and its *best* case (0.92) is already later +than the v3.1 board's *worst* case (0.892). + +That it builds M2 twice where v3.1 builds it once is a symptom of the same +binary taking the retry path, not a code difference. + +**This is not a sharp position cutoff.** A rev-0 retry at 0.984 slots was +acknowledged in run 21, later than first attempts at 0.92 that were not. The +variability matters more than the mean. ### The ask -On the esp32 target, adopt the esp32s2 behaviour: construct the NDP Response -once, and transmit it early in the next Discovery Window rather than late in -the current one. The esp32s2 library demonstrates this works against the same -peer with a 6-of-6 success rate. +Adopt the esp32s2 strategy on esp32: construct the NDP Response once and +transmit it early in the *next* Discovery Window, rather than late in the +current one. The esp32s2 library already demonstrates it against the same +peer, and unlike the same-window approach it does not depend on how quickly +the chip can turn a request around. + +Failing that, the same-window strategy needs enough margin to survive the +slowest silicon the build supports, which today is rev v0.0. + +### Confounds, stated plainly + +The two ESP32 boards differ in more than silicon revision: **rev v0.0 with a +26 MHz crystal (`XTAL_FREQ_AUTO`) and external flash**, versus **rev v3.1 +with a 40 MHz crystal and embedded flash**. So "rev 0" here means "this rev-0 +board". + +Of the three differences the **crystal** is the one most worth suspecting for +a *timing* defect, since Wi-Fi timing derives from it and 26 MHz is the less +common configuration. That is a hypothesis and it is testable with a rev-0 +board on a 40 MHz crystal, which we do not have. ## Ask 2 — do not log an error for a map carrying only Potential entries @@ -127,8 +136,8 @@ E (12422) wifi:Avail: missing a conditional or committed entry on runs where the NDP **confirms successfully**, so it never indicated a negotiation failure. It is an error-level message for a non-error, and it -appears on **both targets** — the esp32s2 logs it in all 6 of its 6 -successful runs. +appears on **all three targets** — the esp32s2 and the ESP32 rev v3.1 each +log it in all 6 of their 6 successful runs. The peer's NDP Request carries two Availability attributes: map 0 with a **conditional** channel-6 entry covering all 32 slots, and map 1 with @@ -176,6 +185,10 @@ runs it missed the phone's M1 entirely. So that part is a weak receiver for high-rate OFDM, and the frames the ESP32-as-publisher misses are exactly the 48 Mbps ones. +The v3.1 board supports this: running the identical binary it acknowledged +every M1 first try, with **no phone retransmissions at all** in six runs. +Whatever causes the misses travels with the rev-0 board, not with the code. + **Caveat:** promiscuous-mode reception is not necessarily representative of normal station reception, so this is a hypothesis rather than a measurement of the publisher's receive path. It would also be a silicon or From 6e966faa6123047bdd2d901e0a96685b17736387 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 01:02:35 +0000 Subject: [PATCH 27/30] docs: reorder the timing-scatter suspects; drop the crystal hypothesis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I had suggested the 26 MHz crystal as the likeliest cause of the timing scatter. That does not survive scrutiny and is demoted to third. A crystal frequency error produces ppm-scale drift, which NAN TSF synchronisation corrects continuously, and a mis-set XTAL_FREQ generally breaks RF outright rather than adding jitter. A 19.7 ms spread in when M2 is handed to the MAC has the signature of execution latency instead: task preemption, interrupt latency, or flash-cache misses while constructing M2 from code or rodata not held in IRAM — on a board whose flash is external, against one with embedded flash. Suspects for the timing scatter are now ordered: execution latency on the rev-0 board first, revision-specific RF or MAC behaviour second, the crystal last. The 48 Mbps receive weakness keeps RF or silicon as its leading suspect, since that is a different kind of failure. I looked for a documented IDF erratum to support the cache explanation. ESP32_ECO3_CACHE_LOCK_FIX is the obvious candidate and does not apply — it depends on !ESP_SYSTEM_SINGLE_CORE_MODE && SPIRAM and neither board has PSRAM. The draft now says explicitly that the ordering is reasoning from the shape of the measurements rather than a citation. Reasoning from the bench session; the Kconfig check is mine. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 39 +++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 51654fb5119..693dea24cbb 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -117,14 +117,37 @@ slowest silicon the build supports, which today is rev v0.0. ### Confounds, stated plainly The two ESP32 boards differ in more than silicon revision: **rev v0.0 with a -26 MHz crystal (`XTAL_FREQ_AUTO`) and external flash**, versus **rev v3.1 -with a 40 MHz crystal and embedded flash**. So "rev 0" here means "this rev-0 -board". - -Of the three differences the **crystal** is the one most worth suspecting for -a *timing* defect, since Wi-Fi timing derives from it and 26 MHz is the less -common configuration. That is a hypothesis and it is testable with a rev-0 -board on a 40 MHz crystal, which we do not have. +26 MHz crystal (`XTAL_FREQ_AUTO`) and external SPI flash**, versus **rev +v3.1 with a 40 MHz crystal and embedded flash**. So "rev 0" here means "this +rev-0 board". + +For the **timing scatter**, the shape of the data points at execution +latency rather than at the clock source. A 19.7 ms spread in *when M2 is +handed to the MAC* is what task preemption, interrupt latency or +flash-cache misses look like — M2 construction running code or reading +rodata that is not in IRAM, on a board whose flash is external. A crystal +frequency error would be expected to produce ppm-scale drift, which NAN TSF +synchronisation continuously corrects, and a mis-set `XTAL_FREQ` usually +breaks RF outright rather than adding millisecond jitter. Ordering of +suspects, most likely first: + +1. variable execution latency on the rev-0 board — cache and flash path, + core behaviour +2. revision-specific RF or MAC behaviour +3. the crystal + +No documented IDF-level erratum supports this. `ESP32_ECO3_CACHE_LOCK_FIX` +is the obvious candidate and does **not** apply: it `depends on +!ESP_SYSTEM_SINGLE_CORE_MODE && SPIRAM`, and neither board has PSRAM. So the +ordering above is reasoning from the shape of the measurements, not a +citation. + +For the **48 Mbps receive weakness** the ordering is different: RF or +silicon behaviour, possibly including the crystal's effect on the PHY, is +the leading suspect there rather than execution latency. + +Separating any of these needs a second rev-0 board, ideally one with +embedded flash or a 40 MHz crystal, which we do not have. ## Ask 2 — do not log an error for a map carrying only Potential entries From 552f17c1f79b61fdd8662c88e355017003e27262 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 01:09:04 +0000 Subject: [PATCH 28/30] docs: split the rev-0 delay distribution; crystal scaling leads for the floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Treating the rev-0 first-M2 delays as one population hid the structure. Split, they are a tight cluster at 15.089-15.305 ms (sd 0.08, as tight as v3.1's 0.051) and a separate tail from 15.77 to 33.06 ms. That changes the diagnosis. The v3.1 guard before the end of slot 0 is 1.841 ms, within 2 us of 1.8 TU, so it is a designed constant rather than whatever latency allows. The rev-0 cluster's guard is 1.167 ms, a ratio of 0.634 against 26/40 = 0.650 — predicting 15.188 ms where 15.217 was measured, a 29 us miss. 25/40 fits equally well and cannot be separated; a factor of one half is about 5 sd out. So the floor is consistent with a crystal-derived scaling error and the tail is execution latency, and the earlier ordering that put the crystal last is revised accordingly, per phenomenon rather than overall. One correction to the mechanism as proposed: a guard specified in ticks for 40 MHz but counted at 26 MHz would run longer and transmit earlier, the opposite of what is seen. The fit requires a guard converted to ticks with the real 26 MHz crystal and then consumed against a 40 MHz timebase. A blob search for it came up empty and that is recorded. Neither libnet80211.a nor libpp.a references any crystal or clock frequency helper among their 1453 and 447 undefined symbols; no literal 40000000, 26000000, 73728 or 1843200 appears; the NAN datapath literal pool holds nothing of guard-time magnitude, only log line numbers; hal_tsf.o has no literals at all. The only clock-dependent external called is ROM's ets_delay_us. The hypothesis therefore cannot be confirmed or refuted from the blob. The decisive test is a rev v3.x board with a 26 MHz crystal, which should land at about 15.19 ms if the crystal is the cause. Distribution split and the scaling idea from Tyeth and the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 109 +++++++++++++++++++--------- 1 file changed, 75 insertions(+), 34 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 693dea24cbb..7a504bab7cf 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -114,40 +114,81 @@ the chip can turn a request around. Failing that, the same-window strategy needs enough margin to survive the slowest silicon the build supports, which today is rev v0.0. -### Confounds, stated plainly - -The two ESP32 boards differ in more than silicon revision: **rev v0.0 with a -26 MHz crystal (`XTAL_FREQ_AUTO`) and external SPI flash**, versus **rev -v3.1 with a 40 MHz crystal and embedded flash**. So "rev 0" here means "this -rev-0 board". - -For the **timing scatter**, the shape of the data points at execution -latency rather than at the clock source. A 19.7 ms spread in *when M2 is -handed to the MAC* is what task preemption, interrupt latency or -flash-cache misses look like — M2 construction running code or reading -rodata that is not in IRAM, on a board whose flash is external. A crystal -frequency error would be expected to produce ppm-scale drift, which NAN TSF -synchronisation continuously corrects, and a mis-set `XTAL_FREQ` usually -breaks RF outright rather than adding millisecond jitter. Ordering of -suspects, most likely first: - -1. variable execution latency on the rev-0 board — cache and flash path, - core behaviour -2. revision-specific RF or MAC behaviour -3. the crystal - -No documented IDF-level erratum supports this. `ESP32_ECO3_CACHE_LOCK_FIX` -is the obvious candidate and does **not** apply: it `depends on -!ESP_SYSTEM_SINGLE_CORE_MODE && SPIRAM`, and neither board has PSRAM. So the -ordering above is reasoning from the shape of the measurements, not a -citation. - -For the **48 Mbps receive weakness** the ordering is different: RF or -silicon behaviour, possibly including the crystal's effect on the PHY, is -the leading suspect there rather than execution latency. - -Separating any of these needs a second rev-0 board, ideally one with -embedded flash or a 40 MHz crystal, which we do not have. +### The rev-0 distribution has two parts, and they have different causes + +Splitting the rev-0 first-M2 delays rather than treating them as one +population changes the picture. Measured from M1: + +``` +v3.1 (40 MHz XTAL) 14.485 14.616 14.490 14.541 14.606 14.522 + mean 14.543, sd 0.051 guard = 16.384 - 14.543 = 1.841 ms = 1.80 TU + +rev 0 (26 MHz XTAL) cluster: 15.089 15.184 15.249 15.257 15.305 sd ~0.08 + guard = 1.167 ms + tail: 15.77 16.08 16.83 16.93 19.22 19.92 26.09 33.06 +``` + +The v3.1 guard is **1.80 TU**, within 2 µs of 1843.2 µs — a constant guard +before the end of slot 0, not an accident of latency. The rev-0 *cluster* is +just as tight (sd 0.08 vs 0.051), so it is not jitter either; it is the same +mechanism with a shorter guard. + +**The guard ratio is 1.167 / 1.841 = 0.634.** Against 26/40 = 0.650 that +predicts a delay of 15.188 ms where 15.217 was measured — a 29 µs miss. 25/40 +predicts 15.234, a 17 µs miss; the two cannot be separated. A factor of ½ +predicts 15.464, about 5 sd out, and 40/26 is nowhere near. + +So the rev-0 *floor* is consistent with a crystal-derived scaling error in +the guard, which moves the first M2 from 0.887 to 0.927 slots — into the +region where this phone does not acknowledge. The *tail* above 15.8 ms +remains execution latency, or rescheduling after the shortened deadline has +already been missed. + +**Direction of the error.** A guard specified in ticks for 40 MHz but +counted at 26 MHz would run *longer* (2.83 ms) and transmit *earlier*, which +is the opposite of what is seen. The fit requires the reverse: a guard +converted to ticks using the real 26 MHz crystal and then consumed against a +40 MHz timebase, giving 1.196 ms. Anyone looking for this in code should +expect a multiply by the measured crystal frequency feeding a fixed-40 MHz +consumer, not a hard-coded 40 being used where the real value belonged. + +**What the blob does not show.** Searched for it and came up empty, which is +worth recording: + +- Neither `libnet80211.a` nor `libpp.a` references any crystal or clock + frequency helper — no `rtc_clk_xtal_freq_get`, no `esp_clk_xtal_freq`, + nothing matching xtal/clk_freq/apb_freq among 1453 and 447 undefined + symbols respectively. +- No literal `40000000`, `26000000`, `73728` or `1843200` appears in any of + them. +- `ieee80211_nan_datapath.o`'s literal pool holds nothing of plausible + guard-time magnitude; the few values in range are source line numbers + passed to log calls. `hal_tsf.o` has no literals at all. +- The only clock-dependent external the blobs call is ROM's + `ets_delay_us`. + +So the guard is not a visible constant in these objects. If the scaling error +is real it lives in MAC register programming, in ROM, or in a computation the +literal scan cannot see — and it cannot be confirmed or refuted from the +blob. + +**The decisive test** is a **rev v3.x board with a 26 MHz crystal**. If the +crystal is the cause, its first M2 should land at about 15.19 ms (0.927 +slots) despite current silicon. That separates crystal from revision cleanly, +which no board we have can do. + +Suspect ordering, by phenomenon: + +| phenomenon | leading suspect | +|---|---| +| the 15.2 ms floor | crystal-derived scaling of the guard | +| the tail to 33 ms | execution latency, cache and flash path | +| 48 Mbps receive misses | RF or silicon behaviour | + +**Caveats.** The cluster is n=5 and was chosen post hoc, though there is a +natural gap from 15.31 to 15.77. 26/40 and 25/40 are indistinguishable at +this precision. The M1 anchor is common to both boards, so it cannot +contribute the difference. ## Ask 2 — do not log an error for a map carrying only Potential entries From 53c87218411d585d903e1183066160dd5a817201 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 01:10:49 +0000 Subject: [PATCH 29/30] docs: withdraw the timing ask; the rev-0 board was a faulty instrument MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The evidence for the NDP Response timing ask came entirely from one board, and that board turns out to have a bidirectional RF fault. Measured per board: the rev-0 Thing needs 9.81 transmissions per unicast frame against 1.00 on an ESP32 rev v3.1 and 1.01 on an ESP32-S2. At 0-4 ms into the Discovery Window, where the peer is certainly listening, the phone acknowledges only 44 of 388 of the Thing's first transmissions — 11%, against 275 of 278, or 99%, for v3.1. The same board received the phone's 48 Mbps OFDM poorly when used as a sniffer. The phone simply cannot decode most of what that board transmits, so the M2 failures cannot be attributed to transmit timing and the ask is withdrawn rather than reworded. On current silicon the data path comes up in 16 of 16 runs: 6 ESP32-S2 solicited, 6 v3.1 solicited, 4 v3.1 unsolicited. Three previously fenced observations are reattributed to that board, with zero occurrences on v3.1 or S2: the ESP missing M1 up to seven times, run 19's constructed-but-unsent M2, and off-AP discovery failing with an unsolicited publish. The last is positively refuted — v3.1 discovered in 0.55-0.76 s in 4 of 4 runs with about 114 group-addressed SDFs each, so the phone does not ignore group-addressed SDFs off-AP. What survives is two small defects, both reproducing on all three targets: the error-level Avail log that fires on successful runs, and ACCEPTED being reported after the parse returned 262. They are now asks 1 and 2. The 26/40 guard-scaling fit is kept as a curiosity about that board rather than an ESP-IDF ask, with the observation that a clock fault scaling a guard by 26/40 would also produce carrier frequency offset, and carrier offset degrades OFDM decode in both directions — so one faulty clock path may explain the timing floor and the RF loss together. Runs 35-38 and the per-board retry and ACK analysis from the bench session. Co-Authored-By: Claude Opus 5 --- IDF-ISSUE-2-nan-ndp-availability.md | 384 ++++++++-------------------- 1 file changed, 110 insertions(+), 274 deletions(-) diff --git a/IDF-ISSUE-2-nan-ndp-availability.md b/IDF-ISSUE-2-nan-ndp-availability.md index 7a504bab7cf..54d548aa029 100644 --- a/IDF-ISSUE-2-nan-ndp-availability.md +++ b/IDF-ISSUE-2-nan-ndp-availability.md @@ -1,196 +1,33 @@ -# NAN: the esp32 NDP Response strategy has ~1.8 ms of margin and fails on slower supported hardware +# NAN: a spurious error-level availability log, and ACCEPTED reported after a parse error -**Status: draft, not filed.** Asks 1–3 are evidenced and ready. Two further -observations are recorded but deliberately not asked about, because they rest -on too little. +**Status: draft, not filed.** Two small defects, both reproduced on three +targets. A third ask about NDP Response timing was withdrawn — see +[The withdrawn timing ask](#the-withdrawn-timing-ask). ## Summary -The esp32 Wi-Fi library answers an NDP Request **inside the Discovery Window -the request arrived in**. On current silicon that works: an ESP32-U4WDH -rev v3.1 transmits M2 at 0.884–0.892 slots, about **1.8 ms before the window -closes**, acknowledged first try, and establishes the data path in **6 of 6** -runs. +Wi-Fi Aware data paths between an ESP32 and an Android phone work. On +current silicon they came up in **16 of 16** runs — 6 on an ESP32-S2 +(solicited), 6 on an ESP32 rev v3.1 (solicited), 4 on the same v3.1 +(unsolicited). -The same binary on an ESP32-D0WDQ6 **rev v0.0** board transmits anywhere from -0.92 to 2.12 slots — a spread **150 times wider** — overshoots the window, -is never acknowledged on the first attempt, and establishes the data path in -**9 of 16** runs. Rev v0.0 is a supported target -(`CONFIG_ESP32_REV_MIN` defaults to `ESP32_REV_MIN_0`). +Two defects remain, neither affecting whether the data path forms: -The **esp32s2** library uses a different strategy — defer M2 to the *next* -Discovery Window and send it early in slot 0 — which does not depend on -processing latency at all. It is **6 of 6**. - -So this is not "esp32 does it wrong". It is a strategy with very little -margin, which holds on fast hardware and fails on slow hardware that the -build still supports, next to a sibling library whose strategy has no such -dependency. - -Two smaller defects accompany it on all three targets: an error-level log -that fires on successful runs, and an M2 that reports ACCEPTED after the -parse that built it returned an error. +1. An **error-level log** fires on runs that succeed. +2. The NDP Response reports **ACCEPTED** after the parse that built it + returned an error. ## Environment | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Targets | ESP32-D0WDQ6 **rev v0.0**, ESP32-U4WDH **rev v3.1**, ESP32-S2 (Lolin S2 Mini) | -| Example | `wifi_aware/nan_publisher`, SOLICITED, identical config on all three | +| Targets | ESP32-U4WDH **rev v3.1**, ESP32-S2 (Lolin S2 Mini) | +| Example | `wifi_aware/nan_publisher`, solicited and unsolicited | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | -| Capture | ESP32-S2 monitor on channel 6 with ACK frames recorded | - -> **Chip revision.** Rev v0.0 is a supported target — `CONFIG_ESP32_REV_MIN` -> defaults to `ESP32_REV_MIN_0` — and `esp_wifi`, `esp_phy` and `esp_coex` -> contain **no revision-conditional code at all**; the only rev-0 workaround -> anywhere in IDF is the brownout interrupt. So the library is byte-identical -> across revisions, which the v3.1 run confirms directly: the *same binary* -> succeeds 6 of 6 there and manages 9 of 16 on the rev-0 board. The -> difference is in the hardware or its timing, not in branching code. - -ESP-to-ESP NAN-Sync on the same build works end to end — cluster 3.35 s, -match 4.40 s, IPv6 data path 4.93 s, ICMPv6 at 2 ms RTT. Only the Android -data path is unreliable. - -### Method - -Delivery is read from **ACK-by-RA**, with each ACK matched to the frame it -*immediately* follows. A wider match window credits one ACK to two frames of -a retry burst and produces false positives. - -PHY rates quoted here come from the sniffer's own text output. For runs 3–28 -the pcap radiotap headers carry only Channel and signal strength and **no -Rate field**, so those captures and their `*-sniff.txt` must travel together. -The sniffer has since been changed to emit radiotap Rate for non-HT frames -and MCS for HT frames, so later captures are self-contained. - -Runs 17–22 used a sniffer with a PSRAM queue and ACKs filtered to known NAN -NMIs, and recorded **zero drops**. Runs 3–6 predate ACK capture and are also -drop-free. Runs 7–16 overflowed a 24-entry queue (up to 1761 drops), so for -those, burst sizes are lower bounds and a missing frame proves nothing. - ---- - -## Ask 1 — adopt the esp32s2 defer-to-next-window strategy on esp32 - -### Three targets, two strategies - -| | ESP32 rev v0.0 | ESP32 rev v3.1 | ESP32-S2 | -|---|---|---|---| -| Wi-Fi library | esp32 | esp32 (**identical binary**) | esp32s2 | -| M2 constructions logged | two | one | one | -| M2 in the request's own DW | yes, 0.92–2.12 slots | yes, 0.884–0.892 slots | **none** | -| M2 in the next DW | retry, position varies | — | one, 0.47–0.57 slots | -| first attempt acknowledged | **never** | **always** | **always** | -| phone M1 retransmissions | up to 7 | none | none | -| data path established | **9 of 16** | **6 of 6** | **6 of 6** | - -### The margin is the problem - -A Discovery Window slot is 16.384 ms. The v3.1 board transmits M2 at -**14.48–14.61 ms** into it, leaving **1.77 ms**. Its spread across six runs -is 0.008 slots — **0.13 ms**. - -The rev-0 board, running the *same binary*, spreads over 1.200 slots — -**19.7 ms**, 150 times wider — and its *best* case (0.92) is already later -than the v3.1 board's *worst* case (0.892). - -That it builds M2 twice where v3.1 builds it once is a symptom of the same -binary taking the retry path, not a code difference. - -**This is not a sharp position cutoff.** A rev-0 retry at 0.984 slots was -acknowledged in run 21, later than first attempts at 0.92 that were not. The -variability matters more than the mean. +| Capture | monitor on channel 6 with ACK frames recorded, zero drops | -### The ask - -Adopt the esp32s2 strategy on esp32: construct the NDP Response once and -transmit it early in the *next* Discovery Window, rather than late in the -current one. The esp32s2 library already demonstrates it against the same -peer, and unlike the same-window approach it does not depend on how quickly -the chip can turn a request around. - -Failing that, the same-window strategy needs enough margin to survive the -slowest silicon the build supports, which today is rev v0.0. - -### The rev-0 distribution has two parts, and they have different causes - -Splitting the rev-0 first-M2 delays rather than treating them as one -population changes the picture. Measured from M1: - -``` -v3.1 (40 MHz XTAL) 14.485 14.616 14.490 14.541 14.606 14.522 - mean 14.543, sd 0.051 guard = 16.384 - 14.543 = 1.841 ms = 1.80 TU - -rev 0 (26 MHz XTAL) cluster: 15.089 15.184 15.249 15.257 15.305 sd ~0.08 - guard = 1.167 ms - tail: 15.77 16.08 16.83 16.93 19.22 19.92 26.09 33.06 -``` - -The v3.1 guard is **1.80 TU**, within 2 µs of 1843.2 µs — a constant guard -before the end of slot 0, not an accident of latency. The rev-0 *cluster* is -just as tight (sd 0.08 vs 0.051), so it is not jitter either; it is the same -mechanism with a shorter guard. - -**The guard ratio is 1.167 / 1.841 = 0.634.** Against 26/40 = 0.650 that -predicts a delay of 15.188 ms where 15.217 was measured — a 29 µs miss. 25/40 -predicts 15.234, a 17 µs miss; the two cannot be separated. A factor of ½ -predicts 15.464, about 5 sd out, and 40/26 is nowhere near. - -So the rev-0 *floor* is consistent with a crystal-derived scaling error in -the guard, which moves the first M2 from 0.887 to 0.927 slots — into the -region where this phone does not acknowledge. The *tail* above 15.8 ms -remains execution latency, or rescheduling after the shortened deadline has -already been missed. - -**Direction of the error.** A guard specified in ticks for 40 MHz but -counted at 26 MHz would run *longer* (2.83 ms) and transmit *earlier*, which -is the opposite of what is seen. The fit requires the reverse: a guard -converted to ticks using the real 26 MHz crystal and then consumed against a -40 MHz timebase, giving 1.196 ms. Anyone looking for this in code should -expect a multiply by the measured crystal frequency feeding a fixed-40 MHz -consumer, not a hard-coded 40 being used where the real value belonged. - -**What the blob does not show.** Searched for it and came up empty, which is -worth recording: - -- Neither `libnet80211.a` nor `libpp.a` references any crystal or clock - frequency helper — no `rtc_clk_xtal_freq_get`, no `esp_clk_xtal_freq`, - nothing matching xtal/clk_freq/apb_freq among 1453 and 447 undefined - symbols respectively. -- No literal `40000000`, `26000000`, `73728` or `1843200` appears in any of - them. -- `ieee80211_nan_datapath.o`'s literal pool holds nothing of plausible - guard-time magnitude; the few values in range are source line numbers - passed to log calls. `hal_tsf.o` has no literals at all. -- The only clock-dependent external the blobs call is ROM's - `ets_delay_us`. - -So the guard is not a visible constant in these objects. If the scaling error -is real it lives in MAC register programming, in ROM, or in a computation the -literal scan cannot see — and it cannot be confirmed or refuted from the -blob. - -**The decisive test** is a **rev v3.x board with a 26 MHz crystal**. If the -crystal is the cause, its first M2 should land at about 15.19 ms (0.927 -slots) despite current silicon. That separates crystal from revision cleanly, -which no board we have can do. - -Suspect ordering, by phenomenon: - -| phenomenon | leading suspect | -|---|---| -| the 15.2 ms floor | crystal-derived scaling of the guard | -| the tail to 33 ms | execution latency, cache and flash path | -| 48 Mbps receive misses | RF or silicon behaviour | - -**Caveats.** The cluster is n=5 and was chosen post hoc, though there is a -natural gap from 15.31 to 15.77. 26/40 and 25/40 are indistinguishable at -this precision. The M1 anchor is common to both boards, so it cannot -contribute the difference. - -## Ask 2 — do not log an error for a map carrying only Potential entries +## Ask 1 — do not log an error for a map carrying only Potential entries The ESP logs @@ -198,16 +35,16 @@ The ESP logs E (12422) wifi:Avail: missing a conditional or committed entry ``` -on runs where the NDP **confirms successfully**, so it never indicated a -negotiation failure. It is an error-level message for a non-error, and it -appears on **all three targets** — the esp32s2 and the ESP32 rev v3.1 each -log it in all 6 of their 6 successful runs. +on runs where the NDP **confirms successfully**. It appears on **all three +targets**, including every one of the 16 successful runs on current silicon. +It never indicated a negotiation failure: it is an error-level message for a +non-error. -The peer's NDP Request carries two Availability attributes: map 0 with a +The peer's NDP Request carries two Availability attributes — map 0 with a **conditional** channel-6 entry covering all 32 slots, and map 1 with -**potential** 5 GHz entries (op class 128, bitmap `0x0020` — the block -centred on 155, containing the NAN 5 GHz discovery channel 149). -Potential-only is exactly what a map-1 entry is for. +**potential** 5 GHz entries (op class 128, bitmap `0x0020`, the block +centred on 155 containing NAN's 5 GHz discovery channel 149). Potential-only +is exactly what a map-1 entry is for. `nan_parse_ndp_req` calls `nan_dp_parse_availability` from an attribute walk (backward branch `0x442 -> 0x135`), consistent with the error coming from the @@ -216,99 +53,98 @@ records keyed on map ID — but it is called from `nan_sched_alloc_conditional`, `nan_sched_allocate_crbs` and `nan_dp_indicate_faw_start`, never from the parser. -This cost two independent investigations several days. - -## Ask 3 — do not report ACCEPTED after the parse returned an error +This message sent two independent investigations down the wrong path for +days. -`nan_dp_parse_availability` logs and returns 262 at `0x1a8`, jumping to -`0x41f`, two instructions before `retw.n` at `0x422`; the success path returns -0 at `0x417`. The M2 the ESP then transmits carries status `0x11`, ACCEPTED. -The log and the frame disagree. +## Ask 2 — do not report ACCEPTED after the parse returned an error ---- +In `ieee80211_nan_datapath.o`, `nan_dp_parse_availability` logs and returns +262 at `0x1a8`, jumping to `0x41f` — two instructions before `retw.n` at +`0x422`. The success path returns 0 at `0x417`. The M2 the ESP then +transmits carries status `0x11`, ACCEPTED. The log and the frame disagree. -## Further observations, not asked about +## The withdrawn timing ask -**The esp32 misses M1 repeatedly — possibly a high-rate OFDM reception -weakness.** In run 18's first window the phone sent M1 seven times and the -ESP acknowledged none; it took the third copy in the next window. Run 20's -first M1 went unacknowledged, run 22's first three did. +Earlier revisions asked Espressif to change how the esp32 library schedules +the NDP Response, on the evidence that its first transmission was never +acknowledged and setup succeeded in only 9 of 16 runs. **That evidence came +entirely from one board, and that board turned out to be faulty.** -There is now a candidate explanation that is not NAN-specific. The two ends -transmit at very different PHY rates, confirmed from the capture metadata: +The board was a SparkFun ESP32 Thing, ESP32-D0WDQ6 **rev v0.0**, 26 MHz +crystal, external flash. Its radio link to the phone is bad in both +directions: -``` -phone NDP-Request, SchedReq bg:48M -37 to -38 dBm -ESP NDP-Response bg:6M -10 to -11 dBm -``` - -When an ESP32 rev v0.0 was used as the *sniffer*, it heard the 6 Mbps -reference transmitter at 93–97 % of the rate an ESP32-S2 sniffer recorded, -but the phone's 48 Mbps frames at only about 5/s against 7.6/s, and in three -runs it missed the phone's M1 entirely. So that part is a weak receiver for -high-rate OFDM, and the frames the ESP32-as-publisher misses are exactly the -48 Mbps ones. - -The v3.1 board supports this: running the identical binary it acknowledged -every M1 first try, with **no phone retransmissions at all** in six runs. -Whatever causes the misses travels with the rev-0 board, not with the code. - -**Caveat:** promiscuous-mode reception is not necessarily representative of -normal station reception, so this is a hypothesis rather than a measurement -of the publisher's receive path. It would also be a silicon or -target-library property rather than a NAN defect. - -**Run 19: M2 constructed and never transmitted.** With zero capture drops -there is no M2 on the air at all, although the ESP acknowledged the phone's -M1 — so it received the request — and its log records building M2 twice, -then `TX Confirm failed`, then rejecting. In its place it sent 14 unicast -Service Discovery Frames to the phone at roughly M1 + 529-548 ms, none -acknowledged, and 3 more at about +1050 ms. One observation; needs repeats. - -**Off-AP discovery fails with an unsolicited publish.** Runs 5 and 6 saw 88 -of 123 group-addressed publish SDFs land at or before +10 ms with the correct -service ID and cluster, and the phone's firmware reported no match at all. A -*solicited* (unicast) publish discovered in 1.25-1.6 s in the same -conditions. Unexplained. - -**A ~20 s teardown of idle data paths** has its own write-up in -`IDF-ISSUE-3-nan-schedule-request.md`. - -## No workaround exists in the public API - -All 23 public `esp_wifi_nan_*` functions, both `wifi_nan_sync_config_t` and -`wifi_nan_datapath_resp_t`, and the four NAN Kconfig options were checked. -None exposes availability, scheduling or transmit timing. `nan_app.c:1634` -only reports the TX failure after the fact. This needs a change inside the -Wi-Fi libraries. - -## Appendix: explanations considered and discarded - -Kept because each was dropped on evidence that constrains what remains. - -1. **Android offers Potential-only availability.** No — the decoded NDP - Request carries a conditional all-slot channel-6 entry in map 0. -2. **A 5 GHz-only offer, excluded because the "no 2.4GHz channel overlap" - string was absent.** Invalid — that check sits at `0x2bd`, downstream of - the early return at `0x1a8`, and is unreachable once the first check - fails. -3. **The negotiation succeeded, proved by the committed ch6 bitmap in M2.** - No — the ESP always advertises its own committed ch6 schedule; its SDFs - carry one before any NDP exists. -4. **A Discovery Window deadline, early termination at ~10-13 ms.** No — - acknowledged and unacknowledged attempts overlap across the whole range. -5. **Slot-anchored scheduling, from run 3's two bursts starting at the - identical offset one period apart.** Run 3's coincidence does not - generalise; later retries started at 0.43-0.90 slots. -6. **Burst length as an outcome oracle — five means exhausted.** No — run 22 - succeeded on the fifth frame of a five-frame burst, and run 18's - two-frame burst was never acknowledged. -7. **The phone fails to receive the ESP's ACKs.** Rests on one frame in run - 18 sent 180 us after an ACK, better explained as an already-queued retry; - runs 20 and 22 show the phone stopping immediately on acknowledgement. +| | rev-0 Thing | ESP32 rev v3.1 | ESP32-S2 | +|---|---|---|---| +| transmissions per unicast frame | **9.81** | 1.00 | 1.01 | +| first transmission acked, 0–4 ms into DW | **44/388 = 11 %** | 275/278 = 99 % | — | +| data path established | 9 of 16 | 6 of 6 | 6 of 6 | + +At 0–4 ms into the Discovery Window the peer is certainly listening, and the +phone still failed to receive or decode **89 %** of that board's frames. The +same board also received the phone's 48 Mbps OFDM poorly when used as a +sniffer. A bidirectional RF-level problem — carrier frequency offset from +the 26 MHz crystal, or rev-0 RF — fits both directions; it was not measurable +with the available equipment. + +So the M2 failures cannot be attributed to transmit timing, and the ask is +withdrawn rather than reworded. + +### What remains interesting about it + +One observation survives as a curiosity rather than a defect. The esp32 +library answers inside the Discovery Window the request arrived in, with a +guard before the end of slot 0 of **1.841 ms = 1.80 TU** on v3.1 (mean of +six runs, sd 0.051 ms) — a designed constant, within 2 µs of 1843.2 µs. + +On the rev-0 board the equivalent guard was 1.167 ms. The ratio, 0.634, sits +between 26/40 = 0.650 and 25/40 = 0.625, which a crystal-derived scaling of +the guard would produce; 26/40 predicts a delay of 15.188 ms against 15.217 +measured. The direction requires a guard converted to ticks with the real +26 MHz crystal and then consumed against a 40 MHz timebase — not a +hard-coded 40 used where the real value belonged, which would lengthen the +guard rather than shorten it. + +Nothing in the blob supports or refutes it. Neither `libnet80211.a` nor +`libpp.a` references any crystal or clock frequency helper among their 1453 +and 447 undefined symbols; no literal `40000000`, `26000000`, `73728` or +`1843200` appears; `ieee80211_nan_datapath.o`'s literal pool holds nothing of +guard-time magnitude, only log line numbers; `hal_tsf.o` has no literals at +all. The only clock-dependent external called is ROM's `ets_delay_us`. + +A rev v3.x board with a 26 MHz crystal would settle it — predicted first M2 +at about 15.19 ms. We have no such board, and with the RF fault identified +the question is academic for ESP-IDF purposes. + +It is worth noting that the two anomalies on that board may share one cause. +A clock problem that scaled a guard interval by roughly 26/40 would also +produce a carrier frequency offset, and carrier offset degrades OFDM decode +in both directions — which is exactly the 11 %-versus-99 % asymmetry and the +poor 48 Mbps reception. One faulty crystal or clock path explains the timing +floor and the RF loss together, and neither needs an ESP-IDF defect to +account for it. + +## Previously fenced observations, now attributed to the faulty board + +- **The ESP missing M1 up to seven times running** — zero occurrences on + v3.1 or S2. +- **Run 19's M2 constructed and never transmitted** — zero occurrences on + v3.1 or S2. +- **Off-AP discovery failing with an unsolicited publish** — does not + reproduce. The v3.1 board discovered in 0.55–0.76 s in 4 of 4 runs, with + about 114 group-addressed publish SDFs per run, and the data path came up + every time. The phone does not ignore group-addressed SDFs off-AP; runs 5 + and 6 failed because of the publisher. + +## Related + +`IDF-ISSUE-3-nan-schedule-request.md` — the ESP has no handling for NAF +subtypes 10–13, so a peer's Schedule Request is never answered and idle data +paths are torn down. That one reproduces on every target and is unaffected +by any of the above. ## Credit -Hardware, captures and decode by the bench session running the ESP32-S2 -monitor, which also supplied corrections to items 3, 5, 6 and the capture -reliability analysis. +Hardware, captures and decode by the bench session running the monitor, +which identified the faulty board and supplied the measurements that +withdrew the timing ask. From ad81c7f8c2178e444ca1235de3b5e2edb1f112e9 Mon Sep 17 00:00:00 2001 From: tyeth Date: Tue, 24 Nov 2026 14:28:40 +0000 Subject: [PATCH 30/30] docs: issue 1 localised to A3 filtering; issue 3 reproduced on current silicon Issue 1 (NAN-USD RX) is no longer a hypothesis. On an ESP32 rev v3.1 and an ESP32-S2, with entry logging in esp_nan_de_rx_action() and on every ROC request, the subscriber holds channel 6 continuously (56 accepted 1 s ROCs, allow_broadcast=1) while 134 publish SDFs go past, and rx_cb is entered zero times. Rewriting only A3 of the publisher's group SDFs to ff:ff:ff:ff:ff:ff makes them arrive and discovery complete in about a second; rewriting only A1 does not. Unicast frames with the same A3 are delivered. This contradicts the allow_broadcast documentation, and since nan_de_tx_multicast() sends A3 = NAN Network ID, ESP-to-ESP USD cannot work as shipped. The patch now carries the full instrumentation and the A1/A3 experiment. Issue 3 (Schedule Request) reproduced on the ESP32 rev v3.1: four idle runs, two with the phone on an AP and two without, each with two MAC-ACKed Schedule Requests at +12 s and +18 s, no response, and a HAL teardown at 21 s. Across runs 23-42 on current silicon the phone sent 23 Schedule Requests, all ACKed, none answered. The esp32s2, esp32c5 and esp32c61 libraries lack schedule handlers too. Co-Authored-By: Claude Opus 5.5 --- IDF-ISSUE-1-localise.patch | 108 +++++++++-- IDF-ISSUE-1-nan-usd-rx.md | 278 ++++++++++++++-------------- IDF-ISSUE-3-nan-schedule-request.md | 64 +++++-- 3 files changed, 270 insertions(+), 180 deletions(-) diff --git a/IDF-ISSUE-1-localise.patch b/IDF-ISSUE-1-localise.patch index 9f70b195059..99d82eb9b8e 100644 --- a/IDF-ISSUE-1-localise.patch +++ b/IDF-ISSUE-1-localise.patch @@ -1,29 +1,97 @@ -Subject: [PATCH] nan_usd: log entry to the action-frame Rx callback +Subject: [PATCH] nan_usd: instrument the USD action-frame Rx path (diagnostic) -Diagnostic only; not a fix. NAN-USD discovery never completes because -nan_de_rx_sdf() is never called, even though the subscriber's own radio -counts 407 NAN SDFs in 60 s. Review of esp_nan_de_rx_action() shows every -gate in it should pass for those frames, so the open question is whether the -callback is entered at all. +Diagnostic only; not a fix. Applies to cb73317. -Never printed -> frames are dropped below the supplicant, in the Wi-Fi - libraries or the hardware Rx filter. Note that NAN SDFs - carry the NAN Network ID 51:6f:9a:01:00:00 in A1 and A3, - which is multicast but not broadcast. -Printed -> the loss is in the gate chain below, and is fixable here. +- Logs every entry to esp_nan_de_rx_action() with A1/A2/A3 and the first six + body bytes, and which early-return gate failed, if any. +- Logs every remain-on-channel request with allow_broadcast and its return + code, and every WIFI_EVENT_ROC_DONE. +- With -DLOCALISE_TX_BCAST=1/2/3 (C define), esp_nan_de_tx() replaces the NAN + Network ID with ff:ff:ff:ff:ff:ff in A1 / A3 / both, for group-addressed + SDFs only. This is the experiment showing A3 decides delivery. -MSG_ERROR rather than MSG_DEBUG so the result does not depend on the -reporter's configured log level. +MSG_ERROR so the result does not depend on the configured log level. +diff --git a/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c b/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c +index 30d54c8a8e..1ce5f5bcfd 100644 --- a/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c +++ b/components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c -@@ -141,6 +141,9 @@ - - int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t channel) - { -+ wpa_printf(MSG_ERROR, "NAN-USD: rx_action entered, len=%u chan=%u", -+ (unsigned)len, (unsigned)channel); -+ +@@ -127,6 +127,7 @@ static void nan_de_tx_event_handler(void *arg, esp_event_base_t event_base, + } else if (event_id == WIFI_EVENT_ROC_DONE) { + wifi_event_roc_done_t *evt = (wifi_event_roc_done_t *)event_data; + int freq = esp_nan_chan_to_freq(evt->channel); ++ wpa_printf(MSG_ERROR, "NAN-USD: ROC_DONE chan=%u", (unsigned)evt->channel); + if (freq == -1) { + wpa_printf(MSG_ERROR, "Invalid channel received from ROC done handler"); + return; +@@ -144,8 +145,18 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha struct ieee80211_hdr *rx_hdr = (struct ieee80211_hdr *)hdr; struct nan_de *nan_de = NULL; int freq; ++ static unsigned s_rx_count; ++ ++ /* LOCALISE: log every entry, MSG_ERROR so it does not depend on log level. */ ++ s_rx_count++; ++ wpa_printf(MSG_ERROR, "NAN-USD: rx_action #%u len=%u chan=%u A1=" MACSTR " A2=" MACSTR " A3=" MACSTR ++ " body=%02x %02x %02x%02x%02x %02x", ++ s_rx_count, (unsigned)len, (unsigned)channel, MAC2STR(rx_hdr->addr1), MAC2STR(rx_hdr->addr2), ++ MAC2STR(rx_hdr->addr3), len > 0 ? payload[0] : 0, len > 1 ? payload[1] : 0, len > 2 ? payload[2] : 0, ++ len > 3 ? payload[3] : 0, len > 4 ? payload[4] : 0, len > 5 ? payload[5] : 0); + + if (len < 6) { ++ wpa_printf(MSG_ERROR, "NAN-USD: gate len<6"); + /* Frame too short for NAN-SDF frame */ + return ESP_FAIL; + } +@@ -169,6 +180,8 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha + /* Received a valid NAN Service Discovery Frame */ + } else { + /* Frame is not a NAN SDF frame */ ++ wpa_printf(MSG_ERROR, "NAN-USD: gate not-SDF cat=%u pa=%u oui=%06x type=%u", ++ category, public_action, (unsigned)oui_value, oui_type); + return ESP_FAIL; + } + +@@ -179,8 +192,10 @@ int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t cha + } + + if (!nan_usd_try_lock_active(&nan_de)) { ++ wpa_printf(MSG_ERROR, "NAN-USD: gate lock/inactive"); + return ESP_FAIL; + } ++ wpa_printf(MSG_ERROR, "NAN-USD: -> nan_de_rx_sdf freq=%d", freq); + nan_de_rx_sdf(nan_de, rx_hdr->addr2, rx_hdr->addr3, freq, payload, len - 6); + NAN_USD_DATA_UNLOCK(); + return ESP_OK; +@@ -204,6 +219,18 @@ static int esp_nan_de_tx(void *ctx, unsigned int freq, unsigned int wait_time, + req->wait_time_ms = wait_time; + memcpy(req->dest_mac, dst, ETH_ALEN); + memcpy(req->bssid, bssid, ETH_ALEN); ++#ifdef LOCALISE_TX_BCAST ++ /* LOCALISE experiment: replace the NAN Network ID 51:6f:9a:01:00:00 (multicast, not broadcast) ++ * with ff:ff:ff:ff:ff:ff. Bit 0 = A1 (dest), bit 1 = A3 (BSSID). Only group-addressed SDFs are touched. */ ++ if (dst[0] & 1) { ++ if (LOCALISE_TX_BCAST & 1) { ++ memset(req->dest_mac, 0xff, ETH_ALEN); ++ } ++ if (LOCALISE_TX_BCAST & 2) { ++ memset(req->bssid, 0xff, ETH_ALEN); ++ } ++ } ++#endif + req->no_ack = false; + req->data_len = buf_len; + req->rx_cb = esp_nan_de_rx_action; +@@ -250,7 +277,11 @@ static int esp_nan_de_listen(void *ctx, unsigned int freq, unsigned int duration + req->done_cb = NULL; + req->allow_broadcast = true; + +- if (esp_wifi_remain_on_channel(req) != ESP_OK) { ++ esp_err_t roc_err = esp_wifi_remain_on_channel(req); ++ /* LOCALISE: show every listen request the subscriber makes, and whether the library accepted it. */ ++ wpa_printf(MSG_ERROR, "NAN-USD: ROC req chan=%d dur=%u allow_bcast=%d -> %d", channel, duration, ++ req->allow_broadcast, roc_err); ++ if (roc_err != ESP_OK) { + wpa_printf(MSG_ERROR, "ROC request failure"); + os_free(req); + return ESP_FAIL; diff --git a/IDF-ISSUE-1-nan-usd-rx.md b/IDF-ISSUE-1-nan-usd-rx.md index 60c4b01002c..1f822b1f109 100644 --- a/IDF-ISSUE-1-nan-usd-rx.md +++ b/IDF-ISSUE-1-nan-usd-rx.md @@ -1,179 +1,177 @@ -# NAN-USD: received Service Discovery Frames never reach the discovery engine +# NAN-USD: group-addressed SDFs are dropped before the ROC Rx callback unless A3 is broadcast, so USD discovery never completes -**Status: draft, not filed.** One measurement is still outstanding — see -[What would settle it](#what-would-settle-it). +**Status: draft, ready.** Measured on current silicon (ESP32 rev v3.1 and +ESP32-S2) with instrumented logging in the open-source receive path. The loss +is localised to below the supplicant, and the deciding address field is +identified. ## Summary -With `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, a USD publisher transmits valid NAN -Service Discovery Frames and a USD subscriber's own radio receives them, but -`nan_de_rx_sdf()` is never called, so discovery never completes. Two ESP32s -configured as publisher and subscriber never discover each other, in either -role assignment. +With `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, a USD subscriber that is listening on +the right channel never has its ROC receive callback (`rx_cb`, +`esp_nan_de_rx_action()`) entered for the publisher's Service Discovery +Frames, so discovery never completes. Two ESP boards running the unmodified +`usd_publisher` / `usd_subscriber` examples never discover each other, in +either role assignment. -The subscriber's NIC counted **407 NAN SDFs** during a 60 s window in which -`nan_de_rx_sdf()` was entered zero times. +The frames are dropped because their **Address 3 (BSSID) is the NAN Network ID +`51:6f:9a:01:00:00`, not broadcast**. Changing only A3 to +`ff:ff:ff:ff:ff:ff` makes them arrive and discovery complete in under a +second. Changing only A1 does not. + +This contradicts the documented behaviour of `wifi_roc_req_t.allow_broadcast`, +which the USD listen path sets to `true`: + +> If set to true, broadcast/multicast action frames from any network +> (Address3/BSSID=ANY) will be received in the ROC Rx callback ## Environment | | | |---|---| -| ESP-IDF | `v6.1-dev-6096` (also reproduced on `v6.1-dev-6107`, `cb73317`) | -| Targets | ESP32-D0WDQ6 **rev v0.0 (ECO0)** and ESP32-S3 | -| Config | `CONFIG_IDF_EXPERIMENTAL_FEATURES=y`, `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y` | -| Logging | `CONFIG_WPA_DEBUG_PRINT=y` plus `esp_log_level_set("wpa", ESP_LOG_DEBUG)` | -| Regulatory | `cc=01`, resolved to `GB` MANUAL | - -> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying -> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. -> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to -> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no -> revision-conditional code at all** — the only rev-0 workaround anywhere in -> IDF is the brownout interrupt. So a software-side cause would not be -> revision-specific. An analogue or RF difference in first silicon cannot be -> excluded from here, and reproduction on current silicon (v3.x) is a -> reasonable thing to ask for before treating timing or receive anomalies as -> firmware defects. - -Both boards publish/subscribe the service name `ESP-USD-TEST` with -`ESP_USD_PUBLISH_DEFAULT_PARAMS()` / `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()`, -pinned to channel 6, with no STA association. +| ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | +| Targets | ESP32-U4WDH **rev v3.1** (40 MHz crystal) and ESP32-S2FNR2 rev v1.0 | +| Projects | `examples/wifi/wifi_aware/usd_publisher` and `usd_subscriber`, unchanged apart from logging | +| Config | `CONFIG_IDF_EXPERIMENTAL_FEATURES=y`, `CONFIG_ESP_WIFI_NAN_USD_ENABLE=y`, `CONFIG_ESP_WIFI_DEBUG_PRINT=y`, `esp_log_level_set("wpa", ESP_LOG_DEBUG)` | +| Mode | `WIFI_MODE_NULL`, no association, default channel 6 | +| Capture | a third ESP32 in promiscuous mode on channel 6, written to pcap | -## What was measured +An earlier round on an ESP32 rev v0.0 and an ESP32-S3 showed the same +outcome. Everything below is from the rev v3.1 and S2 boards. -**The publisher transmits correctly.** Captured off the air with an -independent ESP32 in promiscuous mode: Public Action (category `0x04`), -Vendor Specific (`0x09`), WFA OUI `50:6f:9a`, OUI type `0x13`, carrying SDA -(`0x03`) and SDEA (`0x0e`) attributes, at −58 dBm, roughly every 150 ms. -These are well-formed NAN SDFs. +## Instrumentation -**The subscriber's radio receives them.** Running promiscuous mode alongside -the USD subscribe on the same chip, the subscriber counted 407 NAN SDFs in -60 s. +All in open source, in `esp_supplicant/src/esp_nan_usd.c`, at `MSG_ERROR` so +the result does not depend on log level (patch attached as +`IDF-ISSUE-1-localise.patch`): + +- the first line of `esp_nan_de_rx_action()` logs every entry with A1, A2, A3 + and the first six body bytes, and each early-return gate logs which gate + failed; +- `esp_nan_de_listen()` logs every `esp_wifi_remain_on_channel()` request, + its `allow_broadcast` value and its return code; +- the `WIFI_EVENT_ROC_DONE` handler logs each completion. + +## What was measured -**The discovery engine is never invoked.** `nan_de_rx_sdf()` -(`components/wpa_supplicant/src/common/nan_de.c:1271`) logs `NAN: RX SDF from` -at `MSG_DEBUG`. That line never appears. The logging is definitely live: the -positive control +**The subscriber is listening on the right channel the whole time.** In a 60 s +run it issued 56 consecutive ROC requests on channel 6, 1000 ms each, +`allow_broadcast=1`, every one returning `ESP_OK`, each followed by +`ROC_DONE`: ``` -D (785) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST +D (677) wpa: NAN: Assigned new subscribe handle 1 for ESP-USD-TEST +E (687) wpa: NAN-USD: ROC req chan=6 dur=1000 allow_bcast=1 -> 0 +E (1687) wpa: NAN-USD: ROC_DONE chan=6 +E (1687) wpa: NAN-USD: ROC req chan=6 dur=1000 allow_bcast=1 -> 0 +... ``` -is emitted from the same module at the same level in the same run. - -## Ruled out by measurement - -- **Channel.** Both ends pinned to channel 6; `esp_nan_chan_to_freq(6)` - returns 2437, which is correct. -- **Receiver off-channel.** `WIFI_EVENT_ROC_DONE` fires for channel 6 about - once a second throughout. -- **Transmit failure.** `WIFI_EVENT_ACTION_TX_STATUS` never reports `FAILED`. -- **Start-time skew.** Publisher started first, subscriber first, and both - simultaneously. -- **Regulatory domain.** Channel 6 is permitted under the active domain. -- **Power save.** Disabled. -- **Chip and direction.** Roles swapped between the ESP32 and the ESP32-S3; - zero discoveries in every combination. -- **`.type` / active-vs-passive.** Not a factor, and worth stating because it - is the obvious thing to try: the USD path ignores it. - `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and - `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, - .solicited = true`, so setting it changes nothing. - -## The open-source path looks correct +**The publisher's SDFs are on the air, well-formed and strong.** In the same +60 s, the sniffer captured 134 USD publish SDFs from the publisher on channel +6 at about −10 dBm: Public Action, Vendor Specific, WFA OUI, OUI type `0x13`, +SDA and SDEA attributes, with A1 = A3 = `51:6f:9a:01:00:00`. Two other NAN +devices nearby added 164 more SDFs on channel 6, at −32 and −61 dBm. -`esp_nan_de_rx_action()` -(`components/wpa_supplicant/esp_supplicant/src/esp_nan_usd.c:142`) is -registered as `rx_cb` on both the action-TX request and the remain-on-channel -request. Reviewed against the captured frames, every gate in it should pass: +**`rx_cb` is never entered.** Not once for any of those roughly 300 frames. +Because the entry log is the first statement in the callback, no gate in the +open-source path is involved. The frames are discarded below the supplicant. -- `len < 6` — frames are far longer. -- Category `WLAN_ACTION_PUBLIC`, action `WLAN_PA_VENDOR_SPECIFIC`, OUI - `OUI_WFA`, OUI type `NAN_OUI_TYPE` — all four match the capture exactly. -- `esp_nan_chan_to_freq(6)` returns 2437, not `-1`. -- `nan_usd_try_lock_active()` fails only if the mutex is absent or `g_nan_de` - is `NULL`; the subscribe succeeded, so `g_nan_de` is set. +The same holds with the roles swapped (ESP32 publishing, ESP32-S2 +subscribing): 39 accepted ROC windows on channel 6, 87 publish SDFs on air, +zero callback entries, no discovery. -The listen path at `esp_nan_usd.c:240` also sets `req->allow_broadcast = true` -on the `wifi_roc_req_t`, which is documented as what lets broadcast/multicast -action frames from any network reach the callback. +## The deciding experiment -So nothing in the supplicant explains the loss. +The publisher was rebuilt so that `esp_nan_de_tx()` replaces the NAN Network +ID with `ff:ff:ff:ff:ff:ff` in A1, in A3, or in both, for group-addressed SDFs +only. Nothing else changed. ESP32-S2 publishing, ESP32 rev v3.1 subscribing: -## Leading hypothesis +| A1 (DA) | A3 (BSSID) | `rx_cb` entered | discovery | +|---|---|---|---| +| `51:6f:9a:01:00:00` | `51:6f:9a:01:00:00` | never (134 frames on air) | never | +| `ff:ff:ff:ff:ff:ff` | `51:6f:9a:01:00:00` | never (101 frames on air) | never | +| `51:6f:9a:01:00:00` | `ff:ff:ff:ff:ff:ff` | yes | 1.0 s after boot | +| `ff:ff:ff:ff:ff:ff` | `ff:ff:ff:ff:ff:ff` | yes | 0.9 s after boot | -NAN SDFs carry the NAN Network ID `51:6f:9a:01:00:00` in both A1 and A3. The -first octet is `0x51`, whose I/G bit is set, so this is a **multicast address -but not the broadcast address**. The hardware receive filter on a STA -interface accepts frames addressed to the station's own MAC, to broadcast, and -to multicast groups it has joined. +With A3 broadcast, the first frame arrives and is processed normally: -The hypothesis is that the NAN Network ID is not installed in the receive -filter while USD is running, so these frames are dropped in hardware before -`rx_cb` is ever reached. The `allow_broadcast` documentation explicitly -distinguishes the two cases — "frames whose Address3/BSSID is already -broadcast are always delivered" — and `51:6f:9a:01:00:00` is not broadcast. +``` +E (867) wpa: NAN-USD: rx_action #1 len=24 chan=6 A1=ff:ff:ff:ff:ff:ff A2=7c:e8:b1:4a:11:14 A3=ff:ff:ff:ff:ff:ff body=04 09 506f9a 13 +D (877) wpa: NAN: RX SDF from 7c:e8:b1:4a:11:14 freq=2437 len=18 +I (897) wpa: NAN_USD DISCOVERY_RESULT - subscribe_id = 1 peer_publish_id = 1 peer_address = 7c:e8:b1:4a:11:14 service_protocol_type = 0 +``` -This fits the central observation. Promiscuous mode counts the frames because -promiscuous delivery bypasses the MAC address filter and is a different -delivery path from the management-frame callback; it does not re-enable -`rx_cb` for them. +The reverse direction (ESP32 publishing with A3 broadcast, ESP32-S2 +subscribing) also discovers at once: the subscriber matched before its USB +console attached, about a second after boot, and its unicast follow-ups to the +publisher are on air from the start of the capture. With the stock A3 it +never discovers. -**This is a hypothesis, not a measurement.** It is consistent with everything -observed, but the receive filter is inside `libnet80211.a` and cannot be -inspected from source. +**Unicast frames are not affected.** Follow-ups addressed to the receiver's +own MAC, with A3 still `51:6f:9a:01:00:00`, reach `rx_cb` normally; the +ESP32 publisher logged 20 such entries and 11 follow-up receptions. So the +filter applies to group-addressed frames whose A3 is not broadcast. -## What would settle it +## Why ESP-to-ESP USD can never work as shipped -One line, in open source, at the top of `esp_nan_de_rx_action()`: +The supplicant itself transmits USD SDFs with A3 set to the NAN Network ID. +In `components/wpa_supplicant/src/common/nan_de.c`, `nan_de_tx_multicast()`: ```c -int esp_nan_de_rx_action(uint8_t *hdr, uint8_t *payload, size_t len, uint8_t channel) -{ -+ wpa_printf(MSG_ERROR, "NAN-USD: rx_action entered, len=%u chan=%u", (unsigned)len, channel); - struct ieee80211_hdr *rx_hdr = (struct ieee80211_hdr *)hdr; + if (srv->is_p2p) { + network_id = p2p_network_id; + bssid = wildcard_bssid; + } else { + network_id = nan_network_id; + bssid = nan_network_id; + } ``` -- **Never printed** → the frames are dropped below the supplicant, and the - receive-filter hypothesis above is the place to look. -- **Printed, but `nan_de_rx_sdf()` still not reached** → the loss is in the - open-source gate chain after all, and the specific gate is then one more log - line away. That case is fixable in this repository. - -`MSG_ERROR` rather than `MSG_DEBUG` deliberately, so the result does not -depend on the reporter's log level. - -This is already applied on a branch, based on `cb73317` so it matches the -pin currently under test: - -``` -https://github.com/tyeth/esp-idf/tree/nan-usd-rx-localise -``` - -One commit, one file, +14/−0. - -## Reproducer - -No NAN application code is required. Two ESP32s, one calling -`esp_wifi_nan_usd_start()` with a publish, the other with a subscribe, both -pinned to channel 6, with `esp_log_level_set("wpa", ESP_LOG_DEBUG)`. The -subscriber never reports a discovery. +So every non-P2P USD publish or active subscribe an ESP sends carries an A3 +that another ESP's receive path discards. Discovery between two ESPs cannot +complete, in either direction, whatever the timing or channel. + +## Already ruled out + +- **Channel.** Both ends on channel 6; `esp_nan_chan_to_freq(6)` = 2437. The + subscriber is on channel 6 for essentially the whole run (ROC log above). +- **The open-source gate chain.** The entry log precedes every gate and never + prints, so none of `len < 6`, category/action/OUI/type, + `esp_nan_chan_to_freq()` or `nan_usd_try_lock_active()` is involved. +- **Signal level.** The publisher was received by the sniffer at −10 to + −17 dBm, the other devices at −32 and −61 dBm; none reached `rx_cb`. +- **Transmit failure.** The frames are on air, and with A3 changed the same + frames are received. +- **Chip.** ESP32 rev v3.1 and ESP32-S2 behave identically, both directions. +- **`.type` / active vs passive.** The USD path ignores it: + `ESP_USD_SUBSCRIBE_DEFAULT_PARAMS()` hardcodes `.active = false` and + `ESP_USD_PUBLISH_DEFAULT_PARAMS()` hardcodes `.unsolicited = true, + .solicited = true`. ## Impact -NAN-USD is non-functional for discovery on ESP-IDF today. Since -`ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` and not -on `SOC_WIFI_NAN_SUPPORT`, USD is the only Wi-Fi Aware mode available on parts -such as the ESP32-S3, and it is the only one that can run alongside a STA -association. Both properties make it the natural foundation for a portable -Wi-Fi Aware binding, and neither is usable while discovery does not complete. +NAN-USD discovery does not work between ESP devices on ESP-IDF today. It also +cannot receive standard USD SDFs from other implementations, since the Wi-Fi +Aware specification puts a non-broadcast value in A3 (the NAN Cluster ID in +v4.0; the comment in `nan_de.c` near the follow-up path discusses this). The +same filter also drops NAN-Sync SDFs, whose A3 is a Cluster ID such as +`50:6f:9a:01:db:dd`: none of those reached `rx_cb` either. + +Since `ESP_WIFI_NAN_USD_ENABLE` depends only on `IDF_EXPERIMENTAL_FEATURES` +and not on `SOC_WIFI_NAN_SUPPORT`, USD is the only Wi-Fi Aware mode on parts +such as the ESP32-S3, and the only one that can run alongside a STA +association. ## Asks -1. Is the NAN Network ID `51:6f:9a:01:00:00` installed in the receive filter - when USD is active on the STA interface? -2. If not, should `allow_broadcast` cover it, or is a separate multicast - subscription needed? -3. Would you take the instrumentation line above, or is there an existing way - to trace `rx_cb` delivery that we have missed? +1. **Make `allow_broadcast` behave as documented**: when set on a ROC + request, deliver group-addressed Public Action frames to `rx_cb` whatever + their A3, not only when A3 is broadcast. +2. Until then, consider whether `nan_de_tx_multicast()` should use the + wildcard BSSID for A3 on the non-P2P path, as it already does for P2P. + That alone makes ESP-to-ESP USD work (measured above), though it does not + fix reception from other implementations. +3. If the current filtering is intended, please correct the + `allow_broadcast` documentation, and say how a USD subscriber is meant to + receive SDFs whose A3 is the NAN Network ID or a Cluster ID. diff --git a/IDF-ISSUE-3-nan-schedule-request.md b/IDF-ISSUE-3-nan-schedule-request.md index e8a611cc857..c5c1925a955 100644 --- a/IDF-ISSUE-3-nan-schedule-request.md +++ b/IDF-ISSUE-3-nan-schedule-request.md @@ -1,9 +1,9 @@ # NAN: Schedule Request from a peer is never answered, and idle data paths are torn down -**Status: draft, ready.** The mechanism is identified in the binary and the -behaviour is reproduced in three runs under both AP conditions. The impact is -narrower than first thought: idle data paths are torn down, data paths -carrying traffic survive. +**Status: draft, ready.** The mechanism is identified in the binary, and the +behaviour is reproduced on current silicon (ESP32 rev v3.1 and ESP32-S2) as +well as on the first board. The impact is narrower than first thought: idle +data paths are torn down, data paths carrying traffic survive. ## Summary @@ -20,22 +20,43 @@ The ESP has **no handling for NAF subtypes 10–13 at all**. | | | |---|---| | ESP-IDF | `v6.1-dev-6107` (`cb73317`), `esp_wifi/lib` at `7cd4d7b2` | -| Target | ESP32-D0WDQ6 **rev v0.0 (ECO0)**, `wifi_aware/nan_publisher`, SOLICITED | +| Targets | ESP32-U4WDH **rev v3.1** and ESP32-S2FNR2 rev v1.0 (also ESP32-D0WDQ6 rev v0.0, see below) | +| Firmware | `wifi_aware/nan_publisher`, solicited and unsolicited | | Peer | Samsung Galaxy Note 9 (SM-N960F), Android 10 / SDK 29 | -| Capture | ESP32-S2 monitor on channel 6, with ACK frames recorded | +| Capture | a separate ESP32 / ESP32-S2 monitor on channel 6, with ACK frames recorded | -> **Chip revision.** The ESP32 under test is a SparkFun ESP32 Thing carrying -> an **ESP32-D0WDQ6 revision v0.0 (ECO0)**, 26 MHz crystal — first silicon. -> This is still supported by this IDF (`CONFIG_ESP32_REV_MIN` defaults to -> `ESP32_REV_MIN_0`), and `esp_wifi`, `esp_phy` and `esp_coex` contain **no -> revision-conditional code at all** — the only rev-0 workaround anywhere in -> IDF is the brownout interrupt. So a software-side cause would not be -> revision-specific. An analogue or RF difference in first silicon cannot be -> excluded from here, and reproduction on current silicon (v3.x) is a -> reasonable thing to ask for before treating timing or receive anomalies as -> firmware defects. +## Reproduced on current silicon -## Observed, in three runs under both AP conditions +The first runs (7, 8, 9 below) used an ESP32 rev v0.0 board that later turned +out to have an RF fault. Everything was therefore repeated on an ESP32 rev +v3.1 and an ESP32-S2, where the data path itself comes up reliably (16 of 16 +runs). The Schedule Request behaviour is unchanged. + +**Idle data path, ESP32 rev v3.1, unsolicited publish, no traffic after +confirm:** + +| run | phone on an AP? | Schedule Requests (after confirm) | ESP response | NDP lifetime | how it ended | +|---|---|---|---|---|---| +| 39 | yes | +12.0 s, +18.0 s, both MAC-ACKed | none | 21.0 s | phone HAL `eventDataPathTerminated` | +| 40 | yes | +12.0 s, +18.0 s, both MAC-ACKed | none | 20.9 s | phone HAL `eventDataPathTerminated` | +| 41 | no | +12.0 s, +18.0 s, both MAC-ACKed | none | 20.9 s | phone HAL `eventDataPathTerminated` | +| 42 | no | +12.0 s, +18.0 s, both MAC-ACKed | none | 21.0 s | phone HAL `eventDataPathTerminated` | + +In all four, the phone also sent 2–6 Schedule Update Notifications (none +answered), the ESP logged nothing after `NDP confirmed`, and no NDP +Termination frame appeared on air from either side. + +**Across every current-silicon run** (runs 23–42: six on the ESP32-S2, fourteen +on the ESP32 rev v3.1, most with a 2 s keepalive), the phone sent a Schedule +Request in 19 of 20 runs, 23 frames in all, and the ESP MAC-ACKed every one. +The ESP transmitted only NDP Response (subtype 6) in every run, and never a +Schedule Response (subtype 11) or any other subtype in `0x0a`–`0x0d`. + +The rule is the same in all of them, 12 s, then 6 s, then teardown at 21 s +when idle. It does not depend on the chip, on publish type, or on whether the +phone is associated to an AP. + +## First observed, ESP32 rev v0.0, in three runs under both AP conditions Run 7 (phone associated to an AP on channel 64), run 8 (phone not associated at all) and run 9 (not associated, with keepalive traffic) all show the ESP @@ -106,7 +127,9 @@ insistently and being ignored. ## Mechanism, from the binary -`ieee80211_nan_datapath.o` in `libnet80211.a` (esp32). The receive dispatcher +`ieee80211_nan_datapath.o` in `libnet80211.a`. The same five parse handlers, +and no schedule handlers, are present in the `esp32`, `esp32s2`, `esp32c5` and +`esp32c61` libraries at `7cd4d7b2`. In the esp32 library, the receive dispatcher `nan_rx_naf` references exactly **five** parse handlers: ``` @@ -142,8 +165,9 @@ string lives in `.rodata_wlog_error.144` — it is an **error-level** message. string sits in `.rodata_wlog_error.144` — **error level**. If the dispatcher's default case were reached, that line should appear. -It does not. Across runs 2, 3, 7, 8 and 9 there are **zero** occurrences of -`Unknown NAN Action subtype` in any ESP log. In run 9 the console was captured +It does not. Across runs 2, 3, 7, 8 and 9, and the current-silicon idle +runs 39–42, there are **zero** occurrences of `Unknown NAN Action subtype` +in any ESP log. In run 9 the console was captured continuously for about 110 s: the last line is `NDP confirmed` at 12.8 s, followed by 100 s of silence while three Schedule Requests arrived, at least the first of them MAC-acknowledged. Error-level `wifi:` lines are plainly not