The bring-up always printed "joined but no IP after DHCP wait" when no
address came, even when the ESP said the join itself failed (e.g. result=1
err=201: network not found). Print by join result, with a readable name
for the common WiFi reason codes. Initialise the result buffer so a short
reply can't print garbage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sam_mfc.c was empty and CMD_HF_SAM_MFC was a no-op. Implement the relay
the way Seader's plugin_hf_mfc_transmit does it. The SAM runs Crypto1
itself and tags each nfcSend with a format:
- 00 C0 00: plain bytes, CRC already included, parity generated
- 00 00 40 / 24 / 44: air order bit stream carrying the SAM's own parity
Answers to the latter go back in the same bit form, len + len / 8 + 1
bytes like Seader. Unlike Seader, every byte gets its real parity bit;
Seader leaves bytes 8 and on at zero. A silent card is reported to the
SAM as rfStatus 00 20, an unknown format as 00 04, Seader's codes, and
the conversation continues.
Card detected follows Seader for MIFARE Classic: protocol, CSN and SAK,
no ATQA. The card is selected without RATS.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Seader keeps the SIO it sees on the air while the SAM reads a card, which
is what lets it write an iCLASS SR downgrade. Do the same:
- iCLASS: READ / READ4 answers from block 6 on are kept; the SIO is the
lowest captured block holding a SEQUENCE whose DER length is covered by
contiguous captured blocks (so a legacy block 7 that happens to start
with 0x30 is not taken for it).
- DESFire: the ReadData of file 0x0F Seader keys on, plus 91 AF
continuations (Seader only keeps the first frame).
A new request flag (bit 7 for CMD_HF_SAM_PICOPASS, bit 2 for
CMD_HF_SAM_SEOS) asks for a sam_ext_reply_hdr_t ahead of the SAM
response. It is only sent for a plain PACS request, so -d, --info and
--break replies are unchanged. The capture lives in .bss and the reply
is built in BigBuf to keep the RDV4 stack untouched.
Also from Seader: a DESFire EV2 answers the Seos select with a 6F 22 85 20
FCI. Hide it from the SAM as 6A 82 and add Le to the DESFire select.
sam_set_card_detected_seos() moves to sam_common.c as
sam_set_card_detected_iso14a() so the MIFARE Classic path can share it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DemodPCF7931 called DoAcquisition with sample_size 0 and no trigger, so
every capture filled all of BigBuf and only the button could stop it:
~1s on RDV4 (~32 KB), ~13s on PM5 (~405 KB). The decoder then stored
every whole block into an 8-entry stack array and copied them into
ReadPCF7931's 4-entry buffer, both unbounded - a PM5 capture holds ~190.
Capture 4.5 blocks (~0.3s on every platform), decode only the samples
taken and stop storing at the 4 blocks the caller has room for.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The retry check estimated the next attempt from the longest one so far.
That does not bound it:
- get_pulse_length() waits up to 4 bit periods
- one find_double_listen_window() can take about 3.2 s with no signal
- a login + read attempt can take over 6 s
- setup before tstart was not counted
A slow attempt after fast failures could end after the client gave up,
leaving the late reply queued for the next command.
read and info now set a deadline after setup, 1 s before the client
timeout. The listen window, ACK and word decode loops stop at the
deadline, as do the retries. With no deadline set (write, brute, sim,
...) they behave as before. The client waits 5 s for read, as it
already did for info / dump.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Next attempt must fit in 2.5 s, judged by the longest attempt so far.
Client waits 5 s for info/dump.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Some COTAG readers produce two ON(x),OFF(y),ON(z) activations in a row, with
a very short gap in between, but they actually listen for the card response
only after the second activation.
Real COTAG tags respond to both activations, but correctly
detect a field drop after the first ON(z) and reset.
The proxmark COTAG sim code was detecting a field drop, but due to various
delays (unnecessary settle, possible printouts) in such cases then missed
the second activation.
Fix the problematic delays. Also, optimize the activation
detection by carrying the adaptive threshold across calls.
- Implemented passive mode for COTAG sim:
- load modulation with an fc/2 subcarrier locked to the reader carrier.
- This mode is now a default as it has several advantages:
- phase coherent response,
- can detect reader field drop mid frame "transmission" and restart
immediately -- important with some readers that may drop field
early and send reactivation shortly afterwards expecting the
tag to respond there as well.
- "active tx mode" is now via CLI toggle --active: it may give better range,
but may not work with all readers.
- Improved COTAG activation sequence detection for a wider range of COTAG
readers that may vary slightly in activation sequence timings (thresholds
for the rise-to-rise mode).
Per review, drop `lf em 4x50 config`, lf_em4x50_tune.lua, the debug
capture and the doc/commands.* changes. Reader timings go back to the
upstream constants; only the RM delay is new (132 cycles, centre of
the 104-164 range that worked).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every bidirectional EM4x50 command (rdbl, info, dump, lf search) failed
on a PM3 Easy with a 500 uH antenna, while `lf em 4x50 reader` worked.
A raw ADC capture of the exchange showed RM being sent into the tag data
right after the double listen window: find_em4x50_tag() consumes the
first window, the second one is then taken as the first, and
invalid_bit() cannot reject data because its single 3/4-bit sample of
the AC-coupled, saturating signal always sits between g_Low and g_High.
- detect the second listen window by the absence of a rising edge over
its 128-cycle low phase (Manchester data has one per bit)
- `lf em 4x50 config` (CMD_LF_EM4X50_CONFIG): threshold, pulse
tolerance, "0" bit gap start/end and RM delay, changeable at runtime
- defaults moved to the centres of the working ranges measured with the
new lf_em4x50_tune.lua sweep: tol 10 (5-15), gap end 38 (28-50),
rm 132 (104-164); the old gap end 32 was 4 cycles from failing
- rdbl/info retry the login + selective read for up to 1 s
- at debug level extended the whole exchange is captured into BigBuf,
fetch it with `data samples`
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SPI1 is full-duplex with no RX FIFO. Every byte cep_spi_write_sync()
clocks out on MISO also shifts a byte in on MOSI that nothing reads,
and AT32F435/437 RM ch 13.2.9 says the first such byte freezes in
SPI_DT until read - not "newest overwrites oldest" as assumed before.
A frozen byte then gets misread by cep_spi_data_available() as part of
the next frame's length header, forcing a resync. Clear ROERR once
after the write (before the read path can touch it) and once at the
top of the read path (for freezes from other main-loop gaps).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Replace the artificial 68-pair limit with a 2900 ms inter-attempt
budget.
A completed-pair count does not limit failed RF/authentication retries
and unnecessarily restricts fast PM5 collection.
Keep natural buffer capacity, whole-pair packing, client cancellation,
watchdog handling and the existing 3000 ms client response waits.
A blocking attempt can overshoot; persistent errors may yield an empty
nonce reply.
Add actual-handler regression coverage for PM5, RDV4 and GENERIC.
Co-Authored-By: OpenAI coding assistant <noreply@openai.com>
Signed-off-by: nip <182409448+nip-was-here@users.noreply.github.com>
Validate byte length, unfinished bits, collisions and parity-buffer
length before accepting an encrypted nested nonce. Capture decoder
metadata before CHK_TIMEOUT changes it and retry incomplete responses.
Remove the PM5-only 500 us nested-authentication delay and its override.
Preserve other RF timing, the pair cap, cancellation and watchdog calls.
Add native regression coverage without target-key filtering.
Co-Authored-By: OpenAI coding assistant <noreply@openai.com>
Signed-off-by: nip <182409448+nip-was-here@users.noreply.github.com>
Add an opt-in simulator probe that checks a reader's AES authentication continuation against a supplied candidate and stops before the final card response. Expose the result through the firmware protocol and etest bench command, and document the evidence and handshake scope.
Co-Authored-By: OpenAI Codex <noreply@openai.com>
New CLI command `lf cotag sim` with COTAG tag simulation implementation.
Detects COTAG reader activation sequence and emulates a COTAG tag.
Signed-off-by: andrej@towelbyte.net
For the Flipper Zero FAP's status page: hw status/CMD_STATUS replies
entirely via free-text Dbprintf packets the FAP's frame layer discards,
with nothing structured on the terminating ack. CMD_CEP_STATUS follows
the CMD_CAPABILITIES precedent instead - one binary cep_status_t reply
covering CEP handshake state, BWM battery telemetry, and a firmware
version string.
Always replies PM3_SUCCESS; fields for a feature this build lacks
(no WITH_CEP, no WITH_BWM_STATUS) read as zero rather than failing the
command, so any client can call it unconditionally. cep_attached isn't
included yet - its getter (cep_is_attached()) only exists on the
not-yet-merged WFI-skip responsiveness branch (#3687); can be appended
later following capabilities_t's own append-only convention.
Stacked on the pm5-bwm-battery-telemetry branch (CMD_PM5_BWM_GET_BATTERY),
which this command's battery field reuses via bwm_read_battery_info().
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The Flipper master only clocks the bus in bursts roughly every ~120ms
(its own idle poll cadence). CEP_SPI_BYTE_TIMEOUT (~3-10ms real time)
is ~20x shorter than that gap, so cep_spi_write_sync()'s first reply
byte - the one racing against the master's next poll - was giving up
long before the master actually showed up. Measured CEP reply success
at ~22% before this fix, ~100% after, across repeated LA-captured test
runs.
Fix: a separate, ~20x longer timeout (CEP_SPI_HEADER_BYTE_TIMEOUT) used
only for the first two length-header bytes of a reply - the ones that
can land in the gap. Every byte after that stays on the short timeout,
since once the master starts clocking it stays mid-CS and keeps going.
Also makes cep_spi_data_available() call cep_spi_resync() on its two
existing desync-evidence paths (sync-preamble discard overflow, an
implausible length header) instead of just returning false - those are
exactly the AT32 errata ES0003 corruption cep_spi_resync() already
exists to recover from; silently returning false left SPI1 in that bad
state until a later CRC/length check happened to catch it.
Stacked on fix-cep-spi-reliability (#3686, open) - this builds directly
on cep_spi_resync()/cep_spi_wait_tdbe()'s bounded-wait rewrite from that
PR and can't be tested standalone without it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
bwm_charger.h is an armsrc-only header included after pm3_cmd.h in
appmain.c, so a struct embedding bwm_battery_info_t by value (e.g. a
future PM5 status command) couldn't see the type at the point it's
needed. bwm_ble_status_t and bwm_autooff_status_t already live in
pm3_cmd.h for the same reason - this just brings
bwm_battery_info_t in line with them. bwm_charger.c/.h keep their
function declarations unchanged; only the struct's home moves.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
hw status's battery/BWM section (bwm_print_battery_status()) only ever
formats its numbers into free-text Dbprintf lines, unusable by any
embedded/non-terminal client. Add a new command that returns the same
SoC/voltage/current/capacity/temp/health/fault numbers as one small
packed struct via reply_ng().
Refactor the shared reads into bwm_read_battery_info() so hw status
and the new command read the same values and can't drift apart -
hw status keeps all its existing charger-detail lines (MainCtl, input
limit, VIN_DPM, charge voltage/enable) unchanged, sourced from its own
reads as before; only the fuel-gauge numbers and the two small
charger-status reads the new struct needs are now shared.
Motivated by wanting a Flipper Zero FAP battery-status test screen
(separate app repo), but this command is generic and usable by any
client, not CEP-specific.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Flipper link can't interrupt a running reader loop
Problem: triggering the Flipper FAP's built-in ReadHitag2 demo command
turns the RF field on and it stays on even after backing out of the
app - only an unrelated USB command clears it. data_available()
(armsrc/util.c) is the standard idiom LF/HF reader loops use to notice
an incoming CMD_BREAK_LOOP, but it only polled USB/BWM/FPC. CEP's own
transport PR never wired it in, so a Flipper-sent break is invisible
to any loop that was already running.
Fix: add cep_spi_rx_pending() to armsrc/pm5_cep.c/.h - a genuinely
non-blocking single SPI1 RDBF flag check, not a reuse of the existing
(bounded-wait) cep_spi_data_available(), since this gets called every
iteration of every reader loop in the codebase and needs to cost
nothing when idle. Wire it into data_available()/data_available_fast()
alongside the existing BWM/FPC branches, additive since CEP and BWM
can coexist.
Hardware-confirmed: field now drops promptly every cycle instead of
sticking on, across repeated ReadHitag2 attach/attempt/cancel cycles.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Problem
pm5_power_idle()'s WFI sleep adds ~40-50ms of latency before the main
loop notices a fresh byte on CEP's SPI1/USART1. At idle this is the
whole point of WFI - but it's also what made the original attach
handshake miss bytes (GH #3667): cep_attach_poll() runs every 50ms, and
WFI's own latency on top of that was enough to lose bytes of the
Flipper's one-shot handshake string often enough to require a physical
cable replug to recover.
Change
armsrc/appmain.c: skip pm5_power_idle() entirely once cep_is_attached()
is true, so the main loop polls CEP as fast as the hardware allows for
as long as a Flipper is physically present.
armsrc/pm5_cep.c/.h: new cep_is_attached(), true as soon as the CC
controller reports a physical attach - independent of whether the
handshake/SPI transport is actually up yet, so the loop stops sleeping
before the handshake even starts, not after. Paired with a
CEP_ACTIVITY_TIMEOUT_MS (3000ms) idle-detach: the FAP quitting doesn't
touch the CC controller's attach bit (the cable stays connected), so
losing its normal 20-120ms SPI poll cadence for this long is what
actually means it's gone - at that point cep_is_attached() still
reflects the physical attach correctly, but cep_is_active() (and
therefore this PR's WFI-skip, which gates on attachment rather than a
completed handshake) only backs off once the FAP itself has clearly quit
rather than just being between polls.
Built on top of the AT32 SPI1 errata fix (bounded waits + resync) from
the companion CEP-reliability PR - running the main loop flat-out
against an unbounded wait would have just hit that hang faster, which is
why this shipped after rather than alongside it.
Behaviour change
PM5 no longer downclocks to WFI between main-loop iterations while a
Flipper is attached over CEP (idle power draw increases for the duration
of the attach; unaffected when no Flipper is present, and unaffected on
RDV4/non-CEP builds).
Testing
- make clean && make PLATFORM=PM5 PLATFORM_EXTRAS=BWM and
make clean && make PLATFORM=PM3RDV4 - both zero warnings.
- Hardware: this flag was active throughout all of the companion CEP-
reliability PR's hardware testing (60s/110s/240s captures, 18x
`hw status`, 5x attach/detach + `hf search` cycles against a real
card) - all passed with WFI-skip engaged the whole time. Additionally
reflashed this exact branch standalone and reconfirmed a live
attach/detach cycle completes cleanly.
- Not tested: clang toolchain (firmware-only diff); idle power draw was
not independently measured (no direct ammeter in this session's
bench setup, only observed BWM telemetry prior to this change).
Checklist
- [x] Proper style of own code, no unrelated reformatting included
- [x] Builds warning-free with gcc (PM5 and RDV4)
- [ ] clang not tried (firmware-only diff)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Problem
With PR #3672/#3674 landed, CEP handshakes reliably but the SPI transport
hangs PM5 hard (needs a physical reset, no watchdog on this platform)
after some number of attach/reconnect cycles - sometimes the first
cycle, sometimes dozens of pings in. Logic-analyzer capture of a hang in
progress showed a ~1.2s burst of rapid CS-gated retries, and in one
capture, three periodic transactions after that burst got progressively
slower (2.1ms -> 3.9ms -> 3.2ms -> 5.2ms) instead of recovering.
Root causes (two, compounding)
1. cep_spi_write_sync() had seven bare `while (flag == RESET);` spins
waiting on SPI1's TDBE/BF flags, with no timeout. PM5 is the SPI
slave - TDBE only clears when the Flipper is actively clocking, on
its own ~20-120ms schedule, completely async to when PM5's reply is
ready. Queue a reply between two master polls and the wait never
returns - full main-loop death.
2. Artery's own errata sheet for the AT32F435/437 (ES0003) documents
that in SPI slave hardware-CS mode, the internal clock sync is not
guaranteed to reset on every CS falling edge - a bad sync can persist
across transactions with no self-correction. This is PM5's exact CEP
configuration (SPI_CS_HARDWARE_MODE, slave mode).
Change
armsrc/pm5_cep.c:
- cep_spi_write_sync() rewritten around a bounded cep_spi_wait_tdbe()
helper (same spin-iteration-count pattern already used for reads) -
returns PM3_EIO on timeout instead of hanging.
- New cep_spi_resync(): hardware-resets SPI1 via crm_periph_reset()
(a register re-init alone doesn't clear the errata's bad internal
state) and brings it back up. This is Artery's own documented recovery
for ES0003 ("reset SPI and restart communication"), triggered by our
existing NG-frame CRC/length checks instead of the SPI peripheral's
hardware CRC feature.
- cep_do_handshake()'s SPI-stall recovery path was itself unbounded
(retried forever as long as the CC controller reported "still
attached") and missing the StartTicks()/I2C_init(true) guard every
other I2C call site in this file has (same bug class as #3672) - now
bounded (CEP_HANDSHAKE_REPLY_MAX_RETRIES) with the guard added.
- cep_spi_data_available() now discards the Flipper's 0x55 idle-poll
filler bytes before reading the real length header, instead of ever
interpreting one as (part of) a frame length.
armsrc/cmd.c: wire cep_spi_resync() into every CEP-reachable error exit
in receive_ng_internal() (short/overflow/CRC-mismatch reads) and both
reply_old()/reply_ng_internal()'s write-failure paths, so any detected
corruption resets SPI1 before the next transaction rather than letting a
bad sync persist. Add a WITH_CEP-gated inline stub for cep_spi_resync()
so receive_ng_internal()'s call sites don't need per-site #ifdef guards
on non-CEP platforms.
Behaviour change
None for USB/FPC/BWM. CEP: a corrupted or stalled SPI1 transaction now
self-heals (one dropped reply, then normal operation) instead of
wedging the device.
Testing
- make clean && make PLATFORM=PM5 PLATFORM_EXTRAS=BWM and
make clean && make PLATFORM=PM3RDV4 - both zero warnings.
- Hardware: flashed to a real PM5 paired with a real Flipper Zero FAP.
- 60s continuous-connection capture with zero USB activity (isolates
CEP from any client-side interaction): clean, no anomalies.
- 110s capture with 18 real `hw status` calls interspersed: all 18
succeeded, CEP stayed attached throughout.
- 5 full attach/detach cycles with `hf search` against a real NTAG213
card before/during/after each attach (240s, logic-analyzer capture
throughout): all 15 reads returned the identical UID regardless of
CEP state, zero hangs, final liveness check succeeded with no reset
needed.
- Not tested: clang toolchain (firmware-only diff).
Checklist
- [x] Proper style of own code, no unrelated reformatting included
- [x] Builds warning-free with gcc (PM5 and RDV4)
- [ ] clang not tried (firmware-only diff)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Problem:
On PM5 (AT32F435, 288 MHz), `hf mf hardnested` / `hf mf autopwn` consistently
fail on genuine hardened MFC EV1: repeated AcquireEncryptedNonces Auth1/Auth2
errors, the attack never reduces the keyspace (No match for the First_Byte_Sum),
and the client intermittently loses the device (No response from Proxmark3).
Root cause - two PM5-specific issues in MifareAcquireEncryptedNonces():
- The AUTH_NESTED read is issued so soon after the first auth completes that on
the fast AT32 the encrypted-nonce reception is intermittently corrupted
(~0.2%/nonce). It is invisible on other frames (BCC/CRC-checked and retried)
but fatal to hardnested, whose bit-flip elimination is zero-tolerance - one
bad nonce can strike the true key from the candidate set. `--slow` does not
help: its delay is before the first auth (select->auth1), not in the
auth1->nested gap where the corruption occurs.
- MFC_MAX_NONCE_PAIRS is derived from PM3_CMD_DATA_SIZE: ~450 pairs on PM5
(4064-byte buffer) vs ~68 elsewhere (624). A full ~450-pair PM5 round can
outrun the client's 3 s reply wait and drop the link.
Change:
- Add a 500 us settle delay before the AUTH_NESTED read, gated to `#if defined(PM5)`.
- Cap the per-round batch to MFC_ACQ_ROUND_MAX_PAIRS (68) via MIN() - a no-op on
every platform whose natural max is already <= 68.
Behaviour change:
- PM5 hf mf hardnested / autopwn now succeed on hardened MFC EV1. PM5 nonce
acquisition is ~500 us/nonce slower and replies in smaller (68-pair) rounds.
- No behaviour change on any non-PM5 platform (delay compiled out; cap is a
MIN no-op).
Testing:
- make clean && make PLATFORM=PM5, and make clean && make PLATFORM=PM3RDV4:
both warning-free.
- On hardware (PM5): full `hf mf autopwn` recovers all 36 keys of a hardened
MFC EV1 in ~98 s (4 sectors via hardnested, the rest cascaded) and dumps the
card; baseline firmware recovers none.
- Not tested here: clang build, CMake/experimental_lib client variants
(firmware-only change, no client code touched), Windows/macOS. RDV4 not
exercised on hardware - it is unaffected and byte-identical after this change.
Fixes#3595, #3664
receive_ng_internal() zeroed rx->data (up to PM3_CMD_DATA_SIZE bytes)
between the preamble read and the payload read. CEP's SPI1 receiver has
no FIFO (single-byte holding register), so that stall lost bytes on every
frame - confirmed via logic analyzer (wire content byte-perfect) plus
Dbprintf instrumentation showing the payload read consistently short by
half. Reordered so preamble/payload/postamble/CRC are all read back-to-back
before any memset/memcpy happens. USB/FPC/BWM are unaffected: same total
work, just resequenced.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
cep_attach_poll() (and cep_init()) call I2C_BufferReadRaw()/I2C_init(true),
which spin on the shared ticks timer via WaitUS()/WaitMS(). That timer is
routinely stopped with StopTicks() by LF/HF protocol code once it's done
with precision timing (em4x50.c, legicrf.c, hitag_common.c, lfsampling.c,
etc). cep_attach_poll() runs unconditionally every 50ms in the main loop
with no idea whether the timer is currently running - if its poll lands in
a window where something just called StopTicks(), WaitTicks()'s
`while (GetTicks() < target)` spins forever on a frozen counter, hanging
the entire main loop irrecoverably. `hf search` cycles through many such
probes, giving this poll many chances to land in that window, matching the
reported "hf search hangs the PM5, needs a battery pull" regression - and
since the poll runs regardless of Flipper attachment, merely compiling in
WITH_CEP was enough to trigger it.
bwm_lowbatt_poll() (armsrc/bwm_charger.c) is the same shape of periodic
main-loop I2C poller and already guards against exactly this by calling
StartTicks(); I2C_init(true); itself immediately before every I2C access.
Mirror that convention in cep_attach_poll() and cep_init().
Re-enables WITH_CEP as the PM5 default (reverts f88880fc6's temporary
disable) now that the underlying bug is fixed. SKIP_CEP=1 remains available
for anyone who wants to opt out at build time regardless.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Pass the requested system code to firmware selection so default and system-specific reader modes share one polling path. Keep the RF field active across retries for the system-specific mode.
Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
Wire up the previously-dead Flipper Zero handshake/SPI code from
at32_unit_test.c into a real WITH_CEP platform extra, independent of
BWM (new g_reply_via_cep flag, not reusing BWM's g_reply_via_fpc, so
both transports can run concurrently).
Fixes a real reconnect bug found during hardware bring-up: the
handshake listener was gated on a CC-controller attach edge that
didn't reliably fire on every FAP relaunch, requiring a physical
cable replug to reconnect. Now watches for a fresh incoming byte any
time the link reports attached, with a bounded receive timeout so a
stray byte can never hang the main loop.
RF/FPGA-dependent functionality (hf/lf reads) is out of scope here -
tracked separately. Closes#3667.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The module ships with BLE open: anyone in range can connect and run
commands, and there was no way to turn the radio off or to require
pairing from the PM5, although the module already implements bonding
with a static passkey (LE Secure Connections + MITM, SPP characteristic
encrypted) behind commands nothing exposed.
New CMD_PM5_BWM_BLE (0x0183): one action byte, then a full status
snapshot back (bwm_ble_status_t: switch, state, bonding, passkey, TX
power, address, name, bonded devices). Client menu `hw bwm ble`:
status everything above, with a warning while open
on | off persisted radio switch (needs the companion
Proxmark5_BWM_esp32 PR; off =
nothing can connect, USB/WiFi only)
pairing on|off [-k] require the 6-digit passkey, set the passkey; a
change of on/off restarts the stack (drops a
connected client), the factory key 123456 is
flagged
forget -i N | --all remove bonded devices
txpower -a/-c dBm advertising / connection power, -24..18 and 20
The firmware replies before restarting the stack so the reply survives
when the command itself arrived over BLE. Fields a module without the
switch cannot answer read 0xFF and print as unknown. A module that does
not answer at all ends the status snapshot after its first query instead
of running into the client's timeout.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A forward frame on the BWM link is anywhere from ~30 bytes to ~2.1 KB (an
NG reply at PM3_FPC_MAX_DATA), so a 16-frame ack window allowed ~33 KB
in flight while the module held un-acked frames in a 4 KB UART ring:
any radio stall of ~45 ms at 921600 baud overflowed it and the module
dropped PM3 bytes. A frame cap tight enough for big frames stalled
uploads, where the module defers small acks behind large incoming
chunks (the old comment on BWM_FC_WINDOW).
Count bytes instead: a FIFO of un-acked frame lengths (the module acks
in order) with budget BWM_FC_BYTES = BWM_ESP_UART_RX_BUF (12288, the
module's ring in the companion Proxmark5_BWM_esp32 PR) minus 1 KB slack,
and a 64-frame FIFO cap for tiny frames. Change the ring size in both
places; the armsrc -pedantic C99 build rejects a static assert tying
them.
The ack timeout no longer forgets the whole window. That made the gate
open loop for the rest of the command: the acks of forgotten frames
released younger ones early, so after the first eaten ack (bwm_cmd()
drains the ring, #3648) the budget protected nothing. Now it forgets
just enough of the oldest frames to send this one: a lost ack costs one
wait and heals, and a stalled radio gets one frame per timeout on top of
a full ring instead of a window. The wait is 200 ms instead of 50: a
full window that stays full is the module stuck on the radio (a phone
scanning stalls BLE for a few hundred ms), and every timeout leaks a
frame into its ring. A CMD_ERROR broadcast naming SEND_FORWARD_DATA
releases the slot like the ack (older module firmware answers that way
when a WiFi forwarding type is configured and no channel takes the
frame). hw status at debug level prints the window counters.
Measured over BLE with the companion module firmware, which acks a
frame as it leaves its ring: 86 KB/s honest against 88 KB/s open loop,
and a 20 s run with the phone scanning meanwhile finishes clean.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The USB-unplug power-off left two ways to drain the battery: a PM5
woken by the button and forgotten, and one left idle after the phone
disconnected.
Idle trigger (opt-in, PM5_AUTOOFF_IDLE_MS 0 by default so out of the box
only the unplug trigger exists, as before): on battery the board powers
off after the idle timeout with no interaction and no wireless client.
Interaction is a received command over any transport, any button press,
or a client connecting or leaving; a standalone mode or a long-running
command holds the main loop, so neither can be cut short. The BWM
reports its clients with the LINK_STATE broadcast (8092, companion
Proxmark5_BWM_esp32 PR) which bwm_forward.c tracks; at boot the BLE
half is seeded with a status query since the module only reports
changes. When the timer is due but a client is still tracked, the module
is asked for its BLE state (at most every 10 s), so a lost "client left"
broadcast cannot pin the board on. And right before going off the module
is asked once more: older module firmware never sends the broadcast and
a "connected" one can get lost, and neither may power the board off
under a silent BLE client. No answer means off.
--unplug off: the unplug trigger always won, so "survive the unplug, go
off after N idle seconds" was not reachable. It is its own setting
(default on = unchanged). With it off an unplug only restarts the idle
clock - from the unplug, not from the last command, or a board that sat
idle on USB for an hour would still die with the cable. Unplug detection
is edge-based (VUSB present at the previous poll, absent at this one)
instead of "absent and seen since boot", which would fire on every poll
after a tolerated unplug. VUSB is followed while the feature is switched
off too, so switching it on again on battery is not taken for an unplug.
Stored on the BWM: runtime-only settings reset at every boot, which is
exactly when the idle trigger matters. The PM5 has no settings store, so
the switch, the idle timeout and the unplug switch live in the module's
host value slots (APP_CMD_SET/GET_SYS_HOST_VALUE 1021/1022, companion
PR; slot 0 switch, 1 idle seconds, 2 unplug), loaded at the first
auto-off poll and saved by CMD_PM5_BWM_AUTOOFF with 1 s per write, so a
silent or older module still leaves the reply inside the client's 5 s
wait. Without a module, or with an older one, the defaults apply and the
status says "not stored".
hw bwm autooff [on|off] [--idle <sec>] [--unplug <on|off>]; no argument
shows the state, one fact per line: switch, idle timeout, unplug
power-off, stored on module, USB power, USB seen since boot, unplug
trigger armed, tracked client, the module's BLE state, idle time.
Payload [action][enabled][idle_s u32][unplug, optional] with keep
sentinels; both actions are non-zero so an old firmware, which reads
byte 0 as the enable flag, can only be left enabled. hw status prints
the module's live BLE state and the auto power-off setting; at debug
level also the tracked client, which should agree with the live state.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
New `hw bwm wifipower [off|none|min|max]`. `off` turns the BWM's WiFi
fully off (BLE-only, persisted; the same path as `hw bwm wifi stop`,
and the module's default state). The other three set the ESP's persisted
WiFi modem power-save type (CMD_PM5_BWM_WIFI_PS 0x0182, module commands
2052/2053, esp_wifi_set_ps()) used while WiFi is up: min (the ESP-IDF
default, the modem sleeps between DTIM beacons), max (sleeps for the
whole listen interval, lowest current, slower to react), none (modem
always on, lowest latency). With no argument it reports whether WiFi is
up at all and the stored type. Independent of `hw bwm powersave`.
The link helper's "cmd failed" diagnostic is now printed only at debug
level: a status query while WiFi is off fails by design and was
cluttering every call.
Verified on hardware: default reads min with WiFi off; none, max and
min each set and read back; off tears WiFi down; an unknown value is
rejected; max survives a module reboot. Not measured with WiFi
associated.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
New `hw bwm powersave [on|off]` (CMD_PM5_BWM_POWERSAVE 0x0181) shows or
sets the ESP's persisted power-save switch (companion Proxmark5_BWM_esp32
PR: DFS, light sleep and slow advertising after a 30 s fast phase, or
the stock always-on behaviour), so the two can be A/B measured and the
saving turned off when chasing a link problem. `hw status` prints the
state next to the BWM firmware version.
Both module queries in `hw status` are time-bounded (version 2 x 800 ms,
power save 300 ms): a module that is silent, or a firmware without the
command, cannot push the report past the client's timeout.
Verified on hardware: state read/set/persist across an ESP reboot,
`hw status` after 4, 15 and 40 s idle in power-save mode and after 6 s
idle with it off.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Port the "reduce idle power" feature from the Fantasi firmware
(soeinova/Fantasi @ 9671309, plus its later ACC-SOF fix) to the PM5
(AT32F435) target.
Problem
-------
The PM5 firmware ran the ARM core at 288 MHz with a 1.3 V LDO and a
main loop that busy-polled at full speed even when the device was idle.
The 288 MHz PLL and the 1.3 V LDO dominate idle draw, and the busy loop
adds to it. Nothing scaled back when there was no work.
Change
------
New armsrc/pm5_power.c drives a refcounted clock/voltage governor:
- Idle (nothing pending, boost count 0, boot grace elapsed, FPGA off):
take SCLK off the PLL onto HICK-48, power the PLL down, drop the LDO
to 1.1 V, park the FPGA 24 MHz clock (PA8 low), and halt the core in
WFI until the next IRQ or the 1 ms SysTick wake.
- Any timing-critical work holds a 288 MHz boost: AppMain wraps
PacketReceived (which on the PM5 also covers a standalone mode, since
it is only entered through a command there); the BWM low-batt poll
and the RGB indicator wrap their I2C. Boost is refcounted and
IRQ-guarded.
- USB (OS image) moves to the crystal-less HICK-48 clock, ACC-trimmed
against the SOF, so powering the PLL down never touches USB. The
bootrom keeps the HEXT/PLL USB path (AS_BOOTROM), so DFU flashing is
unchanged.
- bwm_uart_clock_update() re-inits UART4 through the SDK usart_init()
on each clock switch (the divider set at 288 MHz is 6x off at 48 MHz).
- FpgaIsOff() (fpga_core.c, PM5 only) tracks the last conf word so the
governor never downclocks while a reader field / emulation is running.
- Wake preamble on the BWM link: the companion module firmware
(Proxmark5_BWM_esp32) light-sleeps 2 s after the last byte on the link
and its UART wakes on RX edges but loses the bytes that carried them.
bwm_uart_write() therefore leads with four 0x55 bytes and a 10 ms
settle on its first write and after 1 s without a write of its own
(RX is not tracked: the ring can be drained long after the bytes
came in). The module only starts light-sleeping once it has seen a
preamble, so the one sent while it was still booting is repeated
after the boot-time link negotiation. A module firmware without light
sleep drops the preamble as noise.
New `hw powersave on|off` toggles the governor at runtime (default on);
`hw status` reports the idle-clock and WFI-asleep fractions.
Behaviour change
----------------
- PM5 idles at 48 MHz with the PLL off and the CPU halted; it boosts to
288 MHz for commands and BWM housekeeping. Command timing and
throughput are unchanged (intra-command work is always boosted).
- PM5 USB now runs off HICK-48 (ACC-trimmed) instead of the HEXT PLL.
- New command id CMD_PM5_POWERSAVE (0x0180).
Testing
-------
Built warning-free (gcc) for PLATFORM=PM5 (with and without
PLATFORM_EXTRAS=BWM), PM3RDV4 and PM3GENERIC, armsrc and bootrom. Client
built via the default Makefile. Not built with clang or on
Windows/macOS; nothing outside PM5/AT32 guards changes.
Flashed to a PM5 and exercised against a MIFARE Classic 4K card:
hw version/status/ping (4000 & 512 B), hw tune, hf search, hf 14a
info/reader (x12 across idle gaps), hf mf info/chk/rdbl, lf search/read,
hw powersave off/on, held-field (raw -sk) correctly blocks the downclock,
hw reset + re-enumerate. All pass; USB stays up across downclocks. Idle
reaches ~80-95% at 48 MHz and ~90%+ WFI-halted after a few seconds idle.
Measured at the USB port: idle draw 283 mA -> 207 mA with the stock
BWM firmware.
Co-authored-by: Soei Nova <soeinova@proton.me>
Co-authored-by: noproto <noproto@zeroday.engineering>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>