Skip to content

feat(bt): BLE advertisement config editor (gated advertise) - #93

Merged
ChrisUFO merged 10 commits into
mainfrom
feature/bt-adv-editor
Nov 19, 2026
Merged

ChrisUFO merged 10 commits into
mainfrom
feature/bt-adv-editor

Conversation

@ChrisUFO

Copy link
Copy Markdown
Owner

BLE advertisement config editor (PR-12 of the Merge 3 series)

Full STM32-side editor for Bluetooth advertisement configuration; advertising executes only on gated ESP32 firmware. The editor is usable and honest today: configure and persist now, advertise gated.

Closes #11

Payload preset table (provenance)

All bytes are protocol facts constructed from public format specifications — no GPL application code was copied. Pinned byte-for-byte by the host suite.

Preset Bytes Len Provenance
Name beacon 02 01 06 + [1+n][09][name] 3..31 Core Spec AD types: Flags (0x01, value 0x06) + Complete Local Name (0x09); empty name → flags-only
Apple proximity 1E FF 4C 00 07 19 + 7B tag + 1B devID + 16B body + 1B suffix 31 (full legacy cap) Apple Inc. company id 0x004C (LE 4C 00), publicly reverse-engineered continuity "Nearby Action" type 0x07, frame len 0x19=25; skeleton bytes are neutral zeros (a live tag rotates them)
Samsung Easysetup 1B FF 75 00 42 09 01 + 6B addr placeholder + filler 28 Samsung Electronics company id 0x0075 (LE 75 00), documented Easysetup identifiers 42 09
Swift Pair 06 FF 06 00 03 00 80 7 Microsoft Corp company id 0x0006 (LE 06 00), Swift Pair scenario 0x03, reserved 0x00, one 0x80 placeholder data byte
Custom (SD) any valid AD-structure payload ≤31 user-provided hex text from 0:/ble/*.adv, validated on load

Documented correction: the plan's Swift Pair anchor literal 07 FF 06 00 03 00 80 is not a self-consistent AD structure (length byte 0x07 claims 7 following bytes; only 6 follow). The shipped skeleton keeps every anchor byte after the length and corrects the length byte to the Core-Spec count (06); the module's own validator enforces this — an invalid preset cannot ship.

Every payload (preset, custom, or built) must pass m1_bt_adv_payload_valid(): a walk of [length][type][data] structures ending exactly on a structure boundary, within the 31-byte legacy cap.

Editor flow (Bluetooth → Adv Editor, 5th child)

  • Name — virtual keyboard (m1_vkb_get_filename, ≤20 chars, filename charset). Applies to the Name beacon preset (mimic presets ship byte-exact; the Apple skeleton fills the cap — no room for a name).
  • Preset — LEFT/RIGHT cycles Name beacon / Apple Prox / Samsung ES / Swift Pair / Custom (SD); OK on Custom opens the payload picker.
  • Interval — LEFT/RIGHT cycles 100/250/500/1000/2000 ms presets (all exact multiples of 5 ms → lossless unit conversion).
  • SD payload — browser over 0:/ble (same m1_fb idiom as Saved); .adv files (whitespace-tolerant hex text) parse+validate on selection; the pick is session-local by design (no new storage).
  • Start/Stop — the gated transport (below).
  • BACK: stops advertising, persists via one atomic settings_save() (shared settings_exit_save idiom). Leaving the Bluetooth menu also stops advertising and clears the session pick.

Command grammar + interval unit conversion

adv <interval_units> <PAYLOAD-HEX>    start advertising
adv stop                              stop advertising
  • Builders refuse rather than truncate (buffer bounds pinned by tests); CRLF is appended by the existing bt_cmd_process plumbing, replies read to the ">> " prompt.
  • Replies classify by line-anchored ADV:OK / ADV:FAIL markers (the console echoes the typed command, so mid-line marker substrings never classify — same discipline as the join classifier).

Interval units (documented deviation): the plan named the field <interval_ms>; the wire carries the BLE-native 0.625 ms unit instead — the native unit of esp_ble_gap_set_adv_params adv_int_min/adv_int_max — so the external console handler needs no lossy arithmetic. The STM32 converts exactly: units = ms × 8 ÷ 5; only multiples of 5 ms inside 20 ms..10.24 s (0x20..0x4000 units) are representable; everything else is refused (never rounded). Expected ESP-side mapping for the external firmware: raw 31-byte adv data (esp_ble_gap_config_adv_data_raw) + adv_int_min = adv_int_max = <interval_units>.

Gate / flash-gate behavior

The advertise minimum is pinned to ESPFW 1.2.0.0 — the version the first console image carrying the adv verb must report (chosen as the next minor after the 1.1.0.0 join-handler pairing; no advertise image exists yet). Consequences, all host-tested:

  • Currently paired 1.1.0.0 image → live gate says OLDER → "ESP update required" diagnostic, nothing is sent (gate-before-write ordering statically pinned in bt_adv_exec_start).
  • Dead console / no version marker → ABSENT → "ESP not responding" / "ESP fw unknown", nothing sent.
  • A stale DR2/DR3 record claiming 1.2.0.0 never flips a live 1.1.0.0 refusal (cache is diagnostics-only).
  • adv stop is only ever sent after a gated start succeeded (the g_bt_adv_active latch, set only after the console confirmed ADV:OK).
  • No code is written against the vendor Esp_spi_at AT+BLEADVDATAEX example (statically pinned unused); the shipped console is the custom verb surface.

Persistence fields used (PR-1 store, no new storage)

bt_adv_name (char[33]), bt_preset (u8), bt_interval_ms (u16) — applied live via the typed setters, one atomic settings_save() on BACK. Editor-shaped round-trip added to the settings-store suite; store default bt_interval_ms=0 maps to the 1000 ms preset, out-of-range bt_preset clamps to Name beacon.

Test matrix

m1_csrc/test/m1_bt_adv_test.py (wired into scripts/run_host_tests.sh), plus updates to the feature-gate and settings suites:

  • Preset table validity + provenance: every preset passes the module's own validator and matches its pinned byte image (Apple 31 = full-cap boundary; Samsung 28; Swift 7).
  • AD-structure validator: boundary walks, zero-length, overrun, trailing garbage, over-cap, two-structure payloads.
  • Command construction: exact adv <units> <HEX> strings (e.g. adv 1600 06FF0600030080), stop command, interval conversion table (100→160 … 2000→3200), BLE bounds (20 ms↔0x20, 10240 ms↔0x4000), exactness/range refusals, worst-case fit vs M1_BT_ADV_CMD_MAX, overflow refusal (never truncated).
  • Gate refusal (nothing sent): compiled real gate core — paired 1.1.0.0 (parsed from ESP32C6_FW_VERSION_LINE) → OLDER/refused; dead console → ABSENT/refused; 1.2.0.0 → EQUIVALENT/allowed; 1.3.0.0 → NEWER/allowed; stale-cache battery.
  • Settings round-trip: editor-shaped values (name/preset/interval) through the real serialize/parse core.
  • Static seams: gate-before-write ordering in bt_adv_exec_start (query + allows() precede the single bt_cmd_process write), g_bt_adv_active latched only after ADV:OK, guarded stop, menu wiring (5 Bluetooth children), persistence setters + settings_exit_save, no vendor AT advertise usage, aggregator wiring.
  • Classifier echo battery (mid-line markers, CRLF/bare-LF anchors, prompt-only, NULL).

Verification

  • sh scripts/run_host_tests.sh — all wired suites pass (incl. the new 29-check BT ADV suite; feature-gate and settings suites updated).
  • Full ARM release build sh build.sh — clean, -Werror scoped to app sources, CRC bin/hex/manifest + emitter parity + MFC/symbol verification all green.
  • python tools/check_case_sensitivity.py — 0 mismatches.
  • Threat model: no change — no credential/secret material is involved in advertisement payloads, and SD payload files are untrusted-input-validated at load; the existing trust boundaries are unchanged.

Hardware acceptance (tracked in the follow-up issue)

On ESP32 firmware with the advertise command: start advertising with each preset and observe payload + interval on a BLE scanner; verify persistence across reboot; verify the old image shows "ESP update required" and sends nothing. Steps / expected observations / rollback in #92.

External-firmware follow-up

#92 (milestone Follow-ups: Merge 3 — Features & release): the external ESP32 console adv verb implementation, the ESPFW ≥ 1.2.0.0 version pairing (ESP32C6_FW_VERSION_LINE moves with it), and the hardware acceptance checklist. The STM32 side needs no change when it lands.


Plan reference: PLAN section 15 (unit PR-12). Commits: payload preset core → editor + gated transport + menu + gate minimum → host suites → docs.

Pure, host-compilable core for the PR-12 advertisement editor
(issue #11): fixed-byte preset table (Apple proximity/continuity
0x07, Samsung Easysetup, Microsoft Swift Pair -- protocol facts
with documented provenance, no GPL application code), Bluetooth
AD-structure validator with the 31-byte legacy cap, Name-beacon
payload builder, exact ms -> 0.625 ms-unit interval conversion
(20 ms..10.24 s BLE range, multiples of 5 ms only), adv/adv-stop
console-command builders that refuse instead of truncating, a
line-anchored ADV:OK/ADV:FAIL reply classifier, and the SD custom
.hex-text parser. No console I/O here: the gated transport lives
in m1_bt.c (next commit).
Bluetooth -> Adv Editor (issue #11): name (vkb), preset cycle
(Name beacon / Apple proximity / Samsung Easysetup / Swift Pair /
Custom-from-SD), interval cycle (100..2000 ms presets), a 0:/ble
.adv payload picker, and a Start/Stop row. Edits persist through
the PR-1 store setters with one atomic settings_save() on BACK;
the custom SD pick is session-local by design (no new storage).

The advertise send funnels through bt_adv_exec_start(): the PR-10
live gate runs BEFORE any console write -- the advertise minimum
is pinned to ESPFW 1.2.0.0 (the version the first console image
carrying the adv verb must report), so the currently paired
1.1.0.0 firmware is honestly OLDER: 'ESP update required', nothing
sent. adv stop is only ever sent after a gated start succeeded;
Bluetooth exit stops advertising and clears the session pick.
Menu: fifth Bluetooth child (capacity 10).
New m1_bt_adv_test.py (wired into scripts/run_host_tests.sh):
- compiled real m1_bt_adv.c TU: preset table validity + byte-image
  provenance pins (Apple 31-byte full-cap, Samsung 28, Swift Pair 7
  with the corrected length byte), AD-structure validator battery,
  Name-beacon bounds (26 chars fills the cap, 27 refused), interval
  conversion (100..2000 ms -> 160..3200 units, BLE 0x20..0x4000
  bounds, exactness refusals), exact adv-command strings + overflow
  refusal, line-anchored ADV:OK/ADV:FAIL classifier echo battery,
  custom hex parser + .adv extension check;
- compiled real gate core: advertise minimum 1.2.0.0; the paired
  image line (ESP32C6_FW_VERSION_LINE, ESPFW 1.1.0.0) parses and is
  OLDER/refused; dead console ABSENT; 1.2.0.0 EQUIVALENT; 1.3.0.0
  NEWER; stale DR2/DR3 never flips a live refusal;
- static seams: gate-before-write ordering in bt_adv_exec_start,
  ADV:OK-latched success, guarded stop, menu wiring (5 children),
  editor persistence setters + settings_exit_save, no vendor
  AT+BLEADVDATAEX usage.

m1_esp_feature_gate_test.py: advertise minimum pin and query-matrix
cases updated to 1.2.0.0. m1_settings_store_test.py: editor-shaped
round-trip scenario (name/preset/interval).
docs/architecture.md: ESP32 co-processor interface section gains the
BLE advertisement contract -- adv <interval_units> <PAYLOAD-HEX> /
adv stop grammar, the documented <interval_ms> -> BLE 0.625 ms-unit
deviation with the exact conversion policy, the expected ESP-side
mapping (raw adv data + adv_int_min/max, line-anchored ADV:OK /
ADV:FAIL replies), the 1.2.0.0 advertise minimum and the honest
OLDER state of the currently paired 1.1.0.0 image, and the note that
the vendor AT+BLEADVDATAEX example is unused. Storage model: the two
0:/ble text conventions (.ble records vs .adv payload hex).
CHANGELOG: [Unreleased] entry for the editor. No threat-model change:
no credential or secret material is involved (reasoning in the PR
body).
Harden V1 from the PR #93 audit: bt_adv_exec_stop ignored the stop
reply -- it cleared g_bt_adv_active regardless of what the console
answered (or timed out on), silently treating a missed stop as
success. The stop path now classifies exactly like the start path:
bt_cmd_process result + line-anchored m1_bt_adv_classify_reply; only
an ADV:OK-classified reply counts as stopped, and any timeout or
ADV:FAIL surfaces 'Adv stop failed / Check ESP32' via the shared
message screen. The latch still clears on every path (Bluetooth-menu
exit, which stops before the ESP32 reset, remains the backstop) and
background discovery still resumes. Five new static pins in
m1_bt_adv_test.py: reply consulted, classification precedes the latch
clear, ADV:OK-only success, failure-message literals, discovery
resume. No changes to preset bytes, interval conversion, gate
minimum/ordering, or any other BT flow.
Iter-1 review of PR #93, both findings fixed:

Fix-now [correctness]: the RUN-row stop branch skipped the
xQueueReset(button_events_q_hdl) every sibling branch performs. A
click queued during the multi-second adv-stop + discovery-resume
exchange was consumed afterwards with the latch cleared, sending an
unintended adv start -- advertising with no user action and no
diagnostic. The reset is hoisted out of the if/else so it runs after
both the start and the stop exchange (branch audit: NAME, PRESET-
custom, FILE already reset; synchronous branches have no exchange
window). New static pins: the RUN branch resets exactly once after
BOTH paths, and the editor's single bt_wait_button reader is
preceded by it.

Advisory [correctness]: the gate refusal screen hardcoded
'Update ESP fw' as the second line for every refusal state -- the
wrong remedy for ABSENT reasons (dead console / failed round trip /
unknown version), where the fix is the link, not firmware. New
bt_adv_gate_hint() derives the hint from the gate result (OLDER ->
'Update ESP fw', otherwise 'Check ESP32'); the compiled test layer
extracts the real helper and pins the mapping for every state,
reason, and NULL.
iter-1 review fixes for PR #93:

- Fix-now: start/stop classification seams were pinned only by
  ordering/substring -- an inverted comparison passed the whole
  suite. Add regex-scoped operator pins: start refuses on
  classify != M1_BT_ADV_REPLY_OK, stop confirms on == OK.
- Advisory: scope the gate-before-write seam to the adv send
  (bt_cmd_process is the only direct writer) and pin the idempotent
  bt_session_ensure bring-up as the sole pre-gate console use.
- Advisory: static pins for the reload mapping helpers (stored
  interval outside the table -> the documented 1000 ms default
  entry; preset id clamped to PRESET_NAME).
- Advisory: m1_bt_adv.h now matches the implementation --
  preset_name returns true for CUSTOM ("Custom (SD)"), and
  preset_table_count excludes NAME as well as CUSTOM.
Iter-2 review of PR #93, all four findings fixed:

Blocker [correctness]: the editor's OK switch had no
BT_ADV_ROW_INTERVAL case, so OK on the Interval row -- whose action
bar says Edit -- fell into the default branch and drove the advertise
transport: a spurious gate-refusal dialog on the shipped 1.1.0.0
console, or silent start/stop of advertising on a >=1.2.0.0 console
with the RUN row off-screen. INTERVAL now has an explicit case whose
OK advances the interval one step (the same cycle LEFT/RIGHT
performs, persisted via settings_set_bt_interval_ms + session_dirty
-- a visible edit matching the Edit label), RUN became an explicit
case, and default: is inert (comments + break) so no future row can
inherit the transport.

Fix-now [correctness]: the BACK exit ran the multi-second
stop/resume exchange and then settings_exit_save (which clears
main_q only), leaking a stale status in the 1-deep button queue and
permanently skewing the menu task's 1:1 notification/status pairing.
The BACK branch now resets button_events_q_hdl after the exchange,
before the atomic save. Whole-loop audit: NAME, PRESET-custom, FILE,
RUN, BACK all reset; synchronous branches have no exchange window.

Advisories: m1_bt_adv.h now names bt_adv_exec_start() (not the
nonexistent bt_adv_exec()) and documents that preset_name returns
true with "Custom (SD)" for CUSTOM; s_adv_samsung lists all 28
initializers explicitly (byte image unchanged, still memcmp-pinned).

Test battery rewritten per the binding disposition: explicit case
per BT_ADV_ROW_* id, inert default (comment-stripped), INTERVAL OK =
persisted advance matching the Edit label, start/stop only via
case BT_ADV_ROW_RUN, BACK reset ordering pin, whole-loop reset
count 5; plus Samsung initializer-count and header-contract pins.

Note: a concurrent advisory lane committed bc589ff (polarity +
reload-mapping pins, header contract text) between this lane's
edits and commit; the split is clean, no content duplicated.
Iter-4 review of PR #93, both findings fixed structurally:

Fix-now [tests]: the reload-mapping helpers had zero executable
coverage -- regex pins bound the shape of the loops but not the
documented default VALUE (mutating M1_BT_ADV_INTERVAL_DEFAULT_MS
1000u->250u or the loop bound left the suite green while stored 0
silently remapped). The interval table and both helpers moved from
the HAL-bound m1_bt.c into the pure core: m1_bt_adv_interval_ms
(clamped slot lookup), m1_bt_adv_interval_index (exact match, then
the 1000 ms default slot, total fallback), m1_bt_adv_preset_clamp --
same semantics, same 100/250/500/1000/2000 table, typed contracts in
m1_bt_adv.h. The editor consumes the new API; the private statics
are gone. New compiled battery covers every slot, the default VALUE
(macro + behavior), stored-0/unlisted reload mapping, and clamp
boundaries; the old regex block is deleted. Mutation-verified:
DEFAULT_MS->250u fails 3 named checks; clamp < -> > fails 3; a
default-loop-bound cut fails behaviorally (and the always-false
variant fails the TU's -Werror).

Advisory [correctness]: the action bar now tells the truth per row.
PRESET shows Pick only on CUSTOM (OK opens the picker) and Cycle
otherwise (OK advances the preset one step, persisted like the
INTERVAL advance); INTERVAL -> Cycle; FILE -> Pick; NAME -> Edit;
RUN -> Start/Stop. The hint reads L/R change only on PRESET/INTERVAL
(where LEFT/RIGHT changes something) and OK select elsewhere. The
mapping lives in pure helpers (bt_adv_ok_label/bt_adv_hint) compiled
verbatim into a new harness layer pinning every row/variant; the
static layer pins the matching OK actions and the gui's use of the
helpers. No interval values, preset bytes, gate behavior, or grammar
changed; no build-file change (m1_bt_adv.c was already in
M1_APP_SOURCES).

A concurrent lane's uncommitted test hunks found in the shared
worktree mid-session (an if_body helper, guard-exit pins, and a
broken stop-body regex) were NOT committed: excised verbatim to
.review/pr-93/concurrent-lane-4c.md for that lane to land itself.
@ChrisUFO
ChrisUFO merged commit 685a60c into main Nov 19, 2026
2 checks passed
@ChrisUFO
ChrisUFO deleted the feature/bt-adv-editor branch November 19, 2026 16:49
ChrisUFO added a commit that referenced this pull request Nov 19, 2026
PR-14 remediation (PLAN §18): PR #93's squash merge dropped fix-lane
commit a67b115, so on main all three guard-exit deletions passed the
host suite undetected (M1 gate-refusal return, M2 non-OK-classification
return, M3 unconditional stop latch -- each verified passing pre-pin).

Port a67b115's brace-matched if_body() extractor and checks 3b/4c onto
the evolved suite (now with the compiled editor-mapping harness):

- 3b: the gate-refusal block must contain 'return ERROR;' and never
  'bt_cmd_process('; the non-OK-reply block must contain 'return ERROR;'
  and never set g_bt_adv_active.
- 4c: 'stopped = 1U' appears exactly once, only inside the brace-matched
  classify == M1_BT_ADV_REPLY_OK condition of bt_adv_exec_stop, with no
  '||' bypass.

Mutation verification: baseline 92/92 green; M1/M2/M3 applied in
isolation each fail the suite (1 FAIL each); source reverted clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(bt): implement Bluetooth Config (advertisement payload editor)

1 participant