From 133b981512f317c38b836f208e9c39afd75b5f28 Mon Sep 17 00:00:00 2001 From: Niel Nielsen Date: Fri, 2 Oct 2026 13:45:56 +0200 Subject: [PATCH 01/15] Change default TCP server port from 7777 to 18888 Signed-off-by: Niel Nielsen --- client/src/cmdbwm.c | 54 ++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/client/src/cmdbwm.c b/client/src/cmdbwm.c index 04a997b8c..0fc028f7b 100644 --- a/client/src/cmdbwm.c +++ b/client/src/cmdbwm.c @@ -230,14 +230,14 @@ static int CmdBWMWifi(const char *Cmd) { "Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", "hw bwm wifi status --> show connection state + IP\n" "hw bwm wifi stop --> tear down WiFi, back to BLE-only\n" - "hw bwm wifi --ssid Home --pwd secret --> bring up, port 7777\n" + "hw bwm wifi --ssid Home --pwd secret --> bring up, port 18888\n" "hw bwm wifi --ssid Home --pwd secret --port 9000"); void *argtable[] = { arg_param_begin, arg_str0(NULL, "ssid", "", "WiFi SSID to join"), arg_str0(NULL, "pwd", "", "WiFi password (omit for open network)"), - arg_int0(NULL, "port", "", "TCP server listen port (default 7777)"), + arg_int0(NULL, "port", "", "TCP server listen port (default 18888)"), arg_str0(NULL, "hostname", "", "DHCP hostname (default Proxmark5)"), arg_param_end }; @@ -251,7 +251,7 @@ static int CmdBWMWifi(const char *Cmd) { int pwd_len = 0; CLIParamStrToBuf(arg_get_str(ctx, 2), pwd, sizeof(pwd) - 1, &pwd_len); - int port = arg_get_int_def(ctx, 3, 7777); + int port = arg_get_int_def(ctx, 3, 18888); uint8_t host[33] = {0}; int host_len = 0; @@ -328,9 +328,9 @@ static int CmdBwmCharge(const char *Cmd) { "Enable or disable BWM battery charging by clearing/setting the\n" "AW32001E charge-enable bit (CEB, REG01[3]). PM5 only.\n" _RED_("One-shot:") " the charger watchdog reverts this after ~160 s unless\n" - "serviced, so charging may stop on its own. Use to nudge a top-up.", - "hw bwm charge off --> disable charging\n" - "hw bwm charge on --> enable charging"); + "serviced, so charging may stop on its own. Use to nudge a top-up.", + "hw bwm charge off --> disable charging\n" + "hw bwm charge on --> enable charging"); void *argtable[] = { arg_param_begin, arg_param_end @@ -787,12 +787,18 @@ static int bwm_setting_txn(uint16_t cmd, uint8_t action, uint8_t value, bool has static const char *bwm_wifi_state_name(uint8_t state) { switch (state) { - case 0: return "disconnected"; - case 1: return "connecting"; - case 2: return "connected"; - case 3: return "reconnecting"; - case 4: return "connect task stopped"; - default: return "unknown state"; + case 0: + return "disconnected"; + case 1: + return "connecting"; + case 2: + return "connected"; + case 3: + return "reconnecting"; + case 4: + return "connect task stopped"; + default: + return "unknown state"; } } @@ -840,10 +846,14 @@ static int CmdBwmPowerSave(const char *Cmd) { static const char *bwm_wifi_ps_name(uint8_t mode) { switch (mode) { - case BWM_WIFI_PS_NONE: return "none"; - case BWM_WIFI_PS_MIN: return "min"; - case BWM_WIFI_PS_MAX: return "max"; - default: return "?"; + case BWM_WIFI_PS_NONE: + return "none"; + case BWM_WIFI_PS_MIN: + return "min"; + case BWM_WIFI_PS_MAX: + return "max"; + default: + return "?"; } } @@ -912,10 +922,14 @@ static int CmdBwmWifiPower(const char *Cmd) { static const char *ble_state_str(uint8_t state) { switch (state) { - case 0: return "off"; - case 1: return "advertising, no client"; - case 2: return "client connected"; - default: return "unknown"; + case 0: + return "off"; + case 1: + return "advertising, no client"; + case 2: + return "client connected"; + default: + return "unknown"; } } From 7d339ac4dc8c9a5bc2dba792b0ecad8da3d6d16d Mon Sep 17 00:00:00 2001 From: Niel Nielsen Date: Fri, 2 Oct 2026 13:47:45 +0200 Subject: [PATCH 02/15] Update default port from 7777 to 18888 Signed-off-by: Niel Nielsen --- doc/md/PM5_Start_Here/PM5-BWM-USAGE.md | 1689 +++++++++++++++++------- 1 file changed, 1248 insertions(+), 441 deletions(-) diff --git a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md index 793b7952a..0fc028f7b 100644 --- a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md +++ b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md @@ -1,441 +1,1248 @@ -# Proxmark5 BWM — Battery, BLE & WiFi - -The **Battery / Wireless Module (BWM)** adds a battery + charger and an ESP32 that -bridges the Proxmark5 to **BLE** and **WiFi**. Everything below is **PM5-only** and -is compiled in with the BWM platform extra. - -## Contents - -- [Build](#build) -- [1. Battery / BWM control](#1-battery--bwm-control) -- [2. BLE](#2-ble) -- [3. WiFi](#3-wifi) -- [4. Update BWM firmware](#4-update-bwm-firmware) -- [Notes](#notes) - ---- - -## Build - -Build the firmware with the BWM extra — this enables `WITH_BWM_FORWARD` (the -UART4 / `app_com` driver, battery telemetry, and BLE/WiFi forwarding): - -``` -make clean -make PLATFORM=PM5 PLATFORM_EXTRAS=BWM -make client # or your usual client build -``` - -Or set it persistently in `Makefile.platform`: - -``` -PLATFORM=PM5 -PLATFORM_EXTRAS=BWM -``` - -> [!NOTE] -> Without `PLATFORM_EXTRAS=BWM` the firmware builds a plain PM5 with **none** of the -> battery / BLE / WiFi commands below. - ---- - -## 1. Battery / BWM control - -These run over any active connection — USB, BLE, or WiFi. - -### `hw status` — battery + charger telemetry - -``` -[usb] pm3 --> hw status -``` - -The **Battery / BWM** section reports the **AW32001** charger (power path, fault, -charge state, input limit, charge current/voltage/enable) and the **BQ27427** fuel -gauge (state-of-charge %, voltage, current, remaining/full capacity, temperature, -health). - -### `hw bwm setcap` — set fuel-gauge design capacity - -Program the BQ27427 **Design Capacity** for the fitted cell. - -| Argument | Description | -| ------------- | -------------------------------------- | -| `--cap ` | Design capacity in mAh (default `500`) | - -``` -hw bwm setcap # set design capacity to the default 500 mAh -hw bwm setcap --cap 500 # set design capacity to 500 mAh -``` - -> [!WARNING] -> Run this **once** after fitting or replacing the battery. Running it repeatedly -> triggers a gauge config-update and disrupts the Impedance Track learning cycle. - -### `hw bwm charge` — enable/disable charging (one-shot) - -Clears/sets the AW32001E charge-enable bit (`CEB`, `REG01[3]`). - -| Sub-action | Description | -| ---------- | ----------------- | -| `on` | Enable charging | -| `off` | Disable charging | - -``` -hw bwm charge on # enable charging -hw bwm charge off # disable charging -``` - -> [!NOTE] -> **One-shot:** the charger watchdog reverts this after ~160 s unless serviced, so -> charging may stop on its own. Use it to nudge a top-up. - -### `hw bwm vchg` — set charge-voltage limit - -Sets the AW32001E charge-voltage regulation target (`VBAT_REG`, `REG04[7:2]`). -Lowering it below 4.2 V reduces top-of-charge stress and extends cell life. - -| Argument | Description | -| ----------- | ----------------------------------------------------------- | -| `--mv ` | Charge voltage in mV (default `4100`, clamped `3600`..`4200`) | - -``` -hw bwm vchg # set the default 4100 mV target (-> 4.095 V) -hw bwm vchg --mv 4200 # set 4200 mV -``` - -The value snaps to the nearest 15 mV hardware step, and the command reports the -voltage actually applied (e.g. `4100` → `4.095 V`; `4110` would be the next step). - -> [!NOTE] -> The firmware applies the `4100` mV default (4.095 V) at **every boot** — the -> AW32001E's own power-on default is 4.2 V. It is a runtime register write, but -> because the boot config disables the charger watchdog the value then holds until -> the next power cycle (which re-applies it), so you don't need to re-run it per -> charge. - -### `hw bwm autooff` — auto power-off on USB unplug - -Toggles automatic power-off when the PM5 is unplugged from USB. **Default is `on`:** -the board powers down after USB is removed so a BWM-equipped PM5 doesn't silently -drain the battery. Button power-on is unaffected. - -| Sub-action | Description | -| ---------- | ----------------------- | -| `on` | Enable auto power-off | -| `off` | Disable auto power-off | - -``` -hw bwm autooff off # disable auto power-off -hw bwm autooff on # re-enable auto power-off -``` - -> [!NOTE] -> **Runtime only** — resets to `on` at each boot. Disable it for an uninterrupted -> move from USB to standalone / BLE / WiFi use on battery. For regular standalone / -> BLE / WiFi use on battery, one can just turn it on when needed, no need to touch -> that setting. - ---- - -## 2. BLE - -The BWM advertises as: - -| Property | Value | -| --------- | ---------------------------------------------- | -| Name | `Proxmark5` | -| Address | `58:2A:BD:34:F1:82` (LE Public, Espressif OUI) | -| Service | `0xAE86` (16-bit) | -| Data char | `0xAE88` (`WRITE` / `WRITE_NO_RSP` / `NOTIFY`) | -| Security | none (plaintext GATT, no bonding) | - -> [!NOTE] -> `58:2A:BD:34:F1:82` is just an example — each module has its own address. Find -> yours with `btmgmt find`, or use the bridge's name-scan (`-n Proxmark5`), which -> avoids needing the address at all. - -There are three ways to connect: a **native transport** (Linux), a **cross-platform -Python bridge** (Linux / macOS / Windows / WSL / iOS), and a **bridge app** on Android -([2.4](#24-android--termux--ble-bridge-app)). - -### `hw bwm name` — get/set the BLE advertising name - -Reads or changes the name the BWM advertises over BLE. With no argument it prints -the current name; `--set` changes it (1–31 characters). - -| Argument | Description | -| --------------- | ---------------------------------------------------- | -| `--set ` | New BLE name, 1–31 chars; omit to read current name | - -``` -hw bwm name # show the current BLE name -hw bwm name --set MyPM5 # set the BLE name to 'MyPM5' -``` - -The name is stored on the BWM in NVS, so it persists across power cycles. The BWM -applies the advertised name at BLE start-up, so setting a name reboots the BWM to -make it take effect — this briefly drops a BLE or WiFi connection, so reconnect -after a few seconds. Over USB the reboot is not noticeable, since the client stays -connected to the PM5 while only the BWM's ESP restarts. - -> [!NOTE] -> If a device is connected over BLE when you change the name, the running -> advertisement can't change mid-connection; the new name shows up on the next -> scan after the reboot. - -### 2.1 Native BLE transport — Linux only, no bridge - -Uses a raw L2CAP/ATT socket — no `bleak`, no `bluetoothd` daemon dependency. -Needs the Bluetooth dev headers at build time: - -``` -sudo apt install libbluetooth-dev -make client # rebuild so HAVE_BLUEZ is picked up -``` - -Then connect by address: - -``` -./pm3 -p ble:58:2A:BD:34:F1:82 -``` - -On success you'll see e.g. `BLE connected, MTU 512, char handle 0x0014`. - -### 2.2 BLE bridge — cross-platform (`pm5_ble_bridge.py`) - -Requires Python 3 and `bleak` (`pip install bleak`). It bridges the BWM's BLE SPP -to a PTY or a TCP socket that the pm3 client then opens. - -> [!IMPORTANT] -> Run the bridge on the machine that has the **Bluetooth radio**. - -Common options: - -| Option | Description | -| --------------------- | ------------------------------------------------- | -| `-n, --name ` | Advertised name to scan for (default `Proxmark5`) | -| `-a, --address ` | Connect by address instead of scanning by name | -| `--dump` | Hexdump traffic both directions (debug) | -| `-v, --verbose` | Verbose logging | - -**a) PTY** (Linux/macOS) — simplest, one process: - -``` -python3 pm5_ble_bridge.py --pty # default link /tmp/pm5-ble -./pm3 -p /tmp/pm5-ble -``` - -**b) TCP listener** — bridge listens, client connects in: - -``` -python3 pm5_ble_bridge.py --tcp 7777 # or HOST:PORT -./pm3 -p tcp:127.0.0.1:7777 -``` - -**c) Outbound TCP** (`--connect`) — bridge dials **out** to a listener. Pairs with -the client's `--wait` mode ([2.3](#23-client-listen-mode--pm3----wait)) and crosses -the WSL2 NAT boundary: - -``` -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 -``` - -**d) Relay only** (no BLE) — TCP listener ↔ PTY, for chaining: - -``` -python3 pm5_ble_bridge.py --relay --listen 7777 --pty -``` - -> [!NOTE] -> **Windows / WSL:** run the bridge on Windows (where the radio is) with `py`, and -> let only TCP cross into WSL. - -### 2.3 Client listen mode — `pm3 … --wait` - -With a `tcp:` port, `--wait` makes the client **bind / listen** and wait for an -incoming connection instead of dialing out. Start the client first, then point the -bridge at it with `--connect`. This removes the relay/PTY hop. - -``` -# window 1 — client listens (blocks until something connects) -./pm3 -p tcp:127.0.0.1:7777 --wait - -# window 2 — bridge dials in (on the machine with the radio) -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 -``` - -> [!NOTE] -> For a plain **serial** port, `--wait` keeps its original meaning: wait ~20 s for -> the device node to appear. - -### 2.4 Android — Termux + BLE bridge app - -Termux has no Bluetooth access, so a bridge app exposes the BWM's BLE characteristic -as a local TCP port that the client then opens — same idea as -[termux_notes.md](../../termux_notes.md), just BLE instead of classic Bluetooth. -Tested with the paid -[BT/USB/TCP Bridge](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) -app, which lets you pick the GATT characteristic; the free version works too but is -limited to 10 minutes per session (the limit resets after quitting the app). - -1. Build the client in Termux (see [termux_notes.md](../../termux_notes.md)). -2. In the bridge app: - -| Setting | Value | -| ---------------- | ----------------------------------------------------------------- | -| Device A | Start TCP server (default port `54321`) | -| Device B | Connect to BLE device → `Proxmark5` | -| Characteristic | the last one: service `0000ae86-…`, characteristic `0000ae88-…`, for RX+TX | - -3. In Termux, connect over the local port: - -``` -./client/proxmark3 tcp:localhost:54321 -``` - -No pairing is needed (the BWM has no BLE security). The same app also does classic -Bluetooth, so one setup covers a Blueshark-equipped Proxmark3 too. - -> [!NOTE] -> If you would rather not use a bridge app, put the phone in hotspot mode and use -> WiFi instead ([3](#3-wifi-sta--tcp-server)): the client then connects straight to -> the BWM's TCP server, with no app in between. - ---- - -## 3. WiFi (STA + TCP server) - -`hw bwm wifi` joins your WiFi network as a **station** and starts a **TCP server** on -the BWM. You then connect the client over plain TCP. Run `hw bwm wifi` over an -existing link (USB, or an existing BLE connection). Use `hw bwm wifi status` to check an -existing connection without touching the config. - -### 3.1 Bring up WiFi - -``` -hw bwm wifi --ssid [--pwd ] [--port ] [--hostname ] -``` - -| Argument | Description | -| ------------------- | ---------------------------------------- | -| `--ssid ` | WiFi network to join **(required)** | -| `--pwd ` | WiFi password (omit for an open network) | -| `--port ` | TCP server listen port (default `7777`) | -| `--hostname ` | DHCP hostname (default `Proxmark5`) | - -Two sub-actions take no other arguments and are positional (no dashes): -`hw bwm wifi status` and `hw bwm wifi stop` (see 3.3 and 3.4). - -``` -hw bwm wifi --ssid Home --pwd secret -hw bwm wifi --ssid Home --pwd secret --port 9000 --hostname pm5-lab -hw bwm wifi --ssid OpenGuestWiFi # open network -``` - -The join can take ~15 s. On success it prints the assigned IP and the connect -strings: - -``` -[+] BWM on WiFi at 192.168.1.77 -[?] Connect with: pm3 -p tcp:192.168.1.77:7777 -[?] Or by name (router-dependent): pm3 -p tcp:pm5-lab:7777 -``` - -### 3.2 Connect over WiFi - -``` -./pm3 -p tcp:192.168.1.77:7777 -``` - -> [!NOTE] -> Connecting **by hostname** works only if your router registers DHCP client names -> in its local DNS (some need a suffix like `.lan` or `.home`; some -> don't do it at all). There is **no mDNS / `.local`** responder, so the IP is the -> reliable path. - -### 3.3 Check WiFi status — `hw bwm wifi status` - -Queries the BWM's current connection state and IP **without** reconnecting or -changing the WiFi config. Handy to confirm a join actually completed — the -bring-up occasionally reports failure if the DHCP lease lands late, even though -the STA connected a moment later. - -``` -hw bwm wifi status -``` - -``` -[+] BWM WiFi connected, IP 192.168.1.77 -[?] Connect with: pm3 -p tcp:192.168.1.77: -``` - -> [!NOTE] -> "Connected" here means the STA has a DHCP lease (a usable IP). If it reports -> not connected right after a bring-up, wait a few seconds and re-check — the -> lease may still be in flight. - -### 3.4 Stop WiFi — `hw bwm wifi stop` - -Tears down the WiFi station and TCP server and returns the BWM to **BLE-only**. -Run it over an existing link (USB or BLE); it does not need any other arguments. - -``` -hw bwm wifi stop -``` - -> [!NOTE] -> If you issue `hw bwm wifi stop` over the **WiFi** connection itself, that connection -> drops as the TCP server goes away — reconnect over USB or BLE afterwards. - ---- - -## 4. Update BWM firmware — `hw bwm upgrade` - -Reflashes the BWM (ESP32-C2) firmware **over the existing BWM link** — no 5-pin -header, no soldering, no `esptool`. Run it over whatever link you already have -(USB or BLE). It updates a BWM that still responds; it **cannot** recover a fully -bricked one — that still needs the production 5-pin header + `esptool`. - -``` -hw bwm upgrade -f [--delay ] -``` - -| Argument | Description | -| -------------- | ------------------------------------------------------------- | -| `-f`, `--file` | ESP32-C2 firmware image `.bin` **(required)** | -| `--delay ` | Per-chunk delay pacing the slow AT32-ESP UART (default `20`) | - -The client refuses to flash anything that is not an ESP32-C2 app image (it checks -the ESP image magic `0xE9` and `chip_id 0x000C`), so a wrong-chip image can't -brick the module. - -It prints the running version first, uploads the image, then reboots the ESP into -the new image and confirms by reading the version back: - -``` -[=] Current BWM firmware..... v1.2.3 -[=] Uploading 812345 bytes of ESP firmware over the BWM link... -[=] BWM rebooting into the new image (link drops briefly)... -[+] BWM firmware updated: v1.2.3 -> v1.3.0 -``` - -> [!NOTE] -> There is **no resume**: a chunk dropped mid-transfer restarts the whole upload, -> and the client retries automatically (up to 6 attempts). If uploads keep failing -> on the slow link, raise the pacing, e.g. `--delay 40`. - -> [!NOTE] -> The link drops briefly while the ESP reboots into the new image. Over BLE the -> post-reboot version read sometimes can't complete even though the flash -> succeeded — reconnect and run `hw status` to confirm the running version. - ---- - -## Notes - -- Bulk transfers over BLE/WiFi (`lf read`, `mem dump`, trace download) are paced by - the BWM flow control so they don't drop — expect them to be **slower than USB**. -- COTAG / large realtime LF reads use a separate streaming - path and are **not** covered by this flow control. -- All BWM commands are **PM5-only** and require the firmware built with - `PLATFORM_EXTRAS=BWM`. +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// BWM (battery/wireless module) commands +//----------------------------------------------------------------------------- + +#include +#include +#include +#include + +#include "cmdparser.h" // command_t +#include "cliparser.h" +#include "comms.h" +#include "usart_defs.h" +#include "ui.h" +#include "cmdbwm.h" +#include "cmdhw.h" +#include "commonutil.h" +#include "pm3_cmd.h" +#include "cmdflashmem.h" // get_signature.. +#include "fileutils.h" // loadFile_safe +#include "util_posix.h" + +static int CmdBwmAutoOff(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm autooff [on|off] [--idle ] + char verb[16] = {0}; + int consumed = 0; + sscanf(Cmd, "%15s%n", verb, &consumed); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + const char *rest = (on || off) ? Cmd + consumed : Cmd; + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm autooff", + "Show or set automatic power-off (PM5 only). Two triggers:\n" + " - USB was present and the cable is pulled: off at once, so a BWM-equipped\n" + " PM5 doesn't silently drain the battery; --unplug off only restarts the\n" + " idle clock instead;\n" + " - on battery with no command, button press or BLE/WiFi client for --idle\n" + " seconds: off (0 = never, the default).\n" + "Button power-on is unaffected. Stored on the BWM; without a module, defaults.", + "hw bwm autooff --> show the current state\n" + "hw bwm autooff off --> disable both triggers\n" + "hw bwm autooff on --> re-enable\n" + "hw bwm autooff --idle 300 --> also off after 5 min idle on battery\n" + "hw bwm autooff --idle 0 --> USB-unplug trigger only (default)\n" + "hw bwm autooff --unplug off --idle 300 --> survive the unplug, off 5 min idle later"); + void *argtable[] = { + arg_param_begin, + arg_int0("i", "idle", "", "idle timeout on battery in seconds, 0 = never"), + arg_str0("u", "unplug", "", "power off when USB is pulled (default on)"), + arg_param_end + }; + CLIExecWithReturn(ctx, rest, argtable, true); + int idle = arg_get_int_def(ctx, 1, -1); + uint8_t ubuf[8] = {0}; + int ulen = 0; + int ures = CLIParamStrToBuf(arg_get_str(ctx, 2), ubuf, sizeof(ubuf) - 1, &ulen); + CLIParserFree(ctx); + if (ures) { + PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + uint8_t unplug = BWM_AUTOOFF_KEEP_U8; + if (ulen) { + if (strcmp((char *)ubuf, "on") == 0) { + unplug = 1; + } else if (strcmp((char *)ubuf, "off") == 0) { + unplug = 0; + } else { + PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + } + if ((idle < -1) || (idle > (int)BWM_AUTOOFF_IDLE_MAX_S)) { + PrintAndLogEx(WARNING, "idle must be 0 to %lu seconds", (unsigned long)BWM_AUTOOFF_IDLE_MAX_S); + return PM3_EINVARG; + } + + struct { + uint8_t action; + uint8_t enabled; + uint32_t idle_s; + uint8_t unplug; + } PACKED payload = { + .action = (on || off || (idle >= 0) || ulen) ? BWM_AUTOOFF_ACTION_SET : BWM_AUTOOFF_ACTION_GET, + .enabled = on ? 1 : (off ? 0 : BWM_AUTOOFF_KEEP_U8), + .idle_s = (idle >= 0) ? (uint32_t)idle : BWM_AUTOOFF_KEEP_U32, + .unplug = unplug, + }; + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_AUTOOFF, (uint8_t *)&payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); + return PM3_ETIMEOUT; + } + if (resp.status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without auto power-off support"); + return resp.status; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to set auto power-off"); + return resp.status; + } + bool enabled = (resp.length >= 1) && (resp.data.asBytes[0] != 0); + PrintAndLogEx(SUCCESS, "Auto power-off....... %s", enabled ? _GREEN_("on") : _YELLOW_("off")); + if (resp.length < 5) { + // firmware before the idle timeout: it only reports the switch + return PM3_SUCCESS; + } + uint32_t idle_s; + memcpy(&idle_s, &resp.data.asBytes[1], sizeof(idle_s)); + if (idle_s) { + PrintAndLogEx(INFO, "Idle timeout......... " _YELLOW_("%u") " s", idle_s); + } else { + PrintAndLogEx(INFO, "Idle timeout......... off"); + } + if (resp.length >= sizeof(bwm_autooff_status_t)) { + const bwm_autooff_status_t *st = (const bwm_autooff_status_t *)resp.data.asBytes; + const char *live = (st->ble_live == 2) ? "client connected" : (st->ble_live == 1) ? "advertising, no client" : (st->ble_live == 0) ? "off" : "no answer"; + PrintAndLogEx(INFO, "Unplug power-off..... %s", st->unplug ? "on" : _YELLOW_("off") " (an unplug only restarts the idle clock)"); + PrintAndLogEx(INFO, "Stored on module..... %s", st->persisted ? "yes" : _YELLOW_("no")); + PrintAndLogEx(INFO, "USB power............ %s", st->usb ? "present" : "absent"); + PrintAndLogEx(INFO, "USB seen since boot.. %s", st->usb_seen ? "yes" : "no"); + PrintAndLogEx(INFO, "Unplug trigger....... %s", (enabled && st->unplug && st->usb_seen) ? _GREEN_("armed") : "not armed"); + PrintAndLogEx(INFO, "Tracked client....... %s", st->link ? "connected (BLE or WiFi)" : "none"); + PrintAndLogEx(INFO, "Module BLE state..... %s", live); + PrintAndLogEx(INFO, "Idle for............. %u s", st->idle_now_s); + if (st->persisted == 0) { + PrintAndLogEx(HINT, "no module, or one too old to store it: the defaults return at the next boot"); + } + } + return PM3_SUCCESS; +} + +static int CmdBWMWifi(const char *Cmd) { + // Sub-actions that carry no other arguments are positional keywords now: + // hw bwm wifi status (was --status) + // hw bwm wifi stop (was --stop) + // Bringing WiFi up still takes value flags, so it stays the default + // (no-keyword) form: hw bwm wifi --ssid --pwd [--port ] + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + + if (strcmp(verb, "status") == 0) { + uint8_t q[1] = { BWM_WIFI_ACTION_STATUS }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, q, sizeof(q)); + PacketResponseNG r; + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (r.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "could not query BWM WiFi status (BWM present?)"); + return r.status; + } + uint8_t state = (r.length >= 1) ? r.data.asBytes[0] : 0xFF; + uint32_t ip = 0; + if (r.length >= 5) { + ip = r.data.asBytes[1] | (r.data.asBytes[2] << 8) | (r.data.asBytes[3] << 16) | ((uint32_t)r.data.asBytes[4] << 24); + } + switch (state) { + case 0xFF: + PrintAndLogEx(INFO, "BWM WiFi disabled (BLE-only). Bring it up with " _YELLOW_("hw bwm wifi --ssid --pwd ")); + break; + case 2: // connected + if (ip) { + PrintAndLogEx(SUCCESS, "BWM WiFi connected, IP " _YELLOW_("%u.%u.%u.%u"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + } else { + PrintAndLogEx(INFO, "BWM WiFi associated, waiting for a DHCP lease..."); + } + break; + case 1: // connecting + PrintAndLogEx(INFO, "BWM WiFi connecting..."); + break; + case 3: // reconnect wait + PrintAndLogEx(INFO, "BWM WiFi reconnecting..."); + break; + case 4: // task stopped + PrintAndLogEx(INFO, "BWM WiFi connect task stopped"); + break; + case 0: // disconnected + default: + PrintAndLogEx(INFO, "BWM WiFi configured but not connected"); + break; + } + return PM3_SUCCESS; + } + + if (strcmp(verb, "stop") == 0) { + uint8_t off[1] = { BWM_WIFI_ACTION_STOP }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, off, sizeof(off)); + PacketResponseNG r; + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (r.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to disable BWM WiFi"); + return r.status; + } + PrintAndLogEx(SUCCESS, "BWM WiFi disabled (back to BLE-only)"); + return PM3_SUCCESS; + } + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm wifi", + "Bring up the BWM in STA + TCP-server mode: join a WiFi network and\n" + "start a TCP server so the client can connect over WiFi. PM5 only.\n" + "Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", + "hw bwm wifi status --> show connection state + IP\n" + "hw bwm wifi stop --> tear down WiFi, back to BLE-only\n" + "hw bwm wifi --ssid Home --pwd secret --> bring up, port 18888\n" + "hw bwm wifi --ssid Home --pwd secret --port 9000"); + + void *argtable[] = { + arg_param_begin, + arg_str0(NULL, "ssid", "", "WiFi SSID to join"), + arg_str0(NULL, "pwd", "", "WiFi password (omit for open network)"), + arg_int0(NULL, "port", "", "TCP server listen port (default 18888)"), + arg_str0(NULL, "hostname", "", "DHCP hostname (default Proxmark5)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + uint8_t ssid[64] = {0}; + int ssid_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 1), ssid, sizeof(ssid) - 1, &ssid_len); + + uint8_t pwd[64] = {0}; + int pwd_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 2), pwd, sizeof(pwd) - 1, &pwd_len); + + int port = arg_get_int_def(ctx, 3, 18888); + + uint8_t host[33] = {0}; + int host_len = 0; + CLIParamStrToBuf(arg_get_str(ctx, 4), host, sizeof(host) - 1, &host_len); + if (host_len == 0) { + strcpy((char *)host, "Proxmark5"); + host_len = 9; + } + CLIParserFree(ctx); + + if (ssid_len == 0) { + PrintAndLogEx(FAILED, "an SSID is required (or " _YELLOW_("hw bwm wifi stop") " to tear down)"); + return PM3_EINVARG; + } + if (port < 1 || port > 65535) { + PrintAndLogEx(FAILED, "port must be 1..65535"); + return PM3_EINVARG; + } + + // payload: [action:u8][port:u16 LE][ssid\0][pwd\0][hostname\0] + uint8_t data[200] = {0}; + int n = 0; + data[n++] = BWM_WIFI_ACTION_START; + data[n++] = (uint8_t)(port & 0xFF); + data[n++] = (uint8_t)((port >> 8) & 0xFF); + memcpy(&data[n], ssid, ssid_len); + n += ssid_len; + data[n++] = 0; + memcpy(&data[n], pwd, pwd_len); + n += pwd_len; + data[n++] = 0; + memcpy(&data[n], host, host_len); + n += host_len; + data[n++] = 0; + + PrintAndLogEx(INFO, "Bringing up BWM WiFi (SSID \"%s\", port %d)... this can take ~15s", ssid, port); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_WIFI, data, n); + PacketResponseNG resp; + // ARM blocks during join + DHCP wait, so allow a long client timeout + if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &resp, 60000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "BWM WiFi bring-up failed (check SSID/password and signal)"); + PrintAndLogEx(HINT, "If it may have joined after DHCP, check: " _YELLOW_("hw bwm wifi status")); + return resp.status; + } + + uint32_t ip = resp.data.asDwords[0]; + PrintAndLogEx(SUCCESS, "BWM on WiFi at %u.%u.%u.%u", + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); + PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:%d"), + ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF, port); + PrintAndLogEx(HINT, "Or by name (router-dependent): " _YELLOW_("pm3 -p tcp:%s:%d"), host, port); + PrintAndLogEx(HINT, "Or by mDNS (BWM fw with mDNS): " _YELLOW_("pm3 -p tcp:%s.local:%d"), host, port); + return PM3_SUCCESS; +} + +static int CmdBwmCharge(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm charge on | off + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + + if (!on && !off) { + // Not a recognised sub-action: render help (also serves -h / empty), + // or error on a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm charge", + "Enable or disable BWM battery charging by clearing/setting the\n" + "AW32001E charge-enable bit (CEB, REG01[3]). PM5 only.\n" + _RED_("One-shot:") " the charger watchdog reverts this after ~160 s unless\n" + "serviced, so charging may stop on its own. Use to nudge a top-up.", + "hw bwm charge off --> disable charging\n" + "hw bwm charge on --> enable charging"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); + return PM3_EINVARG; + } + + uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) + PrintAndLogEx(INFO, "%s BWM battery charging...", off ? "Disabling" : "Enabling"); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_CHARGE_EN, &payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_CHARGE_EN, &resp, 2500) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "charger did not respond (check BWM present)"); + return resp.status; + } + PrintAndLogEx(SUCCESS, "Charging %s. Verify with " _YELLOW_("hw status") ".", + off ? "disabled" : "enabled"); + if (off == false) { + PrintAndLogEx(HINT, "Reverts on the charger watchdog (~160 s) if not serviced."); + } + return PM3_SUCCESS; +} + +static int CmdBwmVchg(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm vchg", + "Set the BWM charger (AW32001E) charge-voltage regulation target.\n" + "Lowering it below 4.2 V reduces top-of-charge stress and extends cell\n" + "life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is\n" + "a runtime register write (reverts on the charger watchdog / POR); the\n" + "firmware re-applies the " _YELLOW_("4100 mV") " default at every boot. PM5 only.", + "hw bwm vchg --> set charge voltage to default 4100 mV (->4.095 V)\n" + "hw bwm vchg --mv 4200 --> set charge voltage to 4200 mV"); + + void *argtable[] = { + arg_param_begin, + arg_int0(NULL, "mv", "", "charge voltage in mV (default 4100, clamped 3600..4200)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int mv = arg_get_int_def(ctx, 1, 4100); + CLIParserFree(ctx); + + if (mv < 3600 || mv > 4200) { + PrintAndLogEx(WARNING, "charge voltage out of range (3600..4200 mV): %d", mv); + return PM3_EINVARG; + } + + uint8_t payload[2] = { (uint8_t)(mv & 0xFF), (uint8_t)((mv >> 8) & 0xFF) }; + PrintAndLogEx(INFO, "Setting BWM charge voltage to " _YELLOW_("%d mV") "...", mv); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_SET_VCHG, payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_SET_VCHG, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "failed to set charge voltage - check BWM present"); + return resp.status; + } + uint16_t applied = (resp.length >= 2) ? (resp.data.asBytes[0] | (resp.data.asBytes[1] << 8)) : 0; + PrintAndLogEx(SUCCESS, "Charge voltage set to " _YELLOW_("%u.%03u V") " (nearest 15 mV step).", applied / 1000, applied % 1000); + return PM3_SUCCESS; +} + +static int CmdBwmSetCap(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm setcap", + "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell.\n" + "Run ONCE after fitting or replacing the battery. This triggers a gauge\n" + "config-update; do not run it repeatedly, as that disrupts the Impedance\n" + "Track learning cycle. PM5 only.", + "hw bwm setcap --> set design capacity to default 500 mAh\n" + "hw bwm setcap --cap 500 --> set design capacity to 500 mAh"); + + void *argtable[] = { + arg_param_begin, + arg_int0(NULL, "cap", "", "design capacity in mAh (default 500)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int cap = arg_get_int_def(ctx, 1, 500); + CLIParserFree(ctx); + + if (cap <= 0 || cap > 32000) { + PrintAndLogEx(WARNING, "capacity out of range: %d mAh", cap); + return PM3_EINVARG; + } + + uint8_t payload[2] = { (uint8_t)(cap & 0xFF), (uint8_t)((cap >> 8) & 0xFF) }; + PrintAndLogEx(INFO, "Programming BWM gauge design capacity to " _YELLOW_("%d mAh") "...", cap); + PrintAndLogEx(INFO, "Run this " _YELLOW_("once") "; then perform a full charge/discharge learning cycle."); + + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_SET_CAP, payload, sizeof(payload)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_PM5_BWM_SET_CAP, &resp, 5000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "gauge provisioning failed - check BWM present and gauge unsealed"); + return resp.status; + } + PrintAndLogEx(SUCCESS, "Design capacity programmed. `hw status` should now report sane capacity."); + return PM3_SUCCESS; +} + + +static void progressbar(long sent, long total, int style) { + int percent = (int)((double)sent / total * 100); + + // Use \r at the start to move the cursor back to the beginning of the line + printf("\rProgress: [%d%%]", percent); + + // Force stdout to print immediately without waiting for a newline + fflush(stdout); +} + +// One full OTA attempt: BEGIN -> WRITE... -> END. The BWM OTA has no resume +// (DEV.md 8.4): a dropped chunk can't be re-sent, so any failure here means the +// caller must restart the whole thing. +static int bwm_ota_once(const uint8_t *fw, size_t fwlen, uint32_t write_delay_ms) { + PacketResponseNG resp; + + // BEGIN: tell the BWM how many bytes are coming. The ESP erases the idle + // OTA slot here; that can take 20-40 s on a 4 MB ESP32-C2, so wait longer + // than the device-side 60 s timeout plus USB round-trip. + uint8_t beg[5] = { BWM_OTA_ACTION_BEGIN, + (uint8_t)(fwlen & 0xFF), (uint8_t)((fwlen >> 8) & 0xFF), + (uint8_t)((fwlen >> 16) & 0xFF), (uint8_t)((fwlen >> 24) & 0xFF) + }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, beg, sizeof(beg)); + if (WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 75000) == false) { + PrintAndLogEx(FAILED, "OTA begin timed out (ESP is likely still erasing the OTA slot)"); + PrintAndLogEx(HINT, "Wait a few seconds and retry; do not power-cycle mid-erase."); + return PM3_ETIMEOUT; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "OTA begin failed (status %d)%s", resp.status, + (resp.status == PM3_ETIMEOUT) ? " - UART timeout waiting for ESP" : ""); + return resp.status; + } + PrintAndLogEx(INFO, "Uploading " _YELLOW_("%zu") " bytes of ESP firmware over the BWM link...", fwlen); + + // WRITE chunks. Bounded by BWM_OTA_CHUNK_MAX (the ESP forwards each WRITE over + // its own small app_com UART frame - see bwm_wifi.c), not just the USB frame. + size_t maxchunk = MIN((size_t)g_conn.max_cmd_data_size - 1, (size_t)BWM_OTA_CHUNK_MAX); + uint8_t *buf = calloc(1, maxchunk + 1); + if (buf == NULL) { + return PM3_EMALLOC; + } + size_t sent = 0; + while (sent < fwlen) { + size_t n = MIN(maxchunk, fwlen - sent); + buf[0] = BWM_OTA_ACTION_WRITE; + memcpy(buf + 1, fw + sent, n); + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, buf, (uint16_t)(n + 1)); + bool got = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 25000); + if (!got || resp.status != PM3_SUCCESS) { + PrintAndLogEx(NORMAL, ""); + if (!got) { + PrintAndLogEx(WARNING, "OTA write stalled at offset %zu (no response)", sent); + } else if (resp.status == PM3_ETIMEOUT) { + PrintAndLogEx(WARNING, "OTA write timed out at offset %zu (ESP did not ACK that chunk)", sent); + } else { + PrintAndLogEx(WARNING, "OTA write rejected at offset %zu (status %d)", sent, resp.status); + } + free(buf); + return PM3_EFAILED; + } + sent += n; + progressbar(sent, fwlen, STYLE_MIXED); + + // Pace the stream. The client->AT32 hop (USB/BLE) is far faster than the + // AT32->ESP UART, so back-to-back writes can outrun the UART and drop a + // chunk -> esp_ota_end() then sees written < total and aborts. A small + // gap gives the UART time to drain. (BLE is naturally paced, which is why + // it "worked" and bursty USB did not - see nemanjan00.) + if (write_delay_ms) { + msleep(write_delay_ms); + } + } + free(buf); + PrintAndLogEx(NORMAL, ""); + + // END: finalize + set the new boot partition + uint8_t end[1] = { BWM_OTA_ACTION_END }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, end, sizeof(end)); + bool got_end = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 30000); + if (got_end && (resp.status == PM3_SUCCESS)) { + return PM3_SUCCESS; + } + if (got_end) { + // The BWM answered END with an error. The common one is a size mismatch: + // esp_ota_end() found written < total, i.e. chunks were dropped in transit. + // That is a genuine failure (boot partition NOT switched) - restart, and + // hint at pacing, which is the usual cure. + PrintAndLogEx(WARNING, "OTA finalize rejected (status %d) - data was lost in transit", resp.status); + PrintAndLogEx(HINT, "Try a per-write delay: " _YELLOW_("hw bwm upgrade -f --delay 20")); + return PM3_EFAILED; + } + // No answer at all. Over BLE the END auto-reboot drops the link before the ack + // returns, so a timeout here means "reached END, reboot likely happened" - + // verify by version rather than discarding a possibly-good flash. + return PM3_ETIMEOUT; +} + +// Query the BWM's running firmware version string (APP_CMD_GET_VERSION_INFO). +static int bwm_get_version(char *out, size_t outlen) { + uint8_t a[1] = { BWM_OTA_ACTION_VERSION }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, a, sizeof(a)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + return PM3_EFAILED; + } + uint16_t n = (r.length < (uint16_t)(outlen - 1)) ? r.length : (uint16_t)(outlen - 1); + memcpy(out, r.data.asBytes, n); + out[n] = 0; + return PM3_SUCCESS; +} + +static int CmdBWMUpgrade(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm upgrade", + "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering.\n" + "Requires a BWM that still responds; this updates a wrong-version ESP, it cannot\n" + "recover a fully bricked one (that still needs the 5-pin header + esptool).", + "hw bwm upgrade -f bwm_esp32.bin"); + void *argtable[] = { + arg_param_begin, + arg_str1("f", "file", "", "ESP32 firmware image (.bin)"), + arg_int0(NULL, "delay", "", "per-chunk delay to pace the slow AT32<->ESP UART (default 20)"), + arg_param_end, + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + int fnlen = 0; + char fn[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)fn, sizeof(fn), &fnlen); + uint32_t write_delay_ms = (uint32_t)arg_get_int_def(ctx, 2, 20); + CLIParserFree(ctx); + + if (fnlen == 0) { + PrintAndLogEx(FAILED, "no filename given"); + return PM3_EINVARG; + } + + uint8_t *fw = NULL; + size_t fwlen = 0; + if ((loadFile_safe(fn, "", (void **)&fw, &fwlen) != PM3_SUCCESS) || (fwlen == 0)) { + PrintAndLogEx(FAILED, "could not read " _YELLOW_("%s"), fn); + return PM3_EFILE; + } + + // Safeguard: refuse to flash anything that is not an ESP32-C2 app image. The + // BWM ESP is an ESP32-C2; a wrong/other-chip image would brick it. + // [0x00] == 0xE9 -> ESP image magic + // [0x0C..0x0D] == 0x000C -> chip_id ESP32-C2 (LE uint16) + // [0xABCD5432..0x20] == 0xABCD5432 -> app descriptor (LE uint32) + if (fwlen < 16) { + PrintAndLogEx(FAILED, "file is too small to be an ESP firmware image (%zu bytes)", fwlen); + free(fw); + return PM3_EFILE; + } + if (fw[0] != 0xE9) { + PrintAndLogEx(FAILED, "refusing to flash: not an ESP image (magic " _YELLOW_("0x%02X") ", expected 0xE9)", fw[0]); + free(fw); + return PM3_EFILE; + } + + // Check Chip ID at offset 0x0C (2 bytes, little-endian) + uint16_t chip_id = MemLeToUint2byte(fw + 0x0C); + if (chip_id != 0x000C) { + PrintAndLogEx(FAILED, "refusing to flash: image chip_id " _YELLOW_("0x%04X") " is not ESP32-C2 (0x000C)", chip_id); + free(fw); + return PM3_EFILE; + } + + // Check Application Signature at offset 0x20 (4 bytes, little-endian) + uint32_t app_sign = MemLeToUint4byte(fw + 0x20); + if (app_sign != 0xABCD5432) { + PrintAndLogEx(FAILED, "refusing to flash: image app_sign " _YELLOW_("0x%08X") " is invalid (expected 0xABCD5432)", app_sign); + free(fw); + return PM3_EFILE; + } + + // Record the running version first, so we can confirm the update actually took + // even when the finalize ack is lost (the case that used to discard a completed + // flash and restart from scratch). + char ver_before[64] = {0}; + bool have_before = (bwm_get_version(ver_before, sizeof(ver_before)) == PM3_SUCCESS); + if (have_before) { + PrintAndLogEx(INFO, "Current BWM firmware..... " _YELLOW_("%s"), ver_before); + } + + // No resume (DEV.md 8.4): a chunk lost mid-transfer restarts the whole upload. + const int max_attempts = 6; // a single dropped chunk restarts the whole upload; + // more attempts make an all-fail run rare until per-chunk + // retry (offset-idempotent ESP write) lands. + for (int attempt = 1; attempt <= max_attempts; attempt++) { + if (attempt > 1) { + // Abort the in-flight ESP OTA (if any) and give a slow erase a chance + // to finish before we BEGIN again. Otherwise attempt N's BEGIN races + // attempt N-1's still-running erase and times out. + PrintAndLogEx(INFO, "restarting OTA from the beginning (attempt " _YELLOW_("%d") "/%d)", attempt, max_attempts); + uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); + PacketResponseNG abortr; + (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &abortr, 8000); + msleep(3000); + } + int res = bwm_ota_once(fw, fwlen, write_delay_ms); + + // Failed during BEGIN/WRITE: image incomplete, restart the whole thing. + if ((res != PM3_SUCCESS) && (res != PM3_ETIMEOUT)) { + continue; + } + + // Reached OTA_END (acked, or ack lost). The image is written and the boot + // partition is set - reboot into it and confirm by version. + if (res == PM3_ETIMEOUT) { + PrintAndLogEx(INFO, "finalize ack not seen - all data was sent, confirming by version..."); + } + // Upload is complete and the ESP is rebooting into the new image. The + // AT32<->ESP link is now desynced (the ESP comes back at its boot-default + // baud), and the AT32 only re-negotiates on its own reset - so reset the PM5 + // to re-sync the link cleanly rather than trying to re-link in place. This + // drops the client link; the user reconnects to a cleanly re-linked PM5. + (void)have_before; + PrintAndLogEx(SUCCESS, "BWM firmware uploaded; resetting the PM5 to re-sync the link..."); + free(fw); + clearCommandBuffer(); + SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); + PrintAndLogEx(INFO, "PM5 has been reset - reconnect, then run " _YELLOW_("hw status") " to confirm the new BWM version."); + return PM3_SUCCESS; + } + free(fw); + + // Exhausted retries without a confirmed update - restore the link and report. + PacketResponseNG resp; + uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); + (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 8000); + PrintAndLogEx(FAILED, "BWM firmware update could not be confirmed after %d attempts", max_attempts); + return PM3_EFAILED; +} +static int CmdHelpBwm(const char *Cmd); + +static int CmdBwmName(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm name", + "Get or set the BWM BLE advertising name (stored on the BWM, in NVS).\n" + "With no --set, prints the current name. Setting a name stores it and reboots\n" + "the BWM to apply it - this briefly drops a BLE/WiFi connection; reconnect after\n" + "a few seconds. Over USB the reboot is not noticeable.", + "hw bwm name --> show current BLE name\n" + "hw bwm name --set MyPM5 --> set BLE name to 'MyPM5'"); + void *argtable[] = { + arg_param_begin, + arg_str0(NULL, "set", "", "new BLE name (1-31 chars); omit to read current name"), + arg_param_end, + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + uint8_t name[64] = {0}; + int nlen = sizeof(name) - 1; // CLIGetStrWithReturn does not guarantee NUL-termination + CLIGetStrWithReturn(ctx, 1, name, &nlen); + CLIParserFree(ctx); + + if (nlen == 0) { + // GET + uint8_t a[1] = { BWM_BLE_NAME_ACTION_GET }; + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE_NAME, a, sizeof(a)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + PrintAndLogEx(FAILED, "failed to read BWM BLE name (is a responsive BWM fitted?)"); + return PM3_EFAILED; + } + char out[BWM_BLE_NAME_MAX_LEN + 1] = {0}; + uint16_t n = (r.length < sizeof(out) - 1) ? r.length : (uint16_t)(sizeof(out) - 1); + memcpy(out, r.data.asBytes, n); + PrintAndLogEx(SUCCESS, "BWM BLE name..... " _YELLOW_("%s"), out); + return PM3_SUCCESS; + } + + // SET + if (nlen > BWM_BLE_NAME_MAX_LEN) { + PrintAndLogEx(FAILED, "name too long: %d chars (max " _YELLOW_("%d") ")", nlen, BWM_BLE_NAME_MAX_LEN); + return PM3_EINVARG; + } + uint8_t payload[1 + BWM_BLE_NAME_MAX_LEN]; + payload[0] = BWM_BLE_NAME_ACTION_SET; + memcpy(payload + 1, name, nlen); + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE_NAME, payload, (uint16_t)(1 + nlen)); + PacketResponseNG r; + if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { + PrintAndLogEx(FAILED, "failed to set BWM BLE name (is a responsive BWM fitted?)"); + return PM3_EFAILED; + } + PrintAndLogEx(SUCCESS, "BWM BLE name set to " _YELLOW_("%s"), name); + + // The ESP applies the name at BLE start-up, so it reboots (device-side) to pick + // it up. That reboot leaves the AT32<->ESP link desynced (the ESP comes back at + // its boot-default baud, and the AT32 only re-negotiates on its own reset), so + // reset the PM5 to re-sync. This drops the client link - reconnect afterwards. + PrintAndLogEx(INFO, "Resetting the PM5 to apply the new name and re-sync the BWM link..."); + clearCommandBuffer(); + SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); + PrintAndLogEx(INFO, "PM5 has been reset - reconnect after a few seconds."); + return PM3_SUCCESS; +} + +// Round trip for the BWM u8 settings (`hw bwm powersave`, `hw bwm wifipower`): +// send [action][value] (value only when has_value) and wait for the ESP's answer. +// Prints the generic failure messages; on PM3_SUCCESS resp holds >= 1 byte. +static int bwm_setting_txn(uint16_t cmd, uint8_t action, uint8_t value, bool has_value, + PacketResponseNG *resp, const char *what) { + uint8_t payload[2] = { action, value }; + clearCommandBuffer(); + SendCommandNG(cmd, payload, has_value ? 2 : 1); + if (WaitForResponseTimeout(cmd, resp, 8000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a responsive BWM?)"); + return PM3_ETIMEOUT; + } + if (resp->status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without BWM link support"); + return resp->status; + } + if (resp->status != PM3_SUCCESS || resp->length < 1) { + PrintAndLogEx(FAILED, "BWM did not answer the %s command (BWM firmware too old?)", what); + return (resp->status != PM3_SUCCESS) ? resp->status : PM3_EFAILED; + } + return PM3_SUCCESS; +} + +static const char *bwm_wifi_state_name(uint8_t state) { + switch (state) { + case 0: + return "disconnected"; + case 1: + return "connecting"; + case 2: + return "connected"; + case 3: + return "reconnecting"; + case 4: + return "connect task stopped"; + default: + return "unknown state"; + } +} + +static int CmdBwmPowerSave(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm powersave [on | off]; no verb shows the state + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + bool show = (verb[0] == 0); + + if (!on && !off && !show) { + // Not a recognised sub-action: render help (also serves -h), or error on + // a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm powersave", + "Show or set the BWM (ESP32) power-save switch, stored on the BWM in NVS.\n" + "Default is " _GREEN_("on") ": the ESP scales its clock down, light-sleeps between\n" + "link traffic, and after 30 s of fast advertising (boot, disconnect) advertises\n" + "once a second. " _YELLOW_("off") " pins it at full clock, no sleep, fast advertising\n" + "throughout. Applies at once and survives reboots. PM5 only.", + "hw bwm powersave --> show the current state\n" + "hw bwm powersave off --> stock always-on behaviour\n" + "hw bwm powersave on --> re-enable power saving"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " or nothing to show the state"); + return PM3_EINVARG; + } + + PacketResponseNG resp; + int res = bwm_setting_txn(CMD_PM5_BWM_POWERSAVE, show ? BWM_POWERSAVE_ACTION_GET : BWM_POWERSAVE_ACTION_SET, + on ? 1 : 0, !show, &resp, "power-save"); + if (res != PM3_SUCCESS) { + return res; + } + bool state = (resp.data.asBytes[0] != 0); + PrintAndLogEx(SUCCESS, "BWM power save..... %s", state ? _GREEN_("on") : _YELLOW_("off")); + return PM3_SUCCESS; +} + +static const char *bwm_wifi_ps_name(uint8_t mode) { + switch (mode) { + case BWM_WIFI_PS_NONE: + return "none"; + case BWM_WIFI_PS_MIN: + return "min"; + case BWM_WIFI_PS_MAX: + return "max"; + default: + return "?"; + } +} + +static int CmdBwmWifiPower(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm wifipower [off | none | min | max]; no verb shows the state + char verb[16] = {0}; + sscanf(Cmd, "%15s", verb); + int mode = -1; + if (verb[0] == 0) { + mode = -1; + } else if (strcmp(verb, "off") == 0) { + // WiFi fully off: same as `hw bwm wifi stop`. + return CmdBWMWifi("stop"); + } else if (strcmp(verb, "none") == 0) { + mode = BWM_WIFI_PS_NONE; + } else if (strcmp(verb, "min") == 0) { + mode = BWM_WIFI_PS_MIN; + } else if (strcmp(verb, "max") == 0) { + mode = BWM_WIFI_PS_MAX; + } else { + // Not a recognised sub-action: render help (also serves -h), or error on + // a stray token, then stop. + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm wifipower", + "Show or set how much power the BWM (ESP32) spends on WiFi.\n" + _YELLOW_("off") " turns WiFi fully off (BLE-only, persisted; the default state, same as\n" + "`hw bwm wifi stop`). Bring it back with " _YELLOW_("hw bwm wifi --ssid --pwd ") ".\n" + "The other three set the modem power-save type while WiFi is up, stored on the\n" + "BWM: " _GREEN_("min") " (default) sleeps between DTIM beacons, " _YELLOW_("max") " for the whole\n" + "listen interval, " _YELLOW_("none") " never. Independent of " _YELLOW_("hw bwm powersave") ". PM5 only.", + "hw bwm wifipower --> show whether WiFi is up and the power-save type\n" + "hw bwm wifipower off --> WiFi fully off, BLE-only\n" + "hw bwm wifipower none --> modem always on while WiFi is up\n" + "hw bwm wifipower min --> ESP-IDF default (DTIM sleep)\n" + "hw bwm wifipower max --> deepest modem sleep"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "specify " _YELLOW_("off") ", " _YELLOW_("none") ", " _YELLOW_("min") ", " _YELLOW_("max") " or nothing to show the state"); + return PM3_EINVARG; + } + + PacketResponseNG resp; + int res = bwm_setting_txn(CMD_PM5_BWM_WIFI_PS, (mode < 0) ? BWM_WIFI_PS_ACTION_GET : BWM_WIFI_PS_ACTION_SET, + (mode < 0) ? 0 : (uint8_t)mode, mode >= 0, &resp, "WiFi power"); + if (res != PM3_SUCCESS) { + return res; + } + uint8_t wifi_state = (resp.length >= 2) ? resp.data.asBytes[1] : BWM_WIFI_STATE_OFF; + if (wifi_state == BWM_WIFI_STATE_OFF) { + PrintAndLogEx(SUCCESS, "BWM WiFi................ " _GREEN_("off") " (BLE-only)"); + } else { + PrintAndLogEx(SUCCESS, "BWM WiFi................ " _YELLOW_("on") " (%s)", bwm_wifi_state_name(wifi_state)); + } + PrintAndLogEx(SUCCESS, "BWM WiFi power save..... " _YELLOW_("%s"), bwm_wifi_ps_name(resp.data.asBytes[0])); + return PM3_SUCCESS; +} + + +// --------------------------------------------------------------------------- +// hw bwm ble: the module's BLE settings (CMD_PM5_BWM_BLE) +// --------------------------------------------------------------------------- + +static const char *ble_state_str(uint8_t state) { + switch (state) { + case 0: + return "off"; + case 1: + return "advertising, no client"; + case 2: + return "client connected"; + default: + return "unknown"; + } +} + +// esp_power_level_t index <-> dBm: -24 dBm + 3 dB per step, index 15 = +20 dBm +static int ble_level_to_dbm(uint8_t level) { + if (level == 15) return 20; + return -24 + 3 * (int)level; +} + +static int ble_dbm_to_level(int dbm) { + if (dbm == 20) return 15; + if (dbm < -24 || dbm > 18 || ((dbm + 24) % 3) != 0) return -1; + return (dbm + 24) / 3; +} + +static void ble_print_status(const bwm_ble_status_t *st) { + PrintAndLogEx(INFO, "--- " _CYAN_("BWM BLE") " ---------------------------"); + if (st->enabled == 0xFF) { + PrintAndLogEx(INFO, "BLE................ %s " _YELLOW_("(module firmware without the on/off switch)"), ble_state_str(st->state)); + } else if (st->enabled == 0) { + PrintAndLogEx(INFO, "BLE................ " _YELLOW_("off") " (persisted; radio silent, USB/WiFi only)"); + } else { + PrintAndLogEx(INFO, "BLE................ " _GREEN_("on") ", %s", ble_state_str(st->state)); + } + if (st->name[0]) { + PrintAndLogEx(INFO, "Name............... " _YELLOW_("%s"), st->name); + } + if (st->addr[0] != 0xFF || st->addr[5] != 0xFF) { + PrintAndLogEx(INFO, "Address............ %02X:%02X:%02X:%02X:%02X:%02X", + st->addr[0], st->addr[1], st->addr[2], st->addr[3], st->addr[4], st->addr[5]); + } + if (st->bonding == 1) { + PrintAndLogEx(INFO, "Pairing............ " _GREEN_("required") " (LE Secure Connections, passkey " _YELLOW_("%.6s") ")", st->passkey); + if (memcmp(st->passkey, "123456", 6) == 0) { + PrintAndLogEx(WARNING, "the passkey is the factory default, change it: " _YELLOW_("hw bwm ble pairing -k <6 digits>")); + } + } else if (st->bonding == 0) { + PrintAndLogEx(INFO, "Pairing............ " _RED_("not required") " - anyone in range can connect and use the device"); + PrintAndLogEx(HINT, "enable it with " _YELLOW_("hw bwm ble pairing on")); + } + if (st->bonded_count != 0xFF) { + PrintAndLogEx(INFO, "Bonded devices..... %u%s", st->bonded_count, (st->bonded_count == BWM_BLE_BONDED_MAX) ? " (or more)" : ""); + for (uint8_t i = 0; i < st->bonded_count; i++) { + const uint8_t *a = st->bonded[i]; + PrintAndLogEx(INFO, " [%u] %02X:%02X:%02X:%02X:%02X:%02X (%s)", i, + a[0], a[1], a[2], a[3], a[4], a[5], (a[6] == 0) ? "public" : "random"); + } + } + if (st->txp_adv != 0xFF && st->txp_conn != 0xFF) { + PrintAndLogEx(INFO, "TX power........... advertising %d dBm, connection %d dBm", + ble_level_to_dbm(st->txp_adv), ble_level_to_dbm(st->txp_conn)); + } +} + +// One CMD_PM5_BWM_BLE round trip. Prints the status on success unless quiet. +static int ble_action(uint8_t action, const uint8_t *arg, size_t alen, bool quiet) { + uint8_t payload[1 + 8] = { action }; + if (alen > sizeof(payload) - 1) { + return PM3_EINVARG; + } + if (alen) { + memcpy(&payload[1], arg, alen); + } + clearCommandBuffer(); + SendCommandNG(CMD_PM5_BWM_BLE, payload, 1 + alen); + PacketResponseNG resp; + // Up to a dozen module round trips behind one reply, plus a light-sleep wake. + if (WaitForResponseTimeout(CMD_PM5_BWM_BLE, &resp, 8000) == false) { + PrintAndLogEx(WARNING, "command timeout (is this a PM5? over BLE, a pairing or on/off change drops your own link)"); + return PM3_ETIMEOUT; + } + if (resp.status == PM3_ENOTIMPL) { + PrintAndLogEx(WARNING, "firmware built without the BWM link"); + return resp.status; + } + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "module refused or did not answer (%s)", (resp.status == PM3_ETIMEOUT) ? "timeout" : "error"); + return resp.status; + } + if (resp.length < sizeof(bwm_ble_status_t)) { + PrintAndLogEx(FAILED, "short reply (%u bytes)", resp.length); + return PM3_EFAILED; + } + if (quiet == false) { + ble_print_status((const bwm_ble_status_t *)resp.data.asBytes); + } + return PM3_SUCCESS; +} + +static int CmdBwmBleStatus(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble status", + "Show the module's BLE settings: on/off, name, address, pairing and passkey,\n" + "bonded devices, TX power.", + "hw bwm ble status"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + return ble_action(BWM_BLE_ACTION_STATUS, NULL, 0, false); +} + +static int ble_set_enable(const char *Cmd, bool on) { + CLIParserContext *ctx; + CLIParserInit(&ctx, on ? "hw bwm ble on" : "hw bwm ble off", + "Switch the module's BLE radio on or off. Persisted on the module, applied at\n" + "once. Off means nothing can connect over BLE at all; the PM5 stays reachable\n" + "over USB (and WiFi if configured). Needs a BWM firmware with the BLE switch.\n" + _YELLOW_("Over BLE, `off` cuts your own connection."), + on ? "hw bwm ble on" : "hw bwm ble off"); + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + uint8_t v = on ? 1 : 0; + return ble_action(BWM_BLE_ACTION_ENABLE, &v, 1, false); +} + +static int CmdBwmBleOn(const char *Cmd) { + return ble_set_enable(Cmd, true); +} + +static int CmdBwmBleOff(const char *Cmd) { + return ble_set_enable(Cmd, false); +} + +static int CmdBwmBlePairing(const char *Cmd) { + // Positional sub-action (no dashes): hw bwm ble pairing [on|off] [-k ] + char verb[16] = {0}; + int consumed = 0; + sscanf(Cmd, "%15s%n", verb, &consumed); + bool on = (strcmp(verb, "on") == 0); + bool off = (strcmp(verb, "off") == 0); + const char *rest = (on || off) ? Cmd + consumed : Cmd; + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble pairing", + "Require pairing before a BLE client can use the device. The module ships with\n" + "pairing " _RED_("off") ": anyone in range can connect and run commands. With it on, a\n" + "client must pair once with the 6-digit passkey (LE Secure Connections, MITM)\n" + "and the data characteristic only works over the encrypted link; paired\n" + "(bonded) devices reconnect without the key until you forget them.\n" + "Both settings persist on the module. A change of on/off restarts the BLE\n" + "stack, which " _YELLOW_("drops a connected client - reconnect (and pair) afterwards.") "\n" + "The factory passkey is 123456; set your own.", + "hw bwm ble pairing on --> require pairing\n" + "hw bwm ble pairing on -k 482913 --> require pairing with this passkey\n" + "hw bwm ble pairing -k 482913 --> change the passkey only\n" + "hw bwm ble pairing off --> open access again"); + void *argtable[] = { + arg_param_begin, + arg_str0("k", "key", "<6 digits>", "passkey a client must enter"), + arg_param_end + }; + CLIExecWithReturn(ctx, rest, argtable, true); + uint8_t key[8] = {0}; + int keylen = 0; + int kres = CLIParamStrToBuf(arg_get_str(ctx, 1), key, sizeof(key) - 1, &keylen); + CLIParserFree(ctx); + if (kres) { + PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); + return PM3_EINVARG; + } + + if (keylen) { + bool ok = (keylen == 6); + for (int i = 0; ok && i < 6; i++) { + ok = isdigit(key[i]); + } + if (ok == false) { + PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); + return PM3_EINVARG; + } + int res = ble_action(BWM_BLE_ACTION_KEY, key, 6, (on || off)); + if (res != PM3_SUCCESS) { + return res; + } + if (!on && !off) { + PrintAndLogEx(SUCCESS, "passkey set"); + return PM3_SUCCESS; + } + } else if (!on && !off) { + PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " and/or " _YELLOW_("-k <6 digits>")); + return PM3_EINVARG; + } + uint8_t v = on ? 1 : 0; + int res = ble_action(BWM_BLE_ACTION_PAIRING, &v, 1, false); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "pairing %s; the BLE stack is restarting, a connected client is dropped", on ? _GREEN_("required") : _YELLOW_("not required")); + } + return res; +} + +static int CmdBwmBleForget(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble forget", + "Remove bonded (paired) devices from the module, so they must pair again with\n" + "the passkey. Indexes are the ones `hw bwm ble status` lists.", + "hw bwm ble forget --all\n" + "hw bwm ble forget -i 0"); + void *argtable[] = { + arg_param_begin, + arg_int0("i", "idx", "", "index of the bonded device to remove"), + arg_lit0(NULL, "all", "remove all bonded devices"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + int idx = arg_get_int_def(ctx, 1, -1); + bool all = arg_get_lit(ctx, 2); + CLIParserFree(ctx); + if ((all && idx >= 0) || (!all && idx < 0)) { + PrintAndLogEx(WARNING, "specify either " _YELLOW_("-i ") " or " _YELLOW_("--all")); + return PM3_EINVARG; + } + if (idx > 254) { + PrintAndLogEx(WARNING, "index out of range"); + return PM3_EINVARG; + } + uint8_t v = all ? 0xFF : (uint8_t)idx; + return ble_action(BWM_BLE_ACTION_FORGET, &v, 1, false); +} + +static int CmdBwmBleTxPower(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hw bwm ble txpower", + "Set the module's BLE transmit power for advertising and/or connections.\n" + "Steps of 3 dB from -24 to 18 dBm, plus 20. Lower saves a little battery and\n" + "shrinks the range at which the device can be found. Persisted on the module.", + "hw bwm ble txpower -a 0 -c 0 --> 0 dBm for both\n" + "hw bwm ble txpower -a -6 --> quieter advertising only"); + void *argtable[] = { + arg_param_begin, + arg_int0("a", "adv", "", "advertising power"), + arg_int0("c", "conn", "", "connection power"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool has_adv = (arg_get_int_count(ctx, 1) > 0); + bool has_conn = (arg_get_int_count(ctx, 2) > 0); + int adv = arg_get_int_def(ctx, 1, 0); + int conn = arg_get_int_def(ctx, 2, 0); + CLIParserFree(ctx); + if ((has_adv == false) && (has_conn == false)) { + PrintAndLogEx(WARNING, "specify " _YELLOW_("-a ") " and/or " _YELLOW_("-c ")); + return PM3_EINVARG; + } + int la = has_adv ? ble_dbm_to_level(adv) : 0; + int lc = has_conn ? ble_dbm_to_level(conn) : 0; + if (la < 0 || lc < 0) { + PrintAndLogEx(WARNING, "valid values: -24, -21, ... 15, 18, 20 dBm"); + return PM3_EINVARG; + } + int res = PM3_SUCCESS; + if (has_adv) { + uint8_t v[2] = { 0, (uint8_t)la }; + res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, has_conn); + } + if (res == PM3_SUCCESS && has_conn) { + uint8_t v[2] = { 1, (uint8_t)lc }; + res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, false); + } + return res; +} + +static int CmdHelpBwmBle(const char *Cmd); +static command_t BwmBleCommandTable[] = { + {"help", CmdHelpBwmBle, AlwaysAvailable, "This help"}, + {"status", CmdBwmBleStatus, IfBwm, "Show BLE settings: on/off, pairing, bonded devices, TX power"}, + {"on", CmdBwmBleOn, IfBwm, "Switch BLE on (persisted)"}, + {"off", CmdBwmBleOff, IfBwm, "Switch BLE off (persisted) - nothing can connect"}, + {"pairing", CmdBwmBlePairing, IfBwm, "Require pairing with a passkey, set the passkey"}, + {"forget", CmdBwmBleForget, IfBwm, "Remove bonded devices"}, + {"txpower", CmdBwmBleTxPower, IfBwm, "Set advertising / connection TX power"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelpBwmBle(const char *Cmd) { + (void)Cmd; + CmdsHelp(BwmBleCommandTable); + return PM3_SUCCESS; +} + +static int CmdBwmBle(const char *Cmd) { + clearCommandBuffer(); + return CmdsParse(BwmBleCommandTable, Cmd); +} + +static command_t BwmCommandTable[] = { + {"help", CmdHelpBwm, AlwaysAvailable, "This help"}, + {"autooff", CmdBwmAutoOff, IfBwm, "Show/set auto power-off (USB unplug, idle on battery)"}, + {"ble", CmdBwmBle, IfBwm, "{ BLE: on/off, pairing, bonded devices, TX power... }"}, + {"charge", CmdBwmCharge, IfBwm, "Enable/disable battery charging (one-shot)"}, + {"name", CmdBwmName, IfBwm, "Get/set the BWM BLE advertising name"}, + {"powersave", CmdBwmPowerSave, IfBwm, "Show/set the BWM power-save switch (DFS, light sleep, slow adv)"}, + {"setcap", CmdBwmSetCap, IfBwm, "Set fuel-gauge design capacity (run once after battery change)"}, + {"upgrade", CmdBWMUpgrade, IfBwm, "Reflash BWM (ESP32) firmware over the BWM link, no header"}, + {"vchg", CmdBwmVchg, IfBwm, "Set charger charge-voltage target (default 4100 mV)"}, + {"wifi", CmdBWMWifi, IfBwm, "Bring up WiFi (STA + TCP server) for a tcp: connection"}, + {"wifipower", CmdBwmWifiPower, IfBwm, "WiFi fully off, or the modem power-save type (none/min/max)"}, + {NULL, NULL, NULL, NULL} +}; + +static int CmdHelpBwm(const char *Cmd) { + (void)Cmd; + CmdsHelp(BwmCommandTable); + return PM3_SUCCESS; +} + +int CmdBwm(const char *Cmd) { + clearCommandBuffer(); + return CmdsParse(BwmCommandTable, Cmd); +} From f9bd1c30105688ad4ae41613d490110e419aa602 Mon Sep 17 00:00:00 2001 From: Niel Nielsen Date: Fri, 2 Oct 2026 13:48:24 +0200 Subject: [PATCH 03/15] Update default port from 7777 to 18888 Signed-off-by: Niel Nielsen --- doc/md/PM5_Start_Here/PM5-BWM-USAGE.md | 1690 +++++++----------------- 1 file changed, 442 insertions(+), 1248 deletions(-) diff --git a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md index 0fc028f7b..752353d94 100644 --- a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md +++ b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md @@ -1,1248 +1,442 @@ -//----------------------------------------------------------------------------- -// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// See LICENSE.txt for the text of the license. -//----------------------------------------------------------------------------- -// BWM (battery/wireless module) commands -//----------------------------------------------------------------------------- - -#include -#include -#include -#include - -#include "cmdparser.h" // command_t -#include "cliparser.h" -#include "comms.h" -#include "usart_defs.h" -#include "ui.h" -#include "cmdbwm.h" -#include "cmdhw.h" -#include "commonutil.h" -#include "pm3_cmd.h" -#include "cmdflashmem.h" // get_signature.. -#include "fileutils.h" // loadFile_safe -#include "util_posix.h" - -static int CmdBwmAutoOff(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm autooff [on|off] [--idle ] - char verb[16] = {0}; - int consumed = 0; - sscanf(Cmd, "%15s%n", verb, &consumed); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - const char *rest = (on || off) ? Cmd + consumed : Cmd; - - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm autooff", - "Show or set automatic power-off (PM5 only). Two triggers:\n" - " - USB was present and the cable is pulled: off at once, so a BWM-equipped\n" - " PM5 doesn't silently drain the battery; --unplug off only restarts the\n" - " idle clock instead;\n" - " - on battery with no command, button press or BLE/WiFi client for --idle\n" - " seconds: off (0 = never, the default).\n" - "Button power-on is unaffected. Stored on the BWM; without a module, defaults.", - "hw bwm autooff --> show the current state\n" - "hw bwm autooff off --> disable both triggers\n" - "hw bwm autooff on --> re-enable\n" - "hw bwm autooff --idle 300 --> also off after 5 min idle on battery\n" - "hw bwm autooff --idle 0 --> USB-unplug trigger only (default)\n" - "hw bwm autooff --unplug off --idle 300 --> survive the unplug, off 5 min idle later"); - void *argtable[] = { - arg_param_begin, - arg_int0("i", "idle", "", "idle timeout on battery in seconds, 0 = never"), - arg_str0("u", "unplug", "", "power off when USB is pulled (default on)"), - arg_param_end - }; - CLIExecWithReturn(ctx, rest, argtable, true); - int idle = arg_get_int_def(ctx, 1, -1); - uint8_t ubuf[8] = {0}; - int ulen = 0; - int ures = CLIParamStrToBuf(arg_get_str(ctx, 2), ubuf, sizeof(ubuf) - 1, &ulen); - CLIParserFree(ctx); - if (ures) { - PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); - return PM3_EINVARG; - } - uint8_t unplug = BWM_AUTOOFF_KEEP_U8; - if (ulen) { - if (strcmp((char *)ubuf, "on") == 0) { - unplug = 1; - } else if (strcmp((char *)ubuf, "off") == 0) { - unplug = 0; - } else { - PrintAndLogEx(WARNING, "--unplug takes " _YELLOW_("on") " or " _YELLOW_("off")); - return PM3_EINVARG; - } - } - if ((idle < -1) || (idle > (int)BWM_AUTOOFF_IDLE_MAX_S)) { - PrintAndLogEx(WARNING, "idle must be 0 to %lu seconds", (unsigned long)BWM_AUTOOFF_IDLE_MAX_S); - return PM3_EINVARG; - } - - struct { - uint8_t action; - uint8_t enabled; - uint32_t idle_s; - uint8_t unplug; - } PACKED payload = { - .action = (on || off || (idle >= 0) || ulen) ? BWM_AUTOOFF_ACTION_SET : BWM_AUTOOFF_ACTION_GET, - .enabled = on ? 1 : (off ? 0 : BWM_AUTOOFF_KEEP_U8), - .idle_s = (idle >= 0) ? (uint32_t)idle : BWM_AUTOOFF_KEEP_U32, - .unplug = unplug, - }; - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_AUTOOFF, (uint8_t *)&payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); - return PM3_ETIMEOUT; - } - if (resp.status == PM3_ENOTIMPL) { - PrintAndLogEx(WARNING, "firmware built without auto power-off support"); - return resp.status; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to set auto power-off"); - return resp.status; - } - bool enabled = (resp.length >= 1) && (resp.data.asBytes[0] != 0); - PrintAndLogEx(SUCCESS, "Auto power-off....... %s", enabled ? _GREEN_("on") : _YELLOW_("off")); - if (resp.length < 5) { - // firmware before the idle timeout: it only reports the switch - return PM3_SUCCESS; - } - uint32_t idle_s; - memcpy(&idle_s, &resp.data.asBytes[1], sizeof(idle_s)); - if (idle_s) { - PrintAndLogEx(INFO, "Idle timeout......... " _YELLOW_("%u") " s", idle_s); - } else { - PrintAndLogEx(INFO, "Idle timeout......... off"); - } - if (resp.length >= sizeof(bwm_autooff_status_t)) { - const bwm_autooff_status_t *st = (const bwm_autooff_status_t *)resp.data.asBytes; - const char *live = (st->ble_live == 2) ? "client connected" : (st->ble_live == 1) ? "advertising, no client" : (st->ble_live == 0) ? "off" : "no answer"; - PrintAndLogEx(INFO, "Unplug power-off..... %s", st->unplug ? "on" : _YELLOW_("off") " (an unplug only restarts the idle clock)"); - PrintAndLogEx(INFO, "Stored on module..... %s", st->persisted ? "yes" : _YELLOW_("no")); - PrintAndLogEx(INFO, "USB power............ %s", st->usb ? "present" : "absent"); - PrintAndLogEx(INFO, "USB seen since boot.. %s", st->usb_seen ? "yes" : "no"); - PrintAndLogEx(INFO, "Unplug trigger....... %s", (enabled && st->unplug && st->usb_seen) ? _GREEN_("armed") : "not armed"); - PrintAndLogEx(INFO, "Tracked client....... %s", st->link ? "connected (BLE or WiFi)" : "none"); - PrintAndLogEx(INFO, "Module BLE state..... %s", live); - PrintAndLogEx(INFO, "Idle for............. %u s", st->idle_now_s); - if (st->persisted == 0) { - PrintAndLogEx(HINT, "no module, or one too old to store it: the defaults return at the next boot"); - } - } - return PM3_SUCCESS; -} - -static int CmdBWMWifi(const char *Cmd) { - // Sub-actions that carry no other arguments are positional keywords now: - // hw bwm wifi status (was --status) - // hw bwm wifi stop (was --stop) - // Bringing WiFi up still takes value flags, so it stays the default - // (no-keyword) form: hw bwm wifi --ssid --pwd [--port ] - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - - if (strcmp(verb, "status") == 0) { - uint8_t q[1] = { BWM_WIFI_ACTION_STATUS }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, q, sizeof(q)); - PacketResponseNG r; - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (r.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "could not query BWM WiFi status (BWM present?)"); - return r.status; - } - uint8_t state = (r.length >= 1) ? r.data.asBytes[0] : 0xFF; - uint32_t ip = 0; - if (r.length >= 5) { - ip = r.data.asBytes[1] | (r.data.asBytes[2] << 8) | (r.data.asBytes[3] << 16) | ((uint32_t)r.data.asBytes[4] << 24); - } - switch (state) { - case 0xFF: - PrintAndLogEx(INFO, "BWM WiFi disabled (BLE-only). Bring it up with " _YELLOW_("hw bwm wifi --ssid --pwd ")); - break; - case 2: // connected - if (ip) { - PrintAndLogEx(SUCCESS, "BWM WiFi connected, IP " _YELLOW_("%u.%u.%u.%u"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - } else { - PrintAndLogEx(INFO, "BWM WiFi associated, waiting for a DHCP lease..."); - } - break; - case 1: // connecting - PrintAndLogEx(INFO, "BWM WiFi connecting..."); - break; - case 3: // reconnect wait - PrintAndLogEx(INFO, "BWM WiFi reconnecting..."); - break; - case 4: // task stopped - PrintAndLogEx(INFO, "BWM WiFi connect task stopped"); - break; - case 0: // disconnected - default: - PrintAndLogEx(INFO, "BWM WiFi configured but not connected"); - break; - } - return PM3_SUCCESS; - } - - if (strcmp(verb, "stop") == 0) { - uint8_t off[1] = { BWM_WIFI_ACTION_STOP }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, off, sizeof(off)); - PacketResponseNG r; - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &r, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (r.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to disable BWM WiFi"); - return r.status; - } - PrintAndLogEx(SUCCESS, "BWM WiFi disabled (back to BLE-only)"); - return PM3_SUCCESS; - } - - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm wifi", - "Bring up the BWM in STA + TCP-server mode: join a WiFi network and\n" - "start a TCP server so the client can connect over WiFi. PM5 only.\n" - "Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", - "hw bwm wifi status --> show connection state + IP\n" - "hw bwm wifi stop --> tear down WiFi, back to BLE-only\n" - "hw bwm wifi --ssid Home --pwd secret --> bring up, port 18888\n" - "hw bwm wifi --ssid Home --pwd secret --port 9000"); - - void *argtable[] = { - arg_param_begin, - arg_str0(NULL, "ssid", "", "WiFi SSID to join"), - arg_str0(NULL, "pwd", "", "WiFi password (omit for open network)"), - arg_int0(NULL, "port", "", "TCP server listen port (default 18888)"), - arg_str0(NULL, "hostname", "", "DHCP hostname (default Proxmark5)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - - uint8_t ssid[64] = {0}; - int ssid_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 1), ssid, sizeof(ssid) - 1, &ssid_len); - - uint8_t pwd[64] = {0}; - int pwd_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 2), pwd, sizeof(pwd) - 1, &pwd_len); - - int port = arg_get_int_def(ctx, 3, 18888); - - uint8_t host[33] = {0}; - int host_len = 0; - CLIParamStrToBuf(arg_get_str(ctx, 4), host, sizeof(host) - 1, &host_len); - if (host_len == 0) { - strcpy((char *)host, "Proxmark5"); - host_len = 9; - } - CLIParserFree(ctx); - - if (ssid_len == 0) { - PrintAndLogEx(FAILED, "an SSID is required (or " _YELLOW_("hw bwm wifi stop") " to tear down)"); - return PM3_EINVARG; - } - if (port < 1 || port > 65535) { - PrintAndLogEx(FAILED, "port must be 1..65535"); - return PM3_EINVARG; - } - - // payload: [action:u8][port:u16 LE][ssid\0][pwd\0][hostname\0] - uint8_t data[200] = {0}; - int n = 0; - data[n++] = BWM_WIFI_ACTION_START; - data[n++] = (uint8_t)(port & 0xFF); - data[n++] = (uint8_t)((port >> 8) & 0xFF); - memcpy(&data[n], ssid, ssid_len); - n += ssid_len; - data[n++] = 0; - memcpy(&data[n], pwd, pwd_len); - n += pwd_len; - data[n++] = 0; - memcpy(&data[n], host, host_len); - n += host_len; - data[n++] = 0; - - PrintAndLogEx(INFO, "Bringing up BWM WiFi (SSID \"%s\", port %d)... this can take ~15s", ssid, port); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_WIFI, data, n); - PacketResponseNG resp; - // ARM blocks during join + DHCP wait, so allow a long client timeout - if (WaitForResponseTimeout(CMD_PM5_BWM_WIFI, &resp, 60000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "BWM WiFi bring-up failed (check SSID/password and signal)"); - PrintAndLogEx(HINT, "If it may have joined after DHCP, check: " _YELLOW_("hw bwm wifi status")); - return resp.status; - } - - uint32_t ip = resp.data.asDwords[0]; - PrintAndLogEx(SUCCESS, "BWM on WiFi at %u.%u.%u.%u", - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF); - PrintAndLogEx(HINT, "Connect with: " _YELLOW_("pm3 -p tcp:%u.%u.%u.%u:%d"), - ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24) & 0xFF, port); - PrintAndLogEx(HINT, "Or by name (router-dependent): " _YELLOW_("pm3 -p tcp:%s:%d"), host, port); - PrintAndLogEx(HINT, "Or by mDNS (BWM fw with mDNS): " _YELLOW_("pm3 -p tcp:%s.local:%d"), host, port); - return PM3_SUCCESS; -} - -static int CmdBwmCharge(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm charge on | off - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - - if (!on && !off) { - // Not a recognised sub-action: render help (also serves -h / empty), - // or error on a stray token, then stop. - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm charge", - "Enable or disable BWM battery charging by clearing/setting the\n" - "AW32001E charge-enable bit (CEB, REG01[3]). PM5 only.\n" - _RED_("One-shot:") " the charger watchdog reverts this after ~160 s unless\n" - "serviced, so charging may stop on its own. Use to nudge a top-up.", - "hw bwm charge off --> disable charging\n" - "hw bwm charge on --> enable charging"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); - return PM3_EINVARG; - } - - uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) - PrintAndLogEx(INFO, "%s BWM battery charging...", off ? "Disabling" : "Enabling"); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_CHARGE_EN, &payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_CHARGE_EN, &resp, 2500) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "charger did not respond (check BWM present)"); - return resp.status; - } - PrintAndLogEx(SUCCESS, "Charging %s. Verify with " _YELLOW_("hw status") ".", - off ? "disabled" : "enabled"); - if (off == false) { - PrintAndLogEx(HINT, "Reverts on the charger watchdog (~160 s) if not serviced."); - } - return PM3_SUCCESS; -} - -static int CmdBwmVchg(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm vchg", - "Set the BWM charger (AW32001E) charge-voltage regulation target.\n" - "Lowering it below 4.2 V reduces top-of-charge stress and extends cell\n" - "life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is\n" - "a runtime register write (reverts on the charger watchdog / POR); the\n" - "firmware re-applies the " _YELLOW_("4100 mV") " default at every boot. PM5 only.", - "hw bwm vchg --> set charge voltage to default 4100 mV (->4.095 V)\n" - "hw bwm vchg --mv 4200 --> set charge voltage to 4200 mV"); - - void *argtable[] = { - arg_param_begin, - arg_int0(NULL, "mv", "", "charge voltage in mV (default 4100, clamped 3600..4200)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - int mv = arg_get_int_def(ctx, 1, 4100); - CLIParserFree(ctx); - - if (mv < 3600 || mv > 4200) { - PrintAndLogEx(WARNING, "charge voltage out of range (3600..4200 mV): %d", mv); - return PM3_EINVARG; - } - - uint8_t payload[2] = { (uint8_t)(mv & 0xFF), (uint8_t)((mv >> 8) & 0xFF) }; - PrintAndLogEx(INFO, "Setting BWM charge voltage to " _YELLOW_("%d mV") "...", mv); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_SET_VCHG, payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_SET_VCHG, &resp, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "failed to set charge voltage - check BWM present"); - return resp.status; - } - uint16_t applied = (resp.length >= 2) ? (resp.data.asBytes[0] | (resp.data.asBytes[1] << 8)) : 0; - PrintAndLogEx(SUCCESS, "Charge voltage set to " _YELLOW_("%u.%03u V") " (nearest 15 mV step).", applied / 1000, applied % 1000); - return PM3_SUCCESS; -} - -static int CmdBwmSetCap(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm setcap", - "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell.\n" - "Run ONCE after fitting or replacing the battery. This triggers a gauge\n" - "config-update; do not run it repeatedly, as that disrupts the Impedance\n" - "Track learning cycle. PM5 only.", - "hw bwm setcap --> set design capacity to default 500 mAh\n" - "hw bwm setcap --cap 500 --> set design capacity to 500 mAh"); - - void *argtable[] = { - arg_param_begin, - arg_int0(NULL, "cap", "", "design capacity in mAh (default 500)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - int cap = arg_get_int_def(ctx, 1, 500); - CLIParserFree(ctx); - - if (cap <= 0 || cap > 32000) { - PrintAndLogEx(WARNING, "capacity out of range: %d mAh", cap); - return PM3_EINVARG; - } - - uint8_t payload[2] = { (uint8_t)(cap & 0xFF), (uint8_t)((cap >> 8) & 0xFF) }; - PrintAndLogEx(INFO, "Programming BWM gauge design capacity to " _YELLOW_("%d mAh") "...", cap); - PrintAndLogEx(INFO, "Run this " _YELLOW_("once") "; then perform a full charge/discharge learning cycle."); - - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_SET_CAP, payload, sizeof(payload)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_SET_CAP, &resp, 5000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a BWM fitted?)"); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "gauge provisioning failed - check BWM present and gauge unsealed"); - return resp.status; - } - PrintAndLogEx(SUCCESS, "Design capacity programmed. `hw status` should now report sane capacity."); - return PM3_SUCCESS; -} - - -static void progressbar(long sent, long total, int style) { - int percent = (int)((double)sent / total * 100); - - // Use \r at the start to move the cursor back to the beginning of the line - printf("\rProgress: [%d%%]", percent); - - // Force stdout to print immediately without waiting for a newline - fflush(stdout); -} - -// One full OTA attempt: BEGIN -> WRITE... -> END. The BWM OTA has no resume -// (DEV.md 8.4): a dropped chunk can't be re-sent, so any failure here means the -// caller must restart the whole thing. -static int bwm_ota_once(const uint8_t *fw, size_t fwlen, uint32_t write_delay_ms) { - PacketResponseNG resp; - - // BEGIN: tell the BWM how many bytes are coming. The ESP erases the idle - // OTA slot here; that can take 20-40 s on a 4 MB ESP32-C2, so wait longer - // than the device-side 60 s timeout plus USB round-trip. - uint8_t beg[5] = { BWM_OTA_ACTION_BEGIN, - (uint8_t)(fwlen & 0xFF), (uint8_t)((fwlen >> 8) & 0xFF), - (uint8_t)((fwlen >> 16) & 0xFF), (uint8_t)((fwlen >> 24) & 0xFF) - }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, beg, sizeof(beg)); - if (WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 75000) == false) { - PrintAndLogEx(FAILED, "OTA begin timed out (ESP is likely still erasing the OTA slot)"); - PrintAndLogEx(HINT, "Wait a few seconds and retry; do not power-cycle mid-erase."); - return PM3_ETIMEOUT; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "OTA begin failed (status %d)%s", resp.status, - (resp.status == PM3_ETIMEOUT) ? " - UART timeout waiting for ESP" : ""); - return resp.status; - } - PrintAndLogEx(INFO, "Uploading " _YELLOW_("%zu") " bytes of ESP firmware over the BWM link...", fwlen); - - // WRITE chunks. Bounded by BWM_OTA_CHUNK_MAX (the ESP forwards each WRITE over - // its own small app_com UART frame - see bwm_wifi.c), not just the USB frame. - size_t maxchunk = MIN((size_t)g_conn.max_cmd_data_size - 1, (size_t)BWM_OTA_CHUNK_MAX); - uint8_t *buf = calloc(1, maxchunk + 1); - if (buf == NULL) { - return PM3_EMALLOC; - } - size_t sent = 0; - while (sent < fwlen) { - size_t n = MIN(maxchunk, fwlen - sent); - buf[0] = BWM_OTA_ACTION_WRITE; - memcpy(buf + 1, fw + sent, n); - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, buf, (uint16_t)(n + 1)); - bool got = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 25000); - if (!got || resp.status != PM3_SUCCESS) { - PrintAndLogEx(NORMAL, ""); - if (!got) { - PrintAndLogEx(WARNING, "OTA write stalled at offset %zu (no response)", sent); - } else if (resp.status == PM3_ETIMEOUT) { - PrintAndLogEx(WARNING, "OTA write timed out at offset %zu (ESP did not ACK that chunk)", sent); - } else { - PrintAndLogEx(WARNING, "OTA write rejected at offset %zu (status %d)", sent, resp.status); - } - free(buf); - return PM3_EFAILED; - } - sent += n; - progressbar(sent, fwlen, STYLE_MIXED); - - // Pace the stream. The client->AT32 hop (USB/BLE) is far faster than the - // AT32->ESP UART, so back-to-back writes can outrun the UART and drop a - // chunk -> esp_ota_end() then sees written < total and aborts. A small - // gap gives the UART time to drain. (BLE is naturally paced, which is why - // it "worked" and bursty USB did not - see nemanjan00.) - if (write_delay_ms) { - msleep(write_delay_ms); - } - } - free(buf); - PrintAndLogEx(NORMAL, ""); - - // END: finalize + set the new boot partition - uint8_t end[1] = { BWM_OTA_ACTION_END }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, end, sizeof(end)); - bool got_end = WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 30000); - if (got_end && (resp.status == PM3_SUCCESS)) { - return PM3_SUCCESS; - } - if (got_end) { - // The BWM answered END with an error. The common one is a size mismatch: - // esp_ota_end() found written < total, i.e. chunks were dropped in transit. - // That is a genuine failure (boot partition NOT switched) - restart, and - // hint at pacing, which is the usual cure. - PrintAndLogEx(WARNING, "OTA finalize rejected (status %d) - data was lost in transit", resp.status); - PrintAndLogEx(HINT, "Try a per-write delay: " _YELLOW_("hw bwm upgrade -f --delay 20")); - return PM3_EFAILED; - } - // No answer at all. Over BLE the END auto-reboot drops the link before the ack - // returns, so a timeout here means "reached END, reboot likely happened" - - // verify by version rather than discarding a possibly-good flash. - return PM3_ETIMEOUT; -} - -// Query the BWM's running firmware version string (APP_CMD_GET_VERSION_INFO). -static int bwm_get_version(char *out, size_t outlen) { - uint8_t a[1] = { BWM_OTA_ACTION_VERSION }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, a, sizeof(a)); - PacketResponseNG r; - if ((WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { - return PM3_EFAILED; - } - uint16_t n = (r.length < (uint16_t)(outlen - 1)) ? r.length : (uint16_t)(outlen - 1); - memcpy(out, r.data.asBytes, n); - out[n] = 0; - return PM3_SUCCESS; -} - -static int CmdBWMUpgrade(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm upgrade", - "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering.\n" - "Requires a BWM that still responds; this updates a wrong-version ESP, it cannot\n" - "recover a fully bricked one (that still needs the 5-pin header + esptool).", - "hw bwm upgrade -f bwm_esp32.bin"); - void *argtable[] = { - arg_param_begin, - arg_str1("f", "file", "", "ESP32 firmware image (.bin)"), - arg_int0(NULL, "delay", "", "per-chunk delay to pace the slow AT32<->ESP UART (default 20)"), - arg_param_end, - }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int fnlen = 0; - char fn[FILE_PATH_SIZE] = {0}; - CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)fn, sizeof(fn), &fnlen); - uint32_t write_delay_ms = (uint32_t)arg_get_int_def(ctx, 2, 20); - CLIParserFree(ctx); - - if (fnlen == 0) { - PrintAndLogEx(FAILED, "no filename given"); - return PM3_EINVARG; - } - - uint8_t *fw = NULL; - size_t fwlen = 0; - if ((loadFile_safe(fn, "", (void **)&fw, &fwlen) != PM3_SUCCESS) || (fwlen == 0)) { - PrintAndLogEx(FAILED, "could not read " _YELLOW_("%s"), fn); - return PM3_EFILE; - } - - // Safeguard: refuse to flash anything that is not an ESP32-C2 app image. The - // BWM ESP is an ESP32-C2; a wrong/other-chip image would brick it. - // [0x00] == 0xE9 -> ESP image magic - // [0x0C..0x0D] == 0x000C -> chip_id ESP32-C2 (LE uint16) - // [0xABCD5432..0x20] == 0xABCD5432 -> app descriptor (LE uint32) - if (fwlen < 16) { - PrintAndLogEx(FAILED, "file is too small to be an ESP firmware image (%zu bytes)", fwlen); - free(fw); - return PM3_EFILE; - } - if (fw[0] != 0xE9) { - PrintAndLogEx(FAILED, "refusing to flash: not an ESP image (magic " _YELLOW_("0x%02X") ", expected 0xE9)", fw[0]); - free(fw); - return PM3_EFILE; - } - - // Check Chip ID at offset 0x0C (2 bytes, little-endian) - uint16_t chip_id = MemLeToUint2byte(fw + 0x0C); - if (chip_id != 0x000C) { - PrintAndLogEx(FAILED, "refusing to flash: image chip_id " _YELLOW_("0x%04X") " is not ESP32-C2 (0x000C)", chip_id); - free(fw); - return PM3_EFILE; - } - - // Check Application Signature at offset 0x20 (4 bytes, little-endian) - uint32_t app_sign = MemLeToUint4byte(fw + 0x20); - if (app_sign != 0xABCD5432) { - PrintAndLogEx(FAILED, "refusing to flash: image app_sign " _YELLOW_("0x%08X") " is invalid (expected 0xABCD5432)", app_sign); - free(fw); - return PM3_EFILE; - } - - // Record the running version first, so we can confirm the update actually took - // even when the finalize ack is lost (the case that used to discard a completed - // flash and restart from scratch). - char ver_before[64] = {0}; - bool have_before = (bwm_get_version(ver_before, sizeof(ver_before)) == PM3_SUCCESS); - if (have_before) { - PrintAndLogEx(INFO, "Current BWM firmware..... " _YELLOW_("%s"), ver_before); - } - - // No resume (DEV.md 8.4): a chunk lost mid-transfer restarts the whole upload. - const int max_attempts = 6; // a single dropped chunk restarts the whole upload; - // more attempts make an all-fail run rare until per-chunk - // retry (offset-idempotent ESP write) lands. - for (int attempt = 1; attempt <= max_attempts; attempt++) { - if (attempt > 1) { - // Abort the in-flight ESP OTA (if any) and give a slow erase a chance - // to finish before we BEGIN again. Otherwise attempt N's BEGIN races - // attempt N-1's still-running erase and times out. - PrintAndLogEx(INFO, "restarting OTA from the beginning (attempt " _YELLOW_("%d") "/%d)", attempt, max_attempts); - uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); - PacketResponseNG abortr; - (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &abortr, 8000); - msleep(3000); - } - int res = bwm_ota_once(fw, fwlen, write_delay_ms); - - // Failed during BEGIN/WRITE: image incomplete, restart the whole thing. - if ((res != PM3_SUCCESS) && (res != PM3_ETIMEOUT)) { - continue; - } - - // Reached OTA_END (acked, or ack lost). The image is written and the boot - // partition is set - reboot into it and confirm by version. - if (res == PM3_ETIMEOUT) { - PrintAndLogEx(INFO, "finalize ack not seen - all data was sent, confirming by version..."); - } - // Upload is complete and the ESP is rebooting into the new image. The - // AT32<->ESP link is now desynced (the ESP comes back at its boot-default - // baud), and the AT32 only re-negotiates on its own reset - so reset the PM5 - // to re-sync the link cleanly rather than trying to re-link in place. This - // drops the client link; the user reconnects to a cleanly re-linked PM5. - (void)have_before; - PrintAndLogEx(SUCCESS, "BWM firmware uploaded; resetting the PM5 to re-sync the link..."); - free(fw); - clearCommandBuffer(); - SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); - PrintAndLogEx(INFO, "PM5 has been reset - reconnect, then run " _YELLOW_("hw status") " to confirm the new BWM version."); - return PM3_SUCCESS; - } - free(fw); - - // Exhausted retries without a confirmed update - restore the link and report. - PacketResponseNG resp; - uint8_t ab[1] = { BWM_OTA_ACTION_ABORT }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_ESP_OTA, ab, sizeof(ab)); - (void)WaitForResponseTimeout(CMD_PM5_BWM_ESP_OTA, &resp, 8000); - PrintAndLogEx(FAILED, "BWM firmware update could not be confirmed after %d attempts", max_attempts); - return PM3_EFAILED; -} -static int CmdHelpBwm(const char *Cmd); - -static int CmdBwmName(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm name", - "Get or set the BWM BLE advertising name (stored on the BWM, in NVS).\n" - "With no --set, prints the current name. Setting a name stores it and reboots\n" - "the BWM to apply it - this briefly drops a BLE/WiFi connection; reconnect after\n" - "a few seconds. Over USB the reboot is not noticeable.", - "hw bwm name --> show current BLE name\n" - "hw bwm name --set MyPM5 --> set BLE name to 'MyPM5'"); - void *argtable[] = { - arg_param_begin, - arg_str0(NULL, "set", "", "new BLE name (1-31 chars); omit to read current name"), - arg_param_end, - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - - uint8_t name[64] = {0}; - int nlen = sizeof(name) - 1; // CLIGetStrWithReturn does not guarantee NUL-termination - CLIGetStrWithReturn(ctx, 1, name, &nlen); - CLIParserFree(ctx); - - if (nlen == 0) { - // GET - uint8_t a[1] = { BWM_BLE_NAME_ACTION_GET }; - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_BLE_NAME, a, sizeof(a)); - PacketResponseNG r; - if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { - PrintAndLogEx(FAILED, "failed to read BWM BLE name (is a responsive BWM fitted?)"); - return PM3_EFAILED; - } - char out[BWM_BLE_NAME_MAX_LEN + 1] = {0}; - uint16_t n = (r.length < sizeof(out) - 1) ? r.length : (uint16_t)(sizeof(out) - 1); - memcpy(out, r.data.asBytes, n); - PrintAndLogEx(SUCCESS, "BWM BLE name..... " _YELLOW_("%s"), out); - return PM3_SUCCESS; - } - - // SET - if (nlen > BWM_BLE_NAME_MAX_LEN) { - PrintAndLogEx(FAILED, "name too long: %d chars (max " _YELLOW_("%d") ")", nlen, BWM_BLE_NAME_MAX_LEN); - return PM3_EINVARG; - } - uint8_t payload[1 + BWM_BLE_NAME_MAX_LEN]; - payload[0] = BWM_BLE_NAME_ACTION_SET; - memcpy(payload + 1, name, nlen); - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_BLE_NAME, payload, (uint16_t)(1 + nlen)); - PacketResponseNG r; - if ((WaitForResponseTimeout(CMD_PM5_BWM_BLE_NAME, &r, 5000) == false) || (r.status != PM3_SUCCESS)) { - PrintAndLogEx(FAILED, "failed to set BWM BLE name (is a responsive BWM fitted?)"); - return PM3_EFAILED; - } - PrintAndLogEx(SUCCESS, "BWM BLE name set to " _YELLOW_("%s"), name); - - // The ESP applies the name at BLE start-up, so it reboots (device-side) to pick - // it up. That reboot leaves the AT32<->ESP link desynced (the ESP comes back at - // its boot-default baud, and the AT32 only re-negotiates on its own reset), so - // reset the PM5 to re-sync. This drops the client link - reconnect afterwards. - PrintAndLogEx(INFO, "Resetting the PM5 to apply the new name and re-sync the BWM link..."); - clearCommandBuffer(); - SendCommandNG(CMD_HARDWARE_RESET, NULL, 0); - PrintAndLogEx(INFO, "PM5 has been reset - reconnect after a few seconds."); - return PM3_SUCCESS; -} - -// Round trip for the BWM u8 settings (`hw bwm powersave`, `hw bwm wifipower`): -// send [action][value] (value only when has_value) and wait for the ESP's answer. -// Prints the generic failure messages; on PM3_SUCCESS resp holds >= 1 byte. -static int bwm_setting_txn(uint16_t cmd, uint8_t action, uint8_t value, bool has_value, - PacketResponseNG *resp, const char *what) { - uint8_t payload[2] = { action, value }; - clearCommandBuffer(); - SendCommandNG(cmd, payload, has_value ? 2 : 1); - if (WaitForResponseTimeout(cmd, resp, 8000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5 with a responsive BWM?)"); - return PM3_ETIMEOUT; - } - if (resp->status == PM3_ENOTIMPL) { - PrintAndLogEx(WARNING, "firmware built without BWM link support"); - return resp->status; - } - if (resp->status != PM3_SUCCESS || resp->length < 1) { - PrintAndLogEx(FAILED, "BWM did not answer the %s command (BWM firmware too old?)", what); - return (resp->status != PM3_SUCCESS) ? resp->status : PM3_EFAILED; - } - return PM3_SUCCESS; -} - -static const char *bwm_wifi_state_name(uint8_t state) { - switch (state) { - case 0: - return "disconnected"; - case 1: - return "connecting"; - case 2: - return "connected"; - case 3: - return "reconnecting"; - case 4: - return "connect task stopped"; - default: - return "unknown state"; - } -} - -static int CmdBwmPowerSave(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm powersave [on | off]; no verb shows the state - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - bool show = (verb[0] == 0); - - if (!on && !off && !show) { - // Not a recognised sub-action: render help (also serves -h), or error on - // a stray token, then stop. - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm powersave", - "Show or set the BWM (ESP32) power-save switch, stored on the BWM in NVS.\n" - "Default is " _GREEN_("on") ": the ESP scales its clock down, light-sleeps between\n" - "link traffic, and after 30 s of fast advertising (boot, disconnect) advertises\n" - "once a second. " _YELLOW_("off") " pins it at full clock, no sleep, fast advertising\n" - "throughout. Applies at once and survives reboots. PM5 only.", - "hw bwm powersave --> show the current state\n" - "hw bwm powersave off --> stock always-on behaviour\n" - "hw bwm powersave on --> re-enable power saving"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " or nothing to show the state"); - return PM3_EINVARG; - } - - PacketResponseNG resp; - int res = bwm_setting_txn(CMD_PM5_BWM_POWERSAVE, show ? BWM_POWERSAVE_ACTION_GET : BWM_POWERSAVE_ACTION_SET, - on ? 1 : 0, !show, &resp, "power-save"); - if (res != PM3_SUCCESS) { - return res; - } - bool state = (resp.data.asBytes[0] != 0); - PrintAndLogEx(SUCCESS, "BWM power save..... %s", state ? _GREEN_("on") : _YELLOW_("off")); - return PM3_SUCCESS; -} - -static const char *bwm_wifi_ps_name(uint8_t mode) { - switch (mode) { - case BWM_WIFI_PS_NONE: - return "none"; - case BWM_WIFI_PS_MIN: - return "min"; - case BWM_WIFI_PS_MAX: - return "max"; - default: - return "?"; - } -} - -static int CmdBwmWifiPower(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm wifipower [off | none | min | max]; no verb shows the state - char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); - int mode = -1; - if (verb[0] == 0) { - mode = -1; - } else if (strcmp(verb, "off") == 0) { - // WiFi fully off: same as `hw bwm wifi stop`. - return CmdBWMWifi("stop"); - } else if (strcmp(verb, "none") == 0) { - mode = BWM_WIFI_PS_NONE; - } else if (strcmp(verb, "min") == 0) { - mode = BWM_WIFI_PS_MIN; - } else if (strcmp(verb, "max") == 0) { - mode = BWM_WIFI_PS_MAX; - } else { - // Not a recognised sub-action: render help (also serves -h), or error on - // a stray token, then stop. - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm wifipower", - "Show or set how much power the BWM (ESP32) spends on WiFi.\n" - _YELLOW_("off") " turns WiFi fully off (BLE-only, persisted; the default state, same as\n" - "`hw bwm wifi stop`). Bring it back with " _YELLOW_("hw bwm wifi --ssid --pwd ") ".\n" - "The other three set the modem power-save type while WiFi is up, stored on the\n" - "BWM: " _GREEN_("min") " (default) sleeps between DTIM beacons, " _YELLOW_("max") " for the whole\n" - "listen interval, " _YELLOW_("none") " never. Independent of " _YELLOW_("hw bwm powersave") ". PM5 only.", - "hw bwm wifipower --> show whether WiFi is up and the power-save type\n" - "hw bwm wifipower off --> WiFi fully off, BLE-only\n" - "hw bwm wifipower none --> modem always on while WiFi is up\n" - "hw bwm wifipower min --> ESP-IDF default (DTIM sleep)\n" - "hw bwm wifipower max --> deepest modem sleep"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("off") ", " _YELLOW_("none") ", " _YELLOW_("min") ", " _YELLOW_("max") " or nothing to show the state"); - return PM3_EINVARG; - } - - PacketResponseNG resp; - int res = bwm_setting_txn(CMD_PM5_BWM_WIFI_PS, (mode < 0) ? BWM_WIFI_PS_ACTION_GET : BWM_WIFI_PS_ACTION_SET, - (mode < 0) ? 0 : (uint8_t)mode, mode >= 0, &resp, "WiFi power"); - if (res != PM3_SUCCESS) { - return res; - } - uint8_t wifi_state = (resp.length >= 2) ? resp.data.asBytes[1] : BWM_WIFI_STATE_OFF; - if (wifi_state == BWM_WIFI_STATE_OFF) { - PrintAndLogEx(SUCCESS, "BWM WiFi................ " _GREEN_("off") " (BLE-only)"); - } else { - PrintAndLogEx(SUCCESS, "BWM WiFi................ " _YELLOW_("on") " (%s)", bwm_wifi_state_name(wifi_state)); - } - PrintAndLogEx(SUCCESS, "BWM WiFi power save..... " _YELLOW_("%s"), bwm_wifi_ps_name(resp.data.asBytes[0])); - return PM3_SUCCESS; -} - - -// --------------------------------------------------------------------------- -// hw bwm ble: the module's BLE settings (CMD_PM5_BWM_BLE) -// --------------------------------------------------------------------------- - -static const char *ble_state_str(uint8_t state) { - switch (state) { - case 0: - return "off"; - case 1: - return "advertising, no client"; - case 2: - return "client connected"; - default: - return "unknown"; - } -} - -// esp_power_level_t index <-> dBm: -24 dBm + 3 dB per step, index 15 = +20 dBm -static int ble_level_to_dbm(uint8_t level) { - if (level == 15) return 20; - return -24 + 3 * (int)level; -} - -static int ble_dbm_to_level(int dbm) { - if (dbm == 20) return 15; - if (dbm < -24 || dbm > 18 || ((dbm + 24) % 3) != 0) return -1; - return (dbm + 24) / 3; -} - -static void ble_print_status(const bwm_ble_status_t *st) { - PrintAndLogEx(INFO, "--- " _CYAN_("BWM BLE") " ---------------------------"); - if (st->enabled == 0xFF) { - PrintAndLogEx(INFO, "BLE................ %s " _YELLOW_("(module firmware without the on/off switch)"), ble_state_str(st->state)); - } else if (st->enabled == 0) { - PrintAndLogEx(INFO, "BLE................ " _YELLOW_("off") " (persisted; radio silent, USB/WiFi only)"); - } else { - PrintAndLogEx(INFO, "BLE................ " _GREEN_("on") ", %s", ble_state_str(st->state)); - } - if (st->name[0]) { - PrintAndLogEx(INFO, "Name............... " _YELLOW_("%s"), st->name); - } - if (st->addr[0] != 0xFF || st->addr[5] != 0xFF) { - PrintAndLogEx(INFO, "Address............ %02X:%02X:%02X:%02X:%02X:%02X", - st->addr[0], st->addr[1], st->addr[2], st->addr[3], st->addr[4], st->addr[5]); - } - if (st->bonding == 1) { - PrintAndLogEx(INFO, "Pairing............ " _GREEN_("required") " (LE Secure Connections, passkey " _YELLOW_("%.6s") ")", st->passkey); - if (memcmp(st->passkey, "123456", 6) == 0) { - PrintAndLogEx(WARNING, "the passkey is the factory default, change it: " _YELLOW_("hw bwm ble pairing -k <6 digits>")); - } - } else if (st->bonding == 0) { - PrintAndLogEx(INFO, "Pairing............ " _RED_("not required") " - anyone in range can connect and use the device"); - PrintAndLogEx(HINT, "enable it with " _YELLOW_("hw bwm ble pairing on")); - } - if (st->bonded_count != 0xFF) { - PrintAndLogEx(INFO, "Bonded devices..... %u%s", st->bonded_count, (st->bonded_count == BWM_BLE_BONDED_MAX) ? " (or more)" : ""); - for (uint8_t i = 0; i < st->bonded_count; i++) { - const uint8_t *a = st->bonded[i]; - PrintAndLogEx(INFO, " [%u] %02X:%02X:%02X:%02X:%02X:%02X (%s)", i, - a[0], a[1], a[2], a[3], a[4], a[5], (a[6] == 0) ? "public" : "random"); - } - } - if (st->txp_adv != 0xFF && st->txp_conn != 0xFF) { - PrintAndLogEx(INFO, "TX power........... advertising %d dBm, connection %d dBm", - ble_level_to_dbm(st->txp_adv), ble_level_to_dbm(st->txp_conn)); - } -} - -// One CMD_PM5_BWM_BLE round trip. Prints the status on success unless quiet. -static int ble_action(uint8_t action, const uint8_t *arg, size_t alen, bool quiet) { - uint8_t payload[1 + 8] = { action }; - if (alen > sizeof(payload) - 1) { - return PM3_EINVARG; - } - if (alen) { - memcpy(&payload[1], arg, alen); - } - clearCommandBuffer(); - SendCommandNG(CMD_PM5_BWM_BLE, payload, 1 + alen); - PacketResponseNG resp; - // Up to a dozen module round trips behind one reply, plus a light-sleep wake. - if (WaitForResponseTimeout(CMD_PM5_BWM_BLE, &resp, 8000) == false) { - PrintAndLogEx(WARNING, "command timeout (is this a PM5? over BLE, a pairing or on/off change drops your own link)"); - return PM3_ETIMEOUT; - } - if (resp.status == PM3_ENOTIMPL) { - PrintAndLogEx(WARNING, "firmware built without the BWM link"); - return resp.status; - } - if (resp.status != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "module refused or did not answer (%s)", (resp.status == PM3_ETIMEOUT) ? "timeout" : "error"); - return resp.status; - } - if (resp.length < sizeof(bwm_ble_status_t)) { - PrintAndLogEx(FAILED, "short reply (%u bytes)", resp.length); - return PM3_EFAILED; - } - if (quiet == false) { - ble_print_status((const bwm_ble_status_t *)resp.data.asBytes); - } - return PM3_SUCCESS; -} - -static int CmdBwmBleStatus(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm ble status", - "Show the module's BLE settings: on/off, name, address, pairing and passkey,\n" - "bonded devices, TX power.", - "hw bwm ble status"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - return ble_action(BWM_BLE_ACTION_STATUS, NULL, 0, false); -} - -static int ble_set_enable(const char *Cmd, bool on) { - CLIParserContext *ctx; - CLIParserInit(&ctx, on ? "hw bwm ble on" : "hw bwm ble off", - "Switch the module's BLE radio on or off. Persisted on the module, applied at\n" - "once. Off means nothing can connect over BLE at all; the PM5 stays reachable\n" - "over USB (and WiFi if configured). Needs a BWM firmware with the BLE switch.\n" - _YELLOW_("Over BLE, `off` cuts your own connection."), - on ? "hw bwm ble on" : "hw bwm ble off"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - uint8_t v = on ? 1 : 0; - return ble_action(BWM_BLE_ACTION_ENABLE, &v, 1, false); -} - -static int CmdBwmBleOn(const char *Cmd) { - return ble_set_enable(Cmd, true); -} - -static int CmdBwmBleOff(const char *Cmd) { - return ble_set_enable(Cmd, false); -} - -static int CmdBwmBlePairing(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm ble pairing [on|off] [-k ] - char verb[16] = {0}; - int consumed = 0; - sscanf(Cmd, "%15s%n", verb, &consumed); - bool on = (strcmp(verb, "on") == 0); - bool off = (strcmp(verb, "off") == 0); - const char *rest = (on || off) ? Cmd + consumed : Cmd; - - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm ble pairing", - "Require pairing before a BLE client can use the device. The module ships with\n" - "pairing " _RED_("off") ": anyone in range can connect and run commands. With it on, a\n" - "client must pair once with the 6-digit passkey (LE Secure Connections, MITM)\n" - "and the data characteristic only works over the encrypted link; paired\n" - "(bonded) devices reconnect without the key until you forget them.\n" - "Both settings persist on the module. A change of on/off restarts the BLE\n" - "stack, which " _YELLOW_("drops a connected client - reconnect (and pair) afterwards.") "\n" - "The factory passkey is 123456; set your own.", - "hw bwm ble pairing on --> require pairing\n" - "hw bwm ble pairing on -k 482913 --> require pairing with this passkey\n" - "hw bwm ble pairing -k 482913 --> change the passkey only\n" - "hw bwm ble pairing off --> open access again"); - void *argtable[] = { - arg_param_begin, - arg_str0("k", "key", "<6 digits>", "passkey a client must enter"), - arg_param_end - }; - CLIExecWithReturn(ctx, rest, argtable, true); - uint8_t key[8] = {0}; - int keylen = 0; - int kres = CLIParamStrToBuf(arg_get_str(ctx, 1), key, sizeof(key) - 1, &keylen); - CLIParserFree(ctx); - if (kres) { - PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); - return PM3_EINVARG; - } - - if (keylen) { - bool ok = (keylen == 6); - for (int i = 0; ok && i < 6; i++) { - ok = isdigit(key[i]); - } - if (ok == false) { - PrintAndLogEx(WARNING, "the passkey must be exactly 6 digits"); - return PM3_EINVARG; - } - int res = ble_action(BWM_BLE_ACTION_KEY, key, 6, (on || off)); - if (res != PM3_SUCCESS) { - return res; - } - if (!on && !off) { - PrintAndLogEx(SUCCESS, "passkey set"); - return PM3_SUCCESS; - } - } else if (!on && !off) { - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") ", " _YELLOW_("off") " and/or " _YELLOW_("-k <6 digits>")); - return PM3_EINVARG; - } - uint8_t v = on ? 1 : 0; - int res = ble_action(BWM_BLE_ACTION_PAIRING, &v, 1, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "pairing %s; the BLE stack is restarting, a connected client is dropped", on ? _GREEN_("required") : _YELLOW_("not required")); - } - return res; -} - -static int CmdBwmBleForget(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm ble forget", - "Remove bonded (paired) devices from the module, so they must pair again with\n" - "the passkey. Indexes are the ones `hw bwm ble status` lists.", - "hw bwm ble forget --all\n" - "hw bwm ble forget -i 0"); - void *argtable[] = { - arg_param_begin, - arg_int0("i", "idx", "", "index of the bonded device to remove"), - arg_lit0(NULL, "all", "remove all bonded devices"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - int idx = arg_get_int_def(ctx, 1, -1); - bool all = arg_get_lit(ctx, 2); - CLIParserFree(ctx); - if ((all && idx >= 0) || (!all && idx < 0)) { - PrintAndLogEx(WARNING, "specify either " _YELLOW_("-i ") " or " _YELLOW_("--all")); - return PM3_EINVARG; - } - if (idx > 254) { - PrintAndLogEx(WARNING, "index out of range"); - return PM3_EINVARG; - } - uint8_t v = all ? 0xFF : (uint8_t)idx; - return ble_action(BWM_BLE_ACTION_FORGET, &v, 1, false); -} - -static int CmdBwmBleTxPower(const char *Cmd) { - CLIParserContext *ctx; - CLIParserInit(&ctx, "hw bwm ble txpower", - "Set the module's BLE transmit power for advertising and/or connections.\n" - "Steps of 3 dB from -24 to 18 dBm, plus 20. Lower saves a little battery and\n" - "shrinks the range at which the device can be found. Persisted on the module.", - "hw bwm ble txpower -a 0 -c 0 --> 0 dBm for both\n" - "hw bwm ble txpower -a -6 --> quieter advertising only"); - void *argtable[] = { - arg_param_begin, - arg_int0("a", "adv", "", "advertising power"), - arg_int0("c", "conn", "", "connection power"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - bool has_adv = (arg_get_int_count(ctx, 1) > 0); - bool has_conn = (arg_get_int_count(ctx, 2) > 0); - int adv = arg_get_int_def(ctx, 1, 0); - int conn = arg_get_int_def(ctx, 2, 0); - CLIParserFree(ctx); - if ((has_adv == false) && (has_conn == false)) { - PrintAndLogEx(WARNING, "specify " _YELLOW_("-a ") " and/or " _YELLOW_("-c ")); - return PM3_EINVARG; - } - int la = has_adv ? ble_dbm_to_level(adv) : 0; - int lc = has_conn ? ble_dbm_to_level(conn) : 0; - if (la < 0 || lc < 0) { - PrintAndLogEx(WARNING, "valid values: -24, -21, ... 15, 18, 20 dBm"); - return PM3_EINVARG; - } - int res = PM3_SUCCESS; - if (has_adv) { - uint8_t v[2] = { 0, (uint8_t)la }; - res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, has_conn); - } - if (res == PM3_SUCCESS && has_conn) { - uint8_t v[2] = { 1, (uint8_t)lc }; - res = ble_action(BWM_BLE_ACTION_TXPOWER, v, 2, false); - } - return res; -} - -static int CmdHelpBwmBle(const char *Cmd); -static command_t BwmBleCommandTable[] = { - {"help", CmdHelpBwmBle, AlwaysAvailable, "This help"}, - {"status", CmdBwmBleStatus, IfBwm, "Show BLE settings: on/off, pairing, bonded devices, TX power"}, - {"on", CmdBwmBleOn, IfBwm, "Switch BLE on (persisted)"}, - {"off", CmdBwmBleOff, IfBwm, "Switch BLE off (persisted) - nothing can connect"}, - {"pairing", CmdBwmBlePairing, IfBwm, "Require pairing with a passkey, set the passkey"}, - {"forget", CmdBwmBleForget, IfBwm, "Remove bonded devices"}, - {"txpower", CmdBwmBleTxPower, IfBwm, "Set advertising / connection TX power"}, - {NULL, NULL, NULL, NULL} -}; - -static int CmdHelpBwmBle(const char *Cmd) { - (void)Cmd; - CmdsHelp(BwmBleCommandTable); - return PM3_SUCCESS; -} - -static int CmdBwmBle(const char *Cmd) { - clearCommandBuffer(); - return CmdsParse(BwmBleCommandTable, Cmd); -} - -static command_t BwmCommandTable[] = { - {"help", CmdHelpBwm, AlwaysAvailable, "This help"}, - {"autooff", CmdBwmAutoOff, IfBwm, "Show/set auto power-off (USB unplug, idle on battery)"}, - {"ble", CmdBwmBle, IfBwm, "{ BLE: on/off, pairing, bonded devices, TX power... }"}, - {"charge", CmdBwmCharge, IfBwm, "Enable/disable battery charging (one-shot)"}, - {"name", CmdBwmName, IfBwm, "Get/set the BWM BLE advertising name"}, - {"powersave", CmdBwmPowerSave, IfBwm, "Show/set the BWM power-save switch (DFS, light sleep, slow adv)"}, - {"setcap", CmdBwmSetCap, IfBwm, "Set fuel-gauge design capacity (run once after battery change)"}, - {"upgrade", CmdBWMUpgrade, IfBwm, "Reflash BWM (ESP32) firmware over the BWM link, no header"}, - {"vchg", CmdBwmVchg, IfBwm, "Set charger charge-voltage target (default 4100 mV)"}, - {"wifi", CmdBWMWifi, IfBwm, "Bring up WiFi (STA + TCP server) for a tcp: connection"}, - {"wifipower", CmdBwmWifiPower, IfBwm, "WiFi fully off, or the modem power-save type (none/min/max)"}, - {NULL, NULL, NULL, NULL} -}; - -static int CmdHelpBwm(const char *Cmd) { - (void)Cmd; - CmdsHelp(BwmCommandTable); - return PM3_SUCCESS; -} - -int CmdBwm(const char *Cmd) { - clearCommandBuffer(); - return CmdsParse(BwmCommandTable, Cmd); -} +# Proxmark5 BWM — Battery, BLE & WiFi + +The **Battery / Wireless Module (BWM)** adds a battery + charger and an ESP32 that +bridges the Proxmark5 to **BLE** and **WiFi**. Everything below is **PM5-only** and +is compiled in with the BWM platform extra. + +## Contents + +- [Build](#build) +- [1. Battery / BWM control](#1-battery--bwm-control) +- [2. BLE](#2-ble) +- [3. WiFi](#3-wifi) +- [4. Update BWM firmware](#4-update-bwm-firmware) +- [Notes](#notes) + +--- + +## Build + +Build the firmware with the BWM extra — this enables `WITH_BWM_FORWARD` (the +UART4 / `app_com` driver, battery telemetry, and BLE/WiFi forwarding): + +``` +make clean +make PLATFORM=PM5 PLATFORM_EXTRAS=BWM +make client # or your usual client build +``` + +Or set it persistently in `Makefile.platform`: + +``` +PLATFORM=PM5 +PLATFORM_EXTRAS=BWM +``` + +> [!NOTE] +> Without `PLATFORM_EXTRAS=BWM` the firmware builds a plain PM5 with **none** of the +> battery / BLE / WiFi commands below. + +--- + +## 1. Battery / BWM control + +These run over any active connection — USB, BLE, or WiFi. + +### `hw status` — battery + charger telemetry + +``` +[usb] pm3 --> hw status +``` + +The **Battery / BWM** section reports the **AW32001** charger (power path, fault, +charge state, input limit, charge current/voltage/enable) and the **BQ27427** fuel +gauge (state-of-charge %, voltage, current, remaining/full capacity, temperature, +health). + +### `hw bwm setcap` — set fuel-gauge design capacity + +Program the BQ27427 **Design Capacity** for the fitted cell. + +| Argument | Description | +| ------------- | -------------------------------------- | +| `--cap ` | Design capacity in mAh (default `500`) | + +``` +hw bwm setcap # set design capacity to the default 500 mAh +hw bwm setcap --cap 500 # set design capacity to 500 mAh +``` + +> [!WARNING] +> Run this **once** after fitting or replacing the battery. Running it repeatedly +> triggers a gauge config-update and disrupts the Impedance Track learning cycle. + +### `hw bwm charge` — enable/disable charging (one-shot) + +Clears/sets the AW32001E charge-enable bit (`CEB`, `REG01[3]`). + +| Sub-action | Description | +| ---------- | ----------------- | +| `on` | Enable charging | +| `off` | Disable charging | + +``` +hw bwm charge on # enable charging +hw bwm charge off # disable charging +``` + +> [!NOTE] +> **One-shot:** the charger watchdog reverts this after ~160 s unless serviced, so +> charging may stop on its own. Use it to nudge a top-up. + +### `hw bwm vchg` — set charge-voltage limit + +Sets the AW32001E charge-voltage regulation target (`VBAT_REG`, `REG04[7:2]`). +Lowering it below 4.2 V reduces top-of-charge stress and extends cell life. + +| Argument | Description | +| ----------- | ----------------------------------------------------------- | +| `--mv ` | Charge voltage in mV (default `4100`, clamped `3600`..`4200`) | + +``` +hw bwm vchg # set the default 4100 mV target (-> 4.095 V) +hw bwm vchg --mv 4200 # set 4200 mV +``` + +The value snaps to the nearest 15 mV hardware step, and the command reports the +voltage actually applied (e.g. `4100` → `4.095 V`; `4110` would be the next step). + +> [!NOTE] +> The firmware applies the `4100` mV default (4.095 V) at **every boot** — the +> AW32001E's own power-on default is 4.2 V. It is a runtime register write, but +> because the boot config disables the charger watchdog the value then holds until +> the next power cycle (which re-applies it), so you don't need to re-run it per +> charge. + +### `hw bwm autooff` — auto power-off on USB unplug + +Toggles automatic power-off when the PM5 is unplugged from USB. **Default is `on`:** +the board powers down after USB is removed so a BWM-equipped PM5 doesn't silently +drain the battery. Button power-on is unaffected. + +| Sub-action | Description | +| ---------- | ----------------------- | +| `on` | Enable auto power-off | +| `off` | Disable auto power-off | + +``` +hw bwm autooff off # disable auto power-off +hw bwm autooff on # re-enable auto power-off +``` + +> [!NOTE] +> **Runtime only** — resets to `on` at each boot. Disable it for an uninterrupted +> move from USB to standalone / BLE / WiFi use on battery. For regular standalone / +> BLE / WiFi use on battery, one can just turn it on when needed, no need to touch +> that setting. + +--- + +## 2. BLE + +The BWM advertises as: + +| Property | Value | +| --------- | ---------------------------------------------- | +| Name | `Proxmark5` | +| Address | `58:2A:BD:34:F1:82` (LE Public, Espressif OUI) | +| Service | `0xAE86` (16-bit) | +| Data char | `0xAE88` (`WRITE` / `WRITE_NO_RSP` / `NOTIFY`) | +| Security | none (plaintext GATT, no bonding) | + +> [!NOTE] +> `58:2A:BD:34:F1:82` is just an example — each module has its own address. Find +> yours with `btmgmt find`, or use the bridge's name-scan (`-n Proxmark5`), which +> avoids needing the address at all. + +There are three ways to connect: a **native transport** (Linux), a **cross-platform +Python bridge** (Linux / macOS / Windows / WSL / iOS), and a **bridge app** on Android +([2.4](#24-android--termux--ble-bridge-app)). + +### `hw bwm name` — get/set the BLE advertising name + +Reads or changes the name the BWM advertises over BLE. With no argument it prints +the current name; `--set` changes it (1–31 characters). + +| Argument | Description | +| --------------- | ---------------------------------------------------- | +| `--set ` | New BLE name, 1–31 chars; omit to read current name | + +``` +hw bwm name # show the current BLE name +hw bwm name --set MyPM5 # set the BLE name to 'MyPM5' +``` + +The name is stored on the BWM in NVS, so it persists across power cycles. The BWM +applies the advertised name at BLE start-up, so setting a name reboots the BWM to +make it take effect — this briefly drops a BLE or WiFi connection, so reconnect +after a few seconds. Over USB the reboot is not noticeable, since the client stays +connected to the PM5 while only the BWM's ESP restarts. + +> [!NOTE] +> If a device is connected over BLE when you change the name, the running +> advertisement can't change mid-connection; the new name shows up on the next +> scan after the reboot. + +### 2.1 Native BLE transport — Linux only, no bridge + +Uses a raw L2CAP/ATT socket — no `bleak`, no `bluetoothd` daemon dependency. +Needs the Bluetooth dev headers at build time: + +``` +sudo apt install libbluetooth-dev +make client # rebuild so HAVE_BLUEZ is picked up +``` + +Then connect by address: + +``` +./pm3 -p ble:58:2A:BD:34:F1:82 +``` + +On success you'll see e.g. `BLE connected, MTU 512, char handle 0x0014`. + +### 2.2 BLE bridge — cross-platform (`pm5_ble_bridge.py`) + +Requires Python 3 and `bleak` (`pip install bleak`). It bridges the BWM's BLE SPP +to a PTY or a TCP socket that the pm3 client then opens. + +> [!IMPORTANT] +> Run the bridge on the machine that has the **Bluetooth radio**. + +Common options: + +| Option | Description | +| --------------------- | ------------------------------------------------- | +| `-n, --name ` | Advertised name to scan for (default `Proxmark5`) | +| `-a, --address ` | Connect by address instead of scanning by name | +| `--dump` | Hexdump traffic both directions (debug) | +| `-v, --verbose` | Verbose logging | + +**a) PTY** (Linux/macOS) — simplest, one process: + +``` +python3 pm5_ble_bridge.py --pty # default link /tmp/pm5-ble +./pm3 -p /tmp/pm5-ble +``` + +**b) TCP listener** — bridge listens, client connects in: + +``` +python3 pm5_ble_bridge.py --tcp 7777 # or HOST:PORT +./pm3 -p tcp:127.0.0.1:7777 +``` + +**c) Outbound TCP** (`--connect`) — bridge dials **out** to a listener. Pairs with +the client's `--wait` mode ([2.3](#23-client-listen-mode--pm3----wait)) and crosses +the WSL2 NAT boundary: + +``` +python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +``` + +**d) Relay only** (no BLE) — TCP listener ↔ PTY, for chaining: + +``` +python3 pm5_ble_bridge.py --relay --listen 7777 --pty +``` + +> [!NOTE] +> **Windows / WSL:** run the bridge on Windows (where the radio is) with `py`, and +> let only TCP cross into WSL. + +### 2.3 Client listen mode — `pm3 … --wait` + +With a `tcp:` port, `--wait` makes the client **bind / listen** and wait for an +incoming connection instead of dialing out. Start the client first, then point the +bridge at it with `--connect`. This removes the relay/PTY hop. + +``` +# window 1 — client listens (blocks until something connects) +./pm3 -p tcp:127.0.0.1:7777 --wait + +# window 2 — bridge dials in (on the machine with the radio) +python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +``` + +> [!NOTE] +> For a plain **serial** port, `--wait` keeps its original meaning: wait ~20 s for +> the device node to appear. + +### 2.4 Android — Termux + BLE bridge app + +Termux has no Bluetooth access, so a bridge app exposes the BWM's BLE characteristic +as a local TCP port that the client then opens — same idea as +[termux_notes.md](../../termux_notes.md), just BLE instead of classic Bluetooth. +Tested with the paid +[BT/USB/TCP Bridge](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) +app, which lets you pick the GATT characteristic; the free version works too but is +limited to 10 minutes per session (the limit resets after quitting the app). + +1. Build the client in Termux (see [termux_notes.md](../../termux_notes.md)). +2. In the bridge app: + +| Setting | Value | +| ---------------- | ----------------------------------------------------------------- | +| Device A | Start TCP server (default port `54321`) | +| Device B | Connect to BLE device → `Proxmark5` | +| Characteristic | the last one: service `0000ae86-…`, characteristic `0000ae88-…`, for RX+TX | + +3. In Termux, connect over the local port: + +``` +./client/proxmark3 tcp:localhost:54321 +``` + +No pairing is needed (the BWM has no BLE security). The same app also does classic +Bluetooth, so one setup covers a Blueshark-equipped Proxmark3 too. + +> [!NOTE] +> If you would rather not use a bridge app, put the phone in hotspot mode and use +> WiFi instead ([3](#3-wifi-sta--tcp-server)): the client then connects straight to +> the BWM's TCP server, with no app in between. + +--- + +## 3. WiFi (STA + TCP server) + +`hw bwm wifi` joins your WiFi network as a **station** and starts a **TCP server** on +the BWM. You then connect the client over plain TCP. Run `hw bwm wifi` over an +existing link (USB, or an existing BLE connection). Use `hw bwm wifi status` to check an +existing connection without touching the config. + +### 3.1 Bring up WiFi + +``` +hw bwm wifi --ssid [--pwd ] [--port ] [--hostname ] +``` + +| Argument | Description | +| ------------------- | ---------------------------------------- | +| `--ssid ` | WiFi network to join **(required)** | +| `--pwd ` | WiFi password (omit for an open network) | +| `--port ` | TCP server listen port (default `18888`) | +| `--hostname ` | DHCP hostname (default `Proxmark5`) | + +Two sub-actions take no other arguments and are positional (no dashes): +`hw bwm wifi status` and `hw bwm wifi stop` (see 3.3 and 3.4). + +``` +hw bwm wifi --ssid Home --pwd secret +hw bwm wifi --ssid Home --pwd secret --port 9000 --hostname pm5-lab +hw bwm wifi --ssid OpenGuestWiFi # open network +``` + +The join can take ~15 s. On success it prints the assigned IP and the connect +strings: + +``` +[+] BWM on WiFi at 192.168.1.77 +[?] Connect with: pm3 -p tcp:192.168.1.77:18888 +[?] Or by name (router-dependent): pm3 -p tcp:pm5-lab:18888 +``` + +### 3.2 Connect over WiFi + +``` +./pm3 -p tcp:192.168.1.77:18888 +``` + +> [!NOTE] +> Connecting **by hostname** works only if your router registers DHCP client names +> in its local DNS (some need a suffix like `.lan` or `.home`; some +> don't do it at all). BWM firmware with mDNS also answers `.local`, e.g. +> `./pm3 -p tcp:pm5-lab.local:18888`; this needs an mDNS-capable resolver on the host +> (Avahi/nss-mdns or systemd-resolved on Linux; built in on macOS and Windows 10+). + +### 3.3 Check WiFi status — `hw bwm wifi status` + +Queries the BWM's current connection state and IP **without** reconnecting or +changing the WiFi config. Handy to confirm a join actually completed — the +bring-up occasionally reports failure if the DHCP lease lands late, even though +the STA connected a moment later. + +``` +hw bwm wifi status +``` + +``` +[+] BWM WiFi connected, IP 192.168.1.77 +[?] Connect with: pm3 -p tcp:192.168.1.77: +``` + +> [!NOTE] +> "Connected" here means the STA has a DHCP lease (a usable IP). If it reports +> not connected right after a bring-up, wait a few seconds and re-check — the +> lease may still be in flight. + +### 3.4 Stop WiFi — `hw bwm wifi stop` + +Tears down the WiFi station and TCP server and returns the BWM to **BLE-only**. +Run it over an existing link (USB or BLE); it does not need any other arguments. + +``` +hw bwm wifi stop +``` + +> [!NOTE] +> If you issue `hw bwm wifi stop` over the **WiFi** connection itself, that connection +> drops as the TCP server goes away — reconnect over USB or BLE afterwards. + +--- + +## 4. Update BWM firmware — `hw bwm upgrade` + +Reflashes the BWM (ESP32-C2) firmware **over the existing BWM link** — no 5-pin +header, no soldering, no `esptool`. Run it over whatever link you already have +(USB or BLE). It updates a BWM that still responds; it **cannot** recover a fully +bricked one — that still needs the production 5-pin header + `esptool`. + +``` +hw bwm upgrade -f [--delay ] +``` + +| Argument | Description | +| -------------- | ------------------------------------------------------------- | +| `-f`, `--file` | ESP32-C2 firmware image `.bin` **(required)** | +| `--delay ` | Per-chunk delay pacing the slow AT32-ESP UART (default `20`) | + +The client refuses to flash anything that is not an ESP32-C2 app image (it checks +the ESP image magic `0xE9` and `chip_id 0x000C`), so a wrong-chip image can't +brick the module. + +It prints the running version first, uploads the image, then reboots the ESP into +the new image and confirms by reading the version back: + +``` +[=] Current BWM firmware..... v1.2.3 +[=] Uploading 812345 bytes of ESP firmware over the BWM link... +[=] BWM rebooting into the new image (link drops briefly)... +[+] BWM firmware updated: v1.2.3 -> v1.3.0 +``` + +> [!NOTE] +> There is **no resume**: a chunk dropped mid-transfer restarts the whole upload, +> and the client retries automatically (up to 6 attempts). If uploads keep failing +> on the slow link, raise the pacing, e.g. `--delay 40`. + +> [!NOTE] +> The link drops briefly while the ESP reboots into the new image. Over BLE the +> post-reboot version read sometimes can't complete even though the flash +> succeeded — reconnect and run `hw status` to confirm the running version. + +--- + +## Notes + +- Bulk transfers over BLE/WiFi (`lf read`, `mem dump`, trace download) are paced by + the BWM flow control so they don't drop — expect them to be **slower than USB**. +- COTAG / large realtime LF reads use a separate streaming + path and are **not** covered by this flow control. +- All BWM commands are **PM5-only** and require the firmware built with + `PLATFORM_EXTRAS=BWM`. From 63063bd030ae0e9cd196068bdf884d4225577fb1 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 2 Oct 2026 15:05:19 +0200 Subject: [PATCH 04/15] tune docs for default port 18888 --- client/pm5_ble_bridge.py | 4 ++-- doc/commands.json | 4 ++-- doc/md/PM5_Start_Here/PM5-BWM-USAGE.md | 26 +++++++++++++++++--------- doc/termux_notes.md | 18 +++++++++--------- 4 files changed, 30 insertions(+), 22 deletions(-) diff --git a/client/pm5_ble_bridge.py b/client/pm5_ble_bridge.py index c110c2355..38b648034 100644 --- a/client/pm5_ble_bridge.py +++ b/client/pm5_ble_bridge.py @@ -17,8 +17,8 @@ # WSL2 without admin, NAT networking: Windows can only make OUTBOUND # connections, but by default localhostForwarding lets Windows reach a WSL # listener at 127.0.0.1:PORT. So: -# WSL: python3 pm5_ble_bridge.py --relay --listen 7777 --pty /tmp/pm5-ble -# Windows: py pm5_ble_bridge.py -n Proxmark5 --connect 127.0.0.1:7777 +# WSL: python3 pm5_ble_bridge.py --relay --listen 18888 --pty /tmp/pm5-ble +# Windows: py pm5_ble_bridge.py -n Proxmark5 --connect 127.0.0.1:18888 # WSL: ./pm3 /tmp/pm5-ble # If localhostForwarding is off, point --connect at WSL's own IP # (WSL: `hostname -I`) instead of 127.0.0.1. diff --git a/doc/commands.json b/doc/commands.json index 7aadd9acc..f56b72dc6 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -11222,7 +11222,7 @@ "notes": [ "hw bwm wifi status -> show connection state + IP", "hw bwm wifi stop -> tear down WiFi, back to BLE-only", - "hw bwm wifi --ssid Home --pwd secret -> bring up, port 7777", + "hw bwm wifi --ssid Home --pwd secret -> bring up, port 18888", "hw bwm wifi --ssid Home --pwd secret --port 9000" ], "offline": false, @@ -11230,7 +11230,7 @@ "-h, --help This help", "--ssid WiFi SSID to join", "--pwd WiFi password (omit for open network)", - "--port TCP server listen port (default 7777)", + "--port TCP server listen port (default 18888)", "--hostname DHCP hostname (default Proxmark5)" ], "usage": "hw bwm wifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ]" diff --git a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md index 752353d94..ddc9a028e 100644 --- a/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md +++ b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md @@ -228,8 +228,8 @@ python3 pm5_ble_bridge.py --pty # default link /tmp/pm5-ble **b) TCP listener** — bridge listens, client connects in: ``` -python3 pm5_ble_bridge.py --tcp 7777 # or HOST:PORT -./pm3 -p tcp:127.0.0.1:7777 +python3 pm5_ble_bridge.py --tcp 18888 # or HOST:PORT +./pm3 -p tcp:127.0.0.1:18888 ``` **c) Outbound TCP** (`--connect`) — bridge dials **out** to a listener. Pairs with @@ -237,13 +237,13 @@ the client's `--wait` mode ([2.3](#23-client-listen-mode--pm3----wait)) and cros the WSL2 NAT boundary: ``` -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +python3 pm5_ble_bridge.py --connect 127.0.0.1:18888 ``` **d) Relay only** (no BLE) — TCP listener ↔ PTY, for chaining: ``` -python3 pm5_ble_bridge.py --relay --listen 7777 --pty +python3 pm5_ble_bridge.py --relay --listen 18888 --pty ``` > [!NOTE] @@ -258,10 +258,10 @@ bridge at it with `--connect`. This removes the relay/PTY hop. ``` # window 1 — client listens (blocks until something connects) -./pm3 -p tcp:127.0.0.1:7777 --wait +./pm3 -p tcp:127.0.0.1:18888 --wait # window 2 — bridge dials in (on the machine with the radio) -python3 pm5_ble_bridge.py --connect 127.0.0.1:7777 +python3 pm5_ble_bridge.py --connect 127.0.0.1:18888 ``` > [!NOTE] @@ -283,14 +283,18 @@ limited to 10 minutes per session (the limit resets after quitting the app). | Setting | Value | | ---------------- | ----------------------------------------------------------------- | -| Device A | Start TCP server (default port `54321`) | +| Device A | Start TCP server, use client default port:`18888` | | Device B | Connect to BLE device → `Proxmark5` | | Characteristic | the last one: service `0000ae86-…`, characteristic `0000ae88-…`, for RX+TX | -3. In Termux, connect over the local port: +1. In Termux, connect over the local port: ``` -./client/proxmark3 tcp:localhost:54321 +./client/proxmark3 tcp:localhost:18888 +``` +Or, as we're using the default port, just +``` +./client/proxmark3 tcp:localhost ``` No pairing is needed (the BWM has no BLE security). The same app also does classic @@ -346,6 +350,10 @@ strings: ``` ./pm3 -p tcp:192.168.1.77:18888 ``` +Or, as we're using the default port, just +``` +./pm3 -p tcp:192.168.1.77 +``` > [!NOTE] > Connecting **by hostname** works only if your router registers DHCP client names diff --git a/doc/termux_notes.md b/doc/termux_notes.md index 1c3851320..a2bad3886 100644 --- a/doc/termux_notes.md +++ b/doc/termux_notes.md @@ -150,11 +150,11 @@ Install [this free TCPUART app](https://play.google.com/store/apps/details?id=co The app lets you choose the baudrate. Default value (115 200 baud) is fine. Plug the PM3 in and click connect. -Set the toggle in server mode and choose a random port not used by system (e.g. 4321) and start the server. +Set the toggle in server mode and choose a random port not used by system (client default port is 18888) and start the server. Alternatively, use the [paid version of the BT/USB/TCP Bridge app](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) which includes USB bridge as well. -In this app, select TCP server as 'Device A' and choose an unused port (e.g. 4321). +In this app, select TCP server as 'Device A' and choose an unused port (client default port is 18888). Choose your registered PM3 device as 'Device B' -> 'Connect to USB device'. Ensure 'Retransmission' is set to 'both ways'. It is possible to record the config as autostart, cf 'Settings' -> 'Autostart setting'. @@ -167,7 +167,7 @@ You can download the apk on this website without installing F-Droid. The app lets you choose the baudrate. Default value (115 200 baud) is fine. Plug the PM3 in and click `Connect`. -Choose a random port not used by system (e.g. 4321) and click `Start Server`. +Choose a random port not used by system (client default port is 18888) and click `Start Server`. Note: This app uses foreground service to keep the connection alive, so you can safely put it in the background without suspending the transmission. However, you will see a dummy notification in the status bar which is required for foreground service. @@ -180,7 +180,7 @@ Note: This app uses foreground service to keep the connection alive, so you can Install [this free app](https://play.google.com/store/apps/details?id=masar.bb) or [the paid version](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) (which includes usb bridge) You need to pair the proxmark3 in the Android settings. -In the app, select TCP server as 'Device A' and choose an unused port (e.g. 4321). +In the app, select TCP server as 'Device A' and choose an unused port (client default port is 18888). Choose your registered PM3 device as 'Device B' -> 'Connect to classic Bluetooth device'. Ensure 'Retransmission' is set to 'both ways'. It is possible to record the config as autostart, cf 'Settings' -> 'Autostart setting'. @@ -191,10 +191,10 @@ It is possible to record the config as autostart, cf 'Settings' -> 'Autostart se The Proxmark5 Battery Wireless Module (BWM) uses BLE, not classic Bluetooth. The [paid version of the BT/USB/TCP Bridge app](https://play.google.com/store/apps/details?id=masar.bluetoothbridge.pro) handles it (the free version works with 10 minute time limit, can be reset by restarting the app): -In the app, select TCP server as 'Device A' (default port 54321). +In the app, select TCP server as 'Device A', port 18888 to use the client default port. Choose 'Device B' -> 'Connect to BLE device' -> `Proxmark5`. When asked for the characteristic, choose: service UUID starting with `0000ae86`, characteristic starting with `0000ae88`, for RX+TX. -No pairing is needed. Then connect from Termux as in [TCP connection](#tcp-connection) using port 54321. +No pairing is needed. Then connect from Termux as in [TCP connection](#tcp-connection) using port 18888. See [PM5-BWM-USAGE.md](md/PM5_Start_Here/PM5-BWM-USAGE.md) for the BWM firmware build flag and the WiFi alternative, which needs no bridge app at all. @@ -252,10 +252,10 @@ proxmark3 udp:localhost:12345 ^[Top](#top) 1. Phone and pm3 are connected, blue led is on and *not* blinking -2. BTUART Tool TCP Server at Port 4321 +2. BTUART Tool TCP Server at Port 18888 3. Using proxmark3 in termux shows the following error message: ``` -$ proxmark3 tcp:localhost:4321 +$ proxmark3 tcp:localhost:18888 [=] Session log /data/data/com.termux/files/home/.suroot /.proxmark3/log_20210519.txt @@ -263,7 +263,7 @@ $ proxmark3 tcp:localhost:4321 [+] loaded from JSON file /data/data/com.termux/files/ho me/.suroot/.proxmark3/preferences.json -Using UART port tcp:localhost:4321 +Using UART port tcp:localhost:18888 [!!] ERROR: cannot communicate with the Proxmark3 ``` From 2e2720a1da10f52a52c258ccd5464fb3a7143bf0 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 11:20:10 +1000 Subject: [PATCH 05/15] PM5: bound usb_write()'s tx-complete wait The two g_tx_completed spin loops in usb_write() had no timeout at all - if the host ever stopped pulling an IN packet while the device still read as enumerated, PM5 would spin forever with no recovery path. Add a spin-iteration bound (not tick-based: g_tx_completed is set from the USB core's own ISR, and the shared ticks timer is routinely stopped by LF/HF code at arbitrary points), matching the existing bounded-wait pattern used elsewhere in this codebase. Co-Authored-By: Claude Sonnet 5 --- common_arm/usb/usb_cdc_at32.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/common_arm/usb/usb_cdc_at32.c b/common_arm/usb/usb_cdc_at32.c index 80c725b98..2723e8569 100644 --- a/common_arm/usb/usb_cdc_at32.c +++ b/common_arm/usb/usb_cdc_at32.c @@ -18,6 +18,13 @@ static otg_core_type otg_core_struct; static usbd_core_type *udev = &(otg_core_struct.dev); static usbd_desc_t vp_desc; +// Spin-wait iteration bound for usb_write()'s tx-complete wait, not a time +// unit - g_tx_completed is set from the USB core's own IN-endpoint ISR, so +// this can't use the shared ticks timer (see ticks_apis.h StartTicks()/ +// StopTicks() callers elsewhere in armsrc - it's routinely stopped by +// LF/HF code at the exact moments a reply may need to go out). +#define USB_TX_COMPLETE_TIMEOUT 2000000 + /** * @brief get device descriptor * @retval usbd_desc @@ -515,10 +522,14 @@ int usb_write(const uint8_t *data, const size_t len) { // wait for send complete cdc_struct_type *pcdc = (cdc_struct_type *)(udev->class_handler->pdata); + uint32_t tx_timeout = 0; while (pcdc->g_tx_completed != 1) { if (usb_check() == false) { return PM3_EIO; } + if (tx_timeout++ > USB_TX_COMPLETE_TIMEOUT) { + return PM3_EIO; + } // working for send to HOST... // Have a cup of tea? } @@ -531,10 +542,14 @@ int usb_write(const uint8_t *data, const size_t len) { if (usb_vcp_send_data(udev, (uint8_t *) data, 0) != SUCCESS) { return PM3_EIO; } + tx_timeout = 0; while (pcdc->g_tx_completed != 1) { if (usb_check() == false) { return PM3_EIO; } + if (tx_timeout++ > USB_TX_COMPLETE_TIMEOUT) { + return PM3_EIO; + } } } From 8faafcebb0f09c1bd4c31bcbf764235be3da7905 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 11:30:25 +1000 Subject: [PATCH 06/15] PM5 CEP: recover from AT32 SPI1 errata, bound all SPI waits 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 --- armsrc/cmd.c | 21 ++++++++- armsrc/pm5_cep.c | 109 ++++++++++++++++++++++++++++++++++++++++------- armsrc/pm5_cep.h | 11 ++++- 3 files changed, 123 insertions(+), 18 deletions(-) diff --git a/armsrc/cmd.c b/armsrc/cmd.c index 7e9edb1e3..a2d210a0d 100644 --- a/armsrc/cmd.c +++ b/armsrc/cmd.c @@ -22,6 +22,11 @@ #endif #ifdef WITH_CEP #include "pm5_cep.h" +#else +// receive_ng_internal()'s `cep` parameter is always false without WITH_CEP, +// so this is never actually called - just keeps those call sites free of +// per-site #if defined(WITH_CEP) guards. +static inline void cep_spi_resync(void) {} #endif #include "crc16.h" #include "string.h" @@ -91,6 +96,9 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const v if (g_reply_via_cep) { #if defined(WITH_CEP) resultcep = cep_spi_write_sync((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); + if (resultcep != PM3_SUCCESS) { + cep_spi_resync(); + } #else return PM3_EDEVNOTSUPP; #endif @@ -173,6 +181,9 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const if (g_reply_via_cep) { #if defined(WITH_CEP) resultcep = cep_spi_write_sync((uint8_t *)tx, txBufferNGLen); + if (resultcep != PM3_SUCCESS) { + cep_spi_resync(); + } #else return PM3_EDEVNOTSUPP; #endif @@ -214,6 +225,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da } if (bytes != sizeof(PacketCommandNGPreamble)) { + if (cep) cep_spi_resync(); return PM3_EIO; } @@ -225,27 +237,33 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da if (rx->magic == COMMANDNG_PREAMBLE_MAGIC) { // New style NG command if (length > PM3_CMD_DATA_SIZE) { + if (cep) cep_spi_resync(); return PM3_EOVFLOW; } // Get the core and variable length payload bytes = read_ng((uint8_t *)&rx_raw.data, length); if (bytes != length) { + if (cep) cep_spi_resync(); return PM3_EIO; } // Get the postamble bytes = read_ng((uint8_t *)&rx_raw.foopost, sizeof(PacketCommandNGPostamble)); if (bytes != sizeof(PacketCommandNGPostamble)) { + if (cep) cep_spi_resync(); return PM3_EIO; } - // Check CRC, accept MAGIC as placeholder + // Check CRC, accept MAGIC as placeholder - a mismatch here is the + // AT32 errata's own recommended trigger to reset SPI (see + // cep_spi_resync()'s comment). rx->crc = rx_raw.foopost.crc; if (rx->crc != COMMANDNG_POSTAMBLE_MAGIC) { uint8_t first, second; compute_crc(CRC_14443_A, (uint8_t *)&rx_raw, sizeof(PacketCommandNGPreamble) + length, &first, &second); if ((first << 8) + second != rx->crc) { + if (cep) cep_spi_resync(); return PM3_EIO; } } @@ -264,6 +282,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da } else { uint64_t arg[3] = {0}; if (length < sizeof(arg)) { + if (cep) cep_spi_resync(); return PM3_EIO; } diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c index d3a976f3f..ac9f425dc 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -47,6 +47,13 @@ #define CEP_SPI_BYTE_TIMEOUT 100000 // spin-wait iterations per byte (matches source) #define CEP_SPI_RESPONSE_TIMEOUT_US (1000 * 1000) // 1s, matches source #define CEP_HANDSHAKE_RX_TIMEOUT_MS 2000 // bail out of the receive loop rather than ever hang the main loop +#define CEP_HANDSHAKE_REPLY_MAX_RETRIES 3 // bound the stall-recovery loop below - still-attached isn't still-working forever + +// 0x55 filler the Flipper sends while its own SPI poll finds nothing new - +// discard it so the real length header is recognized as soon as it starts, +// instead of ever reading a 0x55 byte as (part of) a frame length. +#define CEP_SYNC_BYTE 0x55 +#define CEP_SYNC_MAX_DISCARD 600 static bool s_cep_active = false; // handshake completed, SPI transport live @@ -155,6 +162,20 @@ static void cep_spi_init(void) { spi_enable(SPI1, TRUE); } +// AT32F435/437 errata ES0003, "CS falling edge not synchronized in SPI +// slave hardware CS mode": the peripheral's internal clock sync isn't +// guaranteed to reset on every CS edge, so a bad sync can persist across +// transactions. Artery's documented recovery is to detect the corruption +// (we already do, via the NG frame's CRC) and reset SPI before retrying - +// a register re-init alone isn't enough, the peripheral needs resetting +// through the clock/reset controller to actually clear that state. +void cep_spi_resync(void) { + spi_enable(SPI1, FALSE); + crm_periph_reset(CRM_SPI1_PERIPH_RESET, TRUE); + crm_periph_reset(CRM_SPI1_PERIPH_RESET, FALSE); + cep_spi_init(); +} + void cep_init(void) { cep_usart_init(); cep_spi_init(); @@ -208,13 +229,23 @@ static bool cep_do_handshake(void) { uint8_t response[] = {0x04, 0x00, 'y', 'e', 's', 0x00}; for (size_t i = 0; i < sizeof(response); i++) { uint32_t wait_start = GetTicks(); + int recovery_attempts = 0; while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { if (GetTicks() - wait_start > CEP_SPI_RESPONSE_TIMEOUT_US) { + // Bound this: "still attached" isn't "still working" forever, + // and I2C_BufferReadRaw() needs the ticks timer running like + // every other call site (see cep_attach_poll()'s comment). + if (++recovery_attempts > CEP_HANDSHAKE_REPLY_MAX_RETRIES) { + return false; + } + StartTicks(); + I2C_init(true); uint8_t cc_ctrl_data; bool ret = I2C_BufferReadRaw(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); - if (ret && ((cc_ctrl_data >> 6 & 0x03) == 0)) { - return false; // disconnected mid-reply + if (!ret || ((cc_ctrl_data >> 6 & 0x03) == 0)) { + return false; // disconnected mid-reply, or can't tell - bail either way } + wait_start = GetTicks(); } } spi_i2s_data_transmit(SPI1, response[i]); @@ -277,16 +308,33 @@ void cep_attach_poll(void) { // SPI NG-frame transport (verbatim from the unit test - already correct) // --------------------------------------------------------------------------- +static bool cep_spi_read_byte(uint8_t *out) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) == RESET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return false; + } + } + *out = spi_i2s_data_receive(SPI1); + return true; +} + bool cep_spi_data_available(void) { uint8_t len_header[2] = {0x00}; - for (size_t i = 0; i < sizeof(len_header); ++i) { - uint64_t timeout = 0; - while (spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) == RESET) { - if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { - return false; - } + size_t discarded = 0; + while (1) { + if (!cep_spi_read_byte(&len_header[0])) { + return false; } - len_header[i] = spi_i2s_data_receive(SPI1); + if (len_header[0] != CEP_SYNC_BYTE) { + break; + } + if (++discarded > CEP_SYNC_MAX_DISCARD) { + return false; + } + } + if (!cep_spi_read_byte(&len_header[1])) { + return false; } uint16_t data_len = (len_header[1] << 8) | len_header[0]; if (data_len > PM3_CMD_DATA_SIZE * 2) { @@ -308,25 +356,56 @@ uint32_t cep_spi_read_ng(uint8_t *data, size_t len) { return len; } +// PM5 is the SPI slave: TDBE only clears when the master is actively +// clocking, which happens on the Flipper's own ~20-120ms poll schedule, +// completely async to when PM5 has a reply ready. An unbounded wait here +// hangs the main loop forever (no recovery, not even a watchdog reset) the +// moment a reply is queued between two master polls - bound every wait so +// a slow/absent master degrades to a dropped reply, not a dead device. +static bool cep_spi_wait_tdbe(void) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return false; + } + } + return true; +} + int cep_spi_write_sync(uint8_t *data, size_t len) { - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe()) { + return PM3_EIO; + } spi_i2s_data_transmit(SPI1, len & 0xFF); - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe()) { + return PM3_EIO; + } spi_i2s_data_transmit(SPI1, (len >> 8) & 0xFF); for (size_t i = 0; i < len; ++i) { - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe()) { + return PM3_EIO; + } spi_i2s_data_transmit(SPI1, data[i]); } // Two trailing zero bytes: the agreed "no more data" idle marker. - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe()) { + return PM3_EIO; + } spi_i2s_data_transmit(SPI1, 0x00); - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe()) { + return PM3_EIO; + } spi_i2s_data_transmit(SPI1, 0x00); - while (spi_i2s_flag_get(SPI1, SPI_I2S_BF_FLAG) == SET); + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_BF_FLAG) == SET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return PM3_EIO; + } + } return PM3_SUCCESS; } diff --git a/armsrc/pm5_cep.h b/armsrc/pm5_cep.h index fafbd33d1..d040bd1ef 100644 --- a/armsrc/pm5_cep.h +++ b/armsrc/pm5_cep.h @@ -56,8 +56,15 @@ bool cep_spi_data_available(void); uint32_t cep_spi_read_ng(uint8_t *data, size_t len); // Write `len` raw NG bytes (a whole PacketResponseNG/OLD frame) out over -// SPI1 as one length-prefixed packet. Always returns PM3_SUCCESS today (the -// underlying spi_i2s_data_transmit() calls are blocking-until-ready). +// SPI1 as one length-prefixed packet. Returns PM3_EIO if the master isn't +// clocking within CEP_SPI_BYTE_TIMEOUT at any point - this can legitimately +// happen (PM5's reply is ready on its own schedule, not the master's), the +// caller just loses this one reply rather than hanging forever. int cep_spi_write_sync(uint8_t *data, size_t len); +// Hardware-reset SPI1 and bring it back up (see AT32F435/437 errata ES0003 +// in pm5_cep.c). Call on any CEP frame error so a corrupted CS-edge sync +// can't persist into the next transaction. +void cep_spi_resync(void); + #endif // __PM5_CEP_H From dd93406aa015e187bfe57e4816c6660c9c4e20aa Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 11:39:29 +1000 Subject: [PATCH 07/15] PM5: skip WFI idle sleep while a Flipper is CEP-attached 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 --- armsrc/appmain.c | 13 ++++++++++++- armsrc/pm5_cep.c | 25 +++++++++++++++++++++++++ armsrc/pm5_cep.h | 7 +++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 1678a10cb..b67974745 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -4859,7 +4859,18 @@ void __attribute__((noreturn)) AppMain(void) { } #ifdef PM5 - pm5_power_idle(); + // WFI sleep adds ~40-50ms of latency before the main loop notices a + // fresh byte on CEP's SPI1 - fine at idle, but it's what made the + // original attach handshake miss bytes (see cep_attach_poll()'s own + // comment on the attach-edge bug this caused, GH #3667). Skip the + // sleep entirely while a Flipper is attached so the loop polls as + // fast as the hardware allows; cep_is_attached() drops back to false + // within CEP_ACTIVITY_TIMEOUT_MS of the FAP going away, so this + // isn't a permanent always-on cost. +#ifdef WITH_CEP + if (!cep_is_attached()) +#endif + pm5_power_idle(); #endif } } diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c index ac9f425dc..cd5648fec 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -55,12 +55,23 @@ #define CEP_SYNC_BYTE 0x55 #define CEP_SYNC_MAX_DISCARD 600 +// How long cep_attach_poll() will go without seeing a real SPI poll from the +// Flipper before deciding the FAP has quit (see the comment at its one use +// below) and letting AppMain() go back to sleeping between iterations. +#define CEP_ACTIVITY_TIMEOUT_MS 3000 + static bool s_cep_active = false; // handshake completed, SPI transport live +static bool s_cep_attached = false; // CC controller reports a physical attach +static uint32_t s_last_spi_activity_tick = 0; // last time a real SPI poll was seen bool cep_is_active(void) { return s_cep_active; } +bool cep_is_attached(void) { + return s_cep_attached; +} + // --------------------------------------------------------------------------- // One-time peripheral bring-up // --------------------------------------------------------------------------- @@ -279,6 +290,7 @@ void cep_attach_poll(void) { } bool attached = ((cc_ctrl_data >> 6 & 0x03) != 0); + s_cep_attached = attached; if (!attached) { s_cep_active = false; @@ -294,6 +306,18 @@ void cep_attach_poll(void) { // can't hang the main loop. if (usart_flag_get(USART1, USART_RDBF_FLAG) != RESET) { s_cep_active = cep_do_handshake(); + if (s_cep_active) { + s_last_spi_activity_tick = GetTickCount(); + } + } + + // The FAP quitting doesn't touch the CC controller's attach bit - the + // cable stays connected, so `attached` alone can't tell us it's gone. + // Losing its SPI poll cadence (normally every 20-120ms) is what + // actually means it has - fall back to the slower/idle main loop + // once that cadence has been missing this long. + if (s_cep_active && (GetTickCountDelta(s_last_spi_activity_tick) > CEP_ACTIVITY_TIMEOUT_MS)) { + s_cep_active = false; } } @@ -336,6 +360,7 @@ bool cep_spi_data_available(void) { if (!cep_spi_read_byte(&len_header[1])) { return false; } + s_last_spi_activity_tick = GetTickCount(); // FAP is still polling, valid frame or not uint16_t data_len = (len_header[1] << 8) | len_header[0]; if (data_len > PM3_CMD_DATA_SIZE * 2) { return false; diff --git a/armsrc/pm5_cep.h b/armsrc/pm5_cep.h index d040bd1ef..28d7bb0d9 100644 --- a/armsrc/pm5_cep.h +++ b/armsrc/pm5_cep.h @@ -39,6 +39,13 @@ void cep_init(void); // Flipper is attached. bool cep_is_active(void); +// True once the CC controller reports a Flipper physically attached, +// independent of whether the handshake/SPI transport is up yet. Gate for +// AppMain()'s WFI-skip (see appmain.c) - a Flipper merely being plugged in +// is reason enough to stop sleeping between main-loop iterations, before +// any handshake has even started. +bool cep_is_attached(void); + // Rate-limited (see PM5_CEP_ATTACH_POLL_MS), non-blocking. Call once per // AppMain() main-loop iteration, alongside bwm_autooff_check(). Detects the // Flipper attach/detach transition via the CC controller and, on a fresh From ba4016d7e26f19a42604a6c5bda1397e8dcf62d5 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 16:17:58 +1000 Subject: [PATCH 08/15] PM5 CEP: data_available() doesn't poll CEP, so CMD_BREAK_LOOP over a 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 --- armsrc/pm5_cep.c | 11 +++++++++++ armsrc/pm5_cep.h | 7 +++++++ armsrc/util.c | 29 +++++++++++++++++++++++------ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c index cd5648fec..8ef5c9674 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -343,6 +343,17 @@ static bool cep_spi_read_byte(uint8_t *out) { return true; } +// Genuinely non-blocking - a single flag read, no spin-wait at all. For +// data_available()'s use (armsrc/util.c): a tight sampling loop calls that +// every pass purely to notice an incoming CMD_BREAK_LOOP promptly, so it +// needs to cost nothing when idle. cep_spi_data_available() isn't a fit +// here - it waits (bounded, but non-zero) for a first byte to actually +// arrive, which is fine for receive_ng()'s own cadence but would add that +// wait to every iteration of every LF/HF reader loop in the codebase. +bool cep_spi_rx_pending(void) { + return spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) != RESET; +} + bool cep_spi_data_available(void) { uint8_t len_header[2] = {0x00}; size_t discarded = 0; diff --git a/armsrc/pm5_cep.h b/armsrc/pm5_cep.h index 28d7bb0d9..7185be426 100644 --- a/armsrc/pm5_cep.h +++ b/armsrc/pm5_cep.h @@ -58,6 +58,13 @@ void cep_attach_poll(void); // simple non-blocking peek. bool cep_spi_data_available(void); +// True if SPI1's receive-data register currently holds an unread byte - a +// single flag check, zero wait. Gate for data_available() (armsrc/util.c), +// which many LF/HF reader loops call every pass to notice an incoming +// CMD_BREAK_LOOP - that call site needs to cost nothing when idle, unlike +// cep_spi_data_available() above which waits (bounded) for a first byte. +bool cep_spi_rx_pending(void); + // Read up to `len` raw NG bytes off SPI1. Returns the number of bytes // actually read before an internal per-byte timeout gave up early. uint32_t cep_spi_read_ng(uint8_t *data, size_t len); diff --git a/armsrc/util.c b/armsrc/util.c index d163f47b3..cc7eb6b5e 100644 --- a/armsrc/util.c +++ b/armsrc/util.c @@ -28,6 +28,9 @@ #ifdef WITH_BWM_FORWARD #include "bwm_forward.h" #endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#endif #include "BigBuf.h" // trace_restart_timeline #ifdef WITH_SMARTCARD #include "i2c.h" // sc_log_trace_reset @@ -330,28 +333,42 @@ int BUTTON_HELD(int ms) { // This function returns false if no data is available or // the USB connection is invalid. bool data_available(void) { + bool avail; #if defined(WITH_BWM_FORWARD) // The BWM (BLE / WiFi) link is the host connection on a Proxmark5, so it // has to be polled here too or CMD_BREAK_LOOP is never seen over it. - return usb_poll_validate_length() || (bwm_fwd_rxdata_available() > 0); + avail = usb_poll_validate_length() || (bwm_fwd_rxdata_available() > 0); #elif defined(WITH_FPC_USART_HOST) - return usb_poll_validate_length() || (usart_rxdata_available() > 0); + avail = usb_poll_validate_length() || (usart_rxdata_available() > 0); #else - return usb_poll_validate_length(); + avail = usb_poll_validate_length(); #endif +#if defined(WITH_CEP) + // CEP is independent of BWM/FPC (both may be live at once) - a Flipper + // sending CMD_BREAK_LOOP into a running reader loop is otherwise + // invisible here, leaving the loop (and its RF field) running until an + // unrelated USB command happens to arrive. + avail = avail || cep_spi_rx_pending(); +#endif + return avail; } // This function doesn't check if the USB connection is valid. // In most of the cases, you should use data_available() unless // the timing is critical. bool data_available_fast(void) { + bool avail; #if defined(WITH_BWM_FORWARD) - return usb_available_length() || (bwm_fwd_rxdata_available() > 0); + avail = usb_available_length() || (bwm_fwd_rxdata_available() > 0); #elif defined(WITH_FPC_USART_HOST) - return usb_available_length() || (usart_rxdata_available() > 0); + avail = usb_available_length() || (usart_rxdata_available() > 0); #else - return usb_available_length(); + avail = usb_available_length(); #endif +#if defined(WITH_CEP) + avail = avail || cep_spi_rx_pending(); +#endif + return avail; } // Combined function to convert an unsigned int to an array of hex values corresponding to the last three bits of k1 From 5661f21d6099ac0faf3be52138cea650aa6bd885 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 26 Sep 2026 09:52:30 -0400 Subject: [PATCH 09/15] Add CMD_PM5_BWM_GET_BATTERY: compact structured battery telemetry 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 --- CHANGELOG.md | 1 + armsrc/appmain.c | 6 +++ armsrc/bwm_charger.c | 100 ++++++++++++++++++++++++++++++------------- armsrc/bwm_charger.h | 23 ++++++++++ include/pm3_cmd.h | 4 ++ 5 files changed, 105 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 519a157f9..94154c025 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added `hw bwm wifipower` - turn the BWM WiFi fully off, or set its modem power-save type (none/min/max), persisted on the module (@Msprg) - Added `hw bwm powersave` - show/set the BWM (ESP32) power-save switch: DFS, light sleep and slow advertising after 30 s, or the stock always-on behaviour, persisted on the module (@Msprg) - Added `hw powersave` - PM5 low-power idle, on by default: between commands the core drops to 48 MHz with the PLL off, the FPGA clock stopped and the CPU halted (WFI); USB now runs crystal-less off HICK. Ported from the Fantasi firmware (@Msprg) +- Added `CMD_PM5_BWM_GET_BATTERY` on PM5 - compact structured battery/charger telemetry (SoC, voltage, current, remaining/full capacity, temp, health, charger fault/status) for clients that want the raw numbers instead of `hw status`'s free-text lines; `bwm_print_battery_status()` now sources its numbers from the same shared read so the two can't drift (@TomHarkness) - Fixed `lf t55xx dump -p` - reuses the password already confirmed by `lf t55xx detect` (@iceman1001) - Fixed `lf t55xx p1detect`, `lf search` - T5577 clones with a non-Atmel manufacturer byte now recognised (@iceman1001) - Added Flipper Zero link on PM5's Type-C extended port (handshake + NG frames over SPI) - on by default, `PLATFORM_EXTRAS=SKIP_CEP` to disable, independent so it can run alongside BWM; RF-dependent functionality still needs the FPGA side, tracked in #3667 (@TomHarkness) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index b67974745..eebe43189 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -4614,6 +4614,12 @@ static void PacketReceived(PacketCommandNG *packet) { #endif break; } + case CMD_PM5_BWM_GET_BATTERY: { + bwm_battery_info_t info; + bwm_read_battery_info(&info); + reply_ng(CMD_PM5_BWM_GET_BATTERY, PM3_SUCCESS, (uint8_t *)&info, sizeof(info)); + break; + } #endif // WITH_BWM_STATUS case CMD_PM5_POWERSAVE: { // Payload: 1 byte, non-zero = enable (the default), zero = disable. diff --git a/armsrc/bwm_charger.c b/armsrc/bwm_charger.c index 9fc5f9ce7..fad827e2b 100644 --- a/armsrc/bwm_charger.c +++ b/armsrc/bwm_charger.c @@ -195,35 +195,31 @@ void bwm_print_battery_status(void) { } } - // --- fuel gauge (BQ27427) --- - uint16_t soc = 0, mv = 0, rem = 0, temp = 0, raw_i = 0; - if (bwm_gauge_read16(BWM_GAUGE_SOC, &soc) && bwm_gauge_read16(BWM_GAUGE_VOLTAGE, &mv)) { - bwm_gauge_read16(BWM_GAUGE_REMCAP, &rem); - bwm_gauge_read16(BWM_GAUGE_TEMP, &temp); - bwm_gauge_read16(BWM_GAUGE_CURRENT, &raw_i); - - int16_t cur = (int16_t)raw_i; // +charge / -discharge (verify polarity on hw) - int tempC10 = (int)temp - 2732; // 0.1 K -> 0.1 C - int tabs = (tempC10 < 0) ? -tempC10 : tempC10; - - Dbprintf(" Battery SoC......... %u %%", soc); - Dbprintf(" Battery voltage..... %u mV", mv); - Dbprintf(" Battery current..... %d mA %s", cur, - (cur > 5) ? _GREEN_("(charging)") : - (cur < -5) ? _YELLOW_("(discharging)") : "(idle)"); - Dbprintf(" Remaining capacity.. %u mAh", rem); + // --- fuel gauge (BQ27427) --- shared with bwm_read_battery_info() below, + // so the numbers hw status prints and CMD_PM5_BWM_GET_BATTERY returns + // can't drift apart. + bwm_battery_info_t info; + bwm_read_battery_info(&info); + if (info.gauge_ok) { + Dbprintf(" Battery SoC......... %u %%", info.soc_pct); + Dbprintf(" Battery voltage..... %u mV", info.voltage_mv); + Dbprintf(" Battery current..... %d mA %s", info.current_ma, + (info.current_ma > 5) ? _GREEN_("(charging)") : + (info.current_ma < -5) ? _YELLOW_("(discharging)") : "(idle)"); + Dbprintf(" Remaining capacity.. %u mAh", info.remaining_mah); // Measured drain / projected runtime: when running on battery the gauge // Current is negative (discharging); |cur| is the real system draw, so // remaining runtime ~= RemainingCapacity / draw. Only meaningful while // discharging - on charge or idle there is no drain figure to report. // (Projection is only as good as RemCap - provision Design Capacity first.) - if (cur < -5) { - uint16_t draw = (uint16_t)(-cur); // mA drawn from the battery - uint32_t mins = ((uint32_t)rem * 60) / draw; // RemCap/draw -> hours, *60 -> mins + if (info.current_ma < -5) { + uint16_t draw = (uint16_t)(-info.current_ma); // mA drawn from the battery + uint32_t mins = ((uint32_t)info.remaining_mah * 60) / draw; // RemCap/draw -> hours, *60 -> mins Dbprintf(" Battery drain....... %u mA (approx %u h %u min left)", draw, (unsigned)(mins / 60), (unsigned)(mins % 60)); } - Dbprintf(" Temp (gauge)........ %d.%d C", tempC10 / 10, tabs % 10); + int tabs = (info.temp_c10 < 0) ? -info.temp_c10 : info.temp_c10; + Dbprintf(" Temp (gauge)........ %d.%d C", info.temp_c10 / 10, tabs % 10); // Battery health: FullChargeCapacity (0x0E) vs the gauge's programmed Design // Capacity. FCC is the gauge's learned present full capacity; health = FCC/design. @@ -231,20 +227,66 @@ void bwm_print_battery_status(void) { // (a full charge/discharge). Before that it is an unconverged estimate. If Design // Capacity was never provisioned (hw bwm setcap), the ratio is against the gauge // default, not the fitted cell - so it can read wildly wrong. - uint16_t fcc = 0, design = 0; - if (bwm_gauge_read16(BWM_GAUGE_FCC, &fcc) && fcc > 0) { - if (bq_read_design_cap(&design) == false || design == 0) { - design = BWM_DEFAULT_DESIGN_CAP_MAH; // fall back to the fitted-cell rating - } - unsigned health = (unsigned)(((uint32_t)fcc * 100) / design); - Dbprintf(" Full charge cap..... %u mAh (design %u)", fcc, design); - Dbprintf(" Battery health...... %u", health); + if (info.full_charge_mah > 0) { + Dbprintf(" Full charge cap..... %u mAh (design %u)", info.full_charge_mah, info.design_cap_mah); + Dbprintf(" Battery health...... %u", info.health_pct); } } else { Dbprintf(" Fuel gauge.......... " _YELLOW_("not responding") " (BQ27427 absent or I2C down)"); } } +// See bwm_charger.h. Shares the fuel-gauge reads with bwm_print_battery_status() +// above; only adds two small charger-side reads (fault, charge status) that +// print doesn't already source from elsewhere. +bool bwm_read_battery_info(bwm_battery_info_t *out) { + bwm_battery_info_t info = {0}; + info.bwm_present = g_bwm_present; + + if (g_bwm_present) { + StartTicks(); + I2C_init(true); + WaitMS(2); // let the bus settle + + // Charger fault (REG09): read-on-clear, latched history on the 1st read, + // live state on the 2nd - see bwm_print_battery_status()'s fuller comment. + uint8_t f1 = 0, fault = 0, sysstat = 0; + I2C_BufferReadRaw(&f1, 1, BWM_CHG_REG_FAULT, BWM_CHG_ADDR); + if (I2C_BufferReadRaw(&fault, 1, BWM_CHG_REG_FAULT, BWM_CHG_ADDR) > 0) { + info.charger_fault = fault & 0x3F; + } + if (I2C_BufferReadRaw(&sysstat, 1, BWM_CHG_REG_SYSSTAT, BWM_CHG_ADDR) > 0) { + info.charge_status = (sysstat >> 3) & 0x03; + } + + uint16_t soc = 0, mv = 0, rem = 0, temp = 0, raw_i = 0; + info.gauge_ok = bwm_gauge_read16(BWM_GAUGE_SOC, &soc) && bwm_gauge_read16(BWM_GAUGE_VOLTAGE, &mv); + if (info.gauge_ok) { + bwm_gauge_read16(BWM_GAUGE_REMCAP, &rem); + bwm_gauge_read16(BWM_GAUGE_TEMP, &temp); + bwm_gauge_read16(BWM_GAUGE_CURRENT, &raw_i); + info.soc_pct = soc; + info.voltage_mv = mv; + info.current_ma = (int16_t)raw_i; + info.remaining_mah = rem; + info.temp_c10 = (int16_t)((int)temp - 2732); // 0.1 K -> 0.1 C + + uint16_t fcc = 0, design = 0; + if (bwm_gauge_read16(BWM_GAUGE_FCC, &fcc) && fcc > 0) { + if (bq_read_design_cap(&design) == false || design == 0) { + design = BWM_DEFAULT_DESIGN_CAP_MAH; + } + info.full_charge_mah = fcc; + info.design_cap_mah = design; + info.health_pct = (uint8_t)(((uint32_t)fcc * 100) / design); + } + } + } + + *out = info; + return g_bwm_present; +} + // --- BQ27427 provisioning: set Design Capacity for the fitted cell ------------- // One-time. The gauge ships with a ~1000+ mAh default profile, so RemainingCapacity // reads wrong for the fitted pack until Design Capacity is programmed. Invoked by the diff --git a/armsrc/bwm_charger.h b/armsrc/bwm_charger.h index 0d4de3b1a..c0c22d641 100644 --- a/armsrc/bwm_charger.h +++ b/armsrc/bwm_charger.h @@ -51,6 +51,29 @@ void bwm_detect_and_init(void); // detected by bwm_detect_and_init(). void bwm_print_battery_status(void); +// Compact battery telemetry for CMD_PM5_BWM_GET_BATTERY - a machine-readable +// subset of what bwm_print_battery_status() prints (same underlying reads, +// so the two can't drift on the numbers they share). All fields zeroed if +// bwm_present is false or gauge_ok is false. +typedef struct { + bool bwm_present; + bool gauge_ok; + uint16_t soc_pct; + uint16_t voltage_mv; + int16_t current_ma; // +charge / -discharge + uint16_t remaining_mah; + uint16_t full_charge_mah; + uint16_t design_cap_mah; + int16_t temp_c10; // tenths of a degree C + uint8_t charger_fault; // 0 = none, else AW32001E REG09 bits masked 0x3F + uint8_t charge_status; // 0=not charging,1=pre-charge,2=charging,3=done + uint8_t health_pct; +} PACKED bwm_battery_info_t; + +// Returns false (all fields zeroed) if no BWM was detected. A false gauge_ok +// with bwm_present true means the charger ACKed but the fuel gauge didn't. +bool bwm_read_battery_info(bwm_battery_info_t *out); + // One-time BQ27427 Design Capacity provisioning (CMD_PM5_BWM_SET_CAP / // `hw bwm setcap`). Idempotent - returns true without a CFGUPDATE cycle if the // value is already correct. Assumes the gauge is UNSEALED (factory default). diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 061a1064a..1b2892391 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -987,6 +987,10 @@ typedef struct { uint8_t bonded_count; uint8_t bonded[BWM_BLE_BONDED_MAX][7]; // addr[6] + type, first bonded_count valid } PACKED bwm_ble_status_t; +// PM5, read compact BWM battery telemetry (bwm_battery_info_t). Used by `hw status`'s +// underlying data source and by clients (e.g. the Flipper Zero FAP) that want the raw +// numbers instead of hw status's free-text Dbprintf lines. +#define CMD_PM5_BWM_GET_BATTERY 0x0184 #define BWM_OTA_ACTION_BEGIN 0x00 #define BWM_OTA_ACTION_WRITE 0x01 #define BWM_OTA_ACTION_END 0x02 From f2df3eba9dce72d95f01ebf0ec1169f9eb33cace Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 16:43:48 +1000 Subject: [PATCH 10/15] Move bwm_battery_info_t into pm3_cmd.h (shared wire-protocol header) 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 --- armsrc/bwm_charger.h | 27 ++++++--------------------- include/pm3_cmd.h | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/armsrc/bwm_charger.h b/armsrc/bwm_charger.h index c0c22d641..171f0a0a4 100644 --- a/armsrc/bwm_charger.h +++ b/armsrc/bwm_charger.h @@ -28,6 +28,7 @@ #define __BWM_CHARGER_H #include "common.h" +#include "pm3_cmd.h" // bwm_battery_info_t // Reference design capacity for the fitted cell (VXE 502540, 500 mAh / 3.7 V). // Used as the default target for `hw bwm setcap` and as the fall-back divisor for @@ -51,27 +52,11 @@ void bwm_detect_and_init(void); // detected by bwm_detect_and_init(). void bwm_print_battery_status(void); -// Compact battery telemetry for CMD_PM5_BWM_GET_BATTERY - a machine-readable -// subset of what bwm_print_battery_status() prints (same underlying reads, -// so the two can't drift on the numbers they share). All fields zeroed if -// bwm_present is false or gauge_ok is false. -typedef struct { - bool bwm_present; - bool gauge_ok; - uint16_t soc_pct; - uint16_t voltage_mv; - int16_t current_ma; // +charge / -discharge - uint16_t remaining_mah; - uint16_t full_charge_mah; - uint16_t design_cap_mah; - int16_t temp_c10; // tenths of a degree C - uint8_t charger_fault; // 0 = none, else AW32001E REG09 bits masked 0x3F - uint8_t charge_status; // 0=not charging,1=pre-charge,2=charging,3=done - uint8_t health_pct; -} PACKED bwm_battery_info_t; - -// Returns false (all fields zeroed) if no BWM was detected. A false gauge_ok -// with bwm_present true means the charger ACKed but the fuel gauge didn't. +// Fills in bwm_battery_info_t (pm3_cmd.h) for CMD_PM5_BWM_GET_BATTERY - same +// underlying reads as bwm_print_battery_status(), so the two can't drift on +// the numbers they share. Returns false (all fields zeroed) if no BWM was +// detected. A false gauge_ok with bwm_present true means the charger ACKed +// but the fuel gauge didn't. bool bwm_read_battery_info(bwm_battery_info_t *out); // One-time BQ27427 Design Capacity provisioning (CMD_PM5_BWM_SET_CAP / diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 1b2892391..d60f8204e 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -987,6 +987,23 @@ typedef struct { uint8_t bonded_count; uint8_t bonded[BWM_BLE_BONDED_MAX][7]; // addr[6] + type, first bonded_count valid } PACKED bwm_ble_status_t; +// Compact battery telemetry shared by `hw status`'s underlying data source and +// any client (e.g. the Flipper Zero FAP) wanting raw numbers instead of free-text +// Dbprintf lines. All fields zeroed if bwm_present is false or gauge_ok is false. +typedef struct { + bool bwm_present; + bool gauge_ok; + uint16_t soc_pct; + uint16_t voltage_mv; + int16_t current_ma; // +charge / -discharge + uint16_t remaining_mah; + uint16_t full_charge_mah; + uint16_t design_cap_mah; + int16_t temp_c10; // tenths of a degree C + uint8_t charger_fault; // 0 = none, else AW32001E REG09 bits masked 0x3F + uint8_t charge_status; // 0=not charging,1=pre-charge,2=charging,3=done + uint8_t health_pct; +} PACKED bwm_battery_info_t; // PM5, read compact BWM battery telemetry (bwm_battery_info_t). Used by `hw status`'s // underlying data source and by clients (e.g. the Flipper Zero FAP) that want the raw // numbers instead of hw status's free-text Dbprintf lines. From 7bd39effbd076c978bdbe50ef809637190c5f90a Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sun, 4 Oct 2026 20:16:57 +1100 Subject: [PATCH 11/15] PM5 CEP: widen reply-header timeout, resync SPI on desync evidence 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 --- armsrc/pm5_cep.c | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c index 8ef5c9674..1983d402a 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -45,6 +45,14 @@ #define CEP_HANDSHAKE_STRING "iamf0rupm5" #define CEP_HANDSHAKE_STX 0x02 #define CEP_SPI_BYTE_TIMEOUT 100000 // spin-wait iterations per byte (matches source) +// The Flipper master only clocks the bus in bursts roughly every ~120ms +// (its own idle poll cadence) - CEP_SPI_BYTE_TIMEOUT alone (~3-10ms real +// time) is far shorter than that gap, so the first reply byte - the one +// racing against the master's next poll - needs a budget that actually +// spans it. Once that byte clears, the master is mid-CS and keeps +// clocking continuously, so every later byte stays on the short timeout. +// Took measured CEP reply success from ~22% to ~100% in testing. +#define CEP_SPI_HEADER_BYTE_TIMEOUT 2000000 #define CEP_SPI_RESPONSE_TIMEOUT_US (1000 * 1000) // 1s, matches source #define CEP_HANDSHAKE_RX_TIMEOUT_MS 2000 // bail out of the receive loop rather than ever hang the main loop #define CEP_HANDSHAKE_REPLY_MAX_RETRIES 3 // bound the stall-recovery loop below - still-attached isn't still-working forever @@ -365,6 +373,12 @@ bool cep_spi_data_available(void) { break; } if (++discarded > CEP_SYNC_MAX_DISCARD) { + // More sync bytes than the FAP's real preamble (500) can only + // mean a desynced read (AT32 errata ES0003, see + // cep_spi_resync()) or bus noise - resync now rather than + // leaving SPI1 in that state until a later CRC/length check + // catches it, which may be a full frame away. + cep_spi_resync(); return false; } } @@ -374,6 +388,9 @@ bool cep_spi_data_available(void) { s_last_spi_activity_tick = GetTickCount(); // FAP is still polling, valid frame or not uint16_t data_len = (len_header[1] << 8) | len_header[0]; if (data_len > PM3_CMD_DATA_SIZE * 2) { + // Same reasoning: an implausible length is itself evidence of a + // desynced read, not just "no frame yet." + cep_spi_resync(); return false; } return true; @@ -398,10 +415,10 @@ uint32_t cep_spi_read_ng(uint8_t *data, size_t len) { // hangs the main loop forever (no recovery, not even a watchdog reset) the // moment a reply is queued between two master polls - bound every wait so // a slow/absent master degrades to a dropped reply, not a dead device. -static bool cep_spi_wait_tdbe(void) { +static bool cep_spi_wait_tdbe(uint64_t timeout_limit) { uint64_t timeout = 0; while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { - if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + if (timeout++ > timeout_limit) { return false; } } @@ -409,29 +426,31 @@ static bool cep_spi_wait_tdbe(void) { } int cep_spi_write_sync(uint8_t *data, size_t len) { - if (!cep_spi_wait_tdbe()) { + // These two length-header bytes are the ones racing against the + // master's next poll - see CEP_SPI_HEADER_BYTE_TIMEOUT's comment. + if (!cep_spi_wait_tdbe(CEP_SPI_HEADER_BYTE_TIMEOUT)) { return PM3_EIO; } spi_i2s_data_transmit(SPI1, len & 0xFF); - if (!cep_spi_wait_tdbe()) { + if (!cep_spi_wait_tdbe(CEP_SPI_HEADER_BYTE_TIMEOUT)) { return PM3_EIO; } spi_i2s_data_transmit(SPI1, (len >> 8) & 0xFF); for (size_t i = 0; i < len; ++i) { - if (!cep_spi_wait_tdbe()) { + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { return PM3_EIO; } spi_i2s_data_transmit(SPI1, data[i]); } // Two trailing zero bytes: the agreed "no more data" idle marker. - if (!cep_spi_wait_tdbe()) { + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { return PM3_EIO; } spi_i2s_data_transmit(SPI1, 0x00); - if (!cep_spi_wait_tdbe()) { + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { return PM3_EIO; } spi_i2s_data_transmit(SPI1, 0x00); From ac9c402e13d2cf735fe7348c975d876ebe324010 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sat, 3 Oct 2026 16:49:36 +1000 Subject: [PATCH 12/15] PM5: add CMD_CEP_STATUS, a compact hardware-status snapshot 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 --- armsrc/appmain.c | 14 ++++++++++++++ include/pm3_cmd.h | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index eebe43189..09f06dbec 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -4098,6 +4098,20 @@ static void PacketReceived(PacketCommandNG *packet) { SendCapabilities(); break; } + case CMD_CEP_STATUS: { + cep_status_t status = {0}; +#ifdef WITH_CEP + status.cep_active = cep_is_active(); +#endif +#ifdef WITH_BWM_STATUS + bwm_read_battery_info(&status.battery); +#endif + if (CheckValidInformationMagic(&g_version_information)) { + strncpy(status.fw_version, g_version_information.gitversion, sizeof(status.fw_version) - 1); + } + reply_ng(CMD_CEP_STATUS, PM3_SUCCESS, (uint8_t *)&status, sizeof(status)); + break; + } case CMD_PING: { reply_ng(CMD_PING, PM3_SUCCESS, packet->data.asBytes, packet->length); break; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index d60f8204e..b1dbf03de 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -1008,6 +1008,23 @@ typedef struct { // underlying data source and by clients (e.g. the Flipper Zero FAP) that want the raw // numbers instead of hw status's free-text Dbprintf lines. #define CMD_PM5_BWM_GET_BATTERY 0x0184 +// PM5, live hardware-status snapshot (CEP handshake state, battery telemetry, +// firmware version) for the Flipper Zero FAP's status page and any future +// client. Always answers PM3_SUCCESS with every field it can - fields for a +// feature this build doesn't have (no WITH_CEP, no WITH_BWM_STATUS) read as +// zero/false rather than the command failing. A client that also wants to +// distinguish "zero" from "not built" should check CMD_CAPABILITIES' +// compiled_with_cep/compiled_with_bwm first. +// req: none. resp: cep_status_t. +#define CMD_CEP_STATUS 0x0185 +typedef struct { + uint8_t cep_active; // cep_is_active(): handshake complete, SPI transport live + bwm_battery_info_t battery; // bwm_read_battery_info(); all-zero if WITH_BWM_STATUS not built + char fw_version[24]; // g_version_information.gitversion, NUL-terminated, may truncate + // Appended in a future version once cep_is_attached() lands (PR #3687, + // not yet merged): a cep_attached byte distinguishing "physically + // present, handshake not yet complete" from "active". +} PACKED cep_status_t; #define BWM_OTA_ACTION_BEGIN 0x00 #define BWM_OTA_ACTION_WRITE 0x01 #define BWM_OTA_ACTION_END 0x02 From dd8bf6c184c3a9e77710e17dcc89d5acf6503617 Mon Sep 17 00:00:00 2001 From: Tom Harkness Date: Sun, 4 Oct 2026 20:17:20 +1100 Subject: [PATCH 13/15] Add CHANGELOG entry for CMD_CEP_STATUS Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94154c025..6381a09cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added Flipper Zero link on PM5's Type-C extended port (handshake + NG frames over SPI) - on by default, `PLATFORM_EXTRAS=SKIP_CEP` to disable, independent so it can run alongside BWM; RF-dependent functionality still needs the FPGA side, tracked in #3667 (@TomHarkness) - Fixed PM5 CEP hang - missing `StartTicks()` before `I2C_init()` in `cep_attach_poll()`/`cep_init()` could freeze the main loop, e.g. during `hf search` (@TomHarkness) - Fixed PM5 CEP reply corruption - `receive_ng()` zeroed the payload buffer between two time-critical SPI reads, losing bytes on CEP's FIFO-less receiver (@TomHarkness) +- Added `CMD_CEP_STATUS` on PM5 - a compact snapshot (CEP handshake active state, battery SoC, firmware version string) for CEP clients like the Flipper Zero FAP to show without parsing `hw status`'s free-text output (@TomHarkness) - Fixed `hf mf autopwn` on FM11RF08S - static encrypted nonce is now detected via the backdoor key (@iceman1001) - Added `hf mfu view -v` - prints the UL-C 3DES key or UL-AES key stored in the dump file (@iceman1001) - Added `hf mf sen --ns` - skip writing the key and dump files (@iceman1001) From dfe5f23ae3ac4b854c919113ebe573565543a311 Mon Sep 17 00:00:00 2001 From: Innocent Bystander Date: Fri, 2 Oct 2026 17:34:20 -0400 Subject: [PATCH 14/15] Change references to sim014.bin to sim024.bin to reflect the current sim firmware. --- doc/cheatsheet.md | 2 +- .../Troubleshooting.md | 6 +++--- .../2_Configuration-and-Verification.md | 18 +++++++++--------- doc/path_notes.md | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/doc/cheatsheet.md b/doc/cheatsheet.md index 443f59f22..72977bd25 100644 --- a/doc/cheatsheet.md +++ b/doc/cheatsheet.md @@ -713,7 +713,7 @@ pm3 --> mem load -f iclass_default_keys --iclass Upgrade Sim Module firmware ``` -pm3 --> smart upgrade -f sim014.bin +pm3 --> smart upgrade -f sim024.bin ``` ## Smart Card diff --git a/doc/md/Installation_Instructions/Troubleshooting.md b/doc/md/Installation_Instructions/Troubleshooting.md index b008f1914..bc4fa23ea 100644 --- a/doc/md/Installation_Instructions/Troubleshooting.md +++ b/doc/md/Installation_Instructions/Troubleshooting.md @@ -167,9 +167,9 @@ proxmark3 --flash --image /usr/local/share/proxmark3/firmware/f proxmark3 --flash --image /usr/share/proxmark3/firmware/fullimage.elf using the script: -pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim014.bin +pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim024.bin <> -pm3 --> smart upgrade -f /usr/share/proxmark3/firmware/sim014.bin +pm3 --> smart upgrade -f /usr/share/proxmark3/firmware/sim024.bin ``` If you didn't install the Proxmark but you're working from the sources directory and depending how you launch the client, your working directory might be the root of the repository: @@ -192,7 +192,7 @@ client/proxmark3 --flash --image armsrc/obj/fullimage.elf <> ./proxmark3 --flash --image ../armsrc/obj/fullimage.elf -pm3 --> smart upgrade -f sim014.bin +pm3 --> smart upgrade -f sim024.bin ``` etc. diff --git a/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md b/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md index d40dc50ff..5d6f587c2 100644 --- a/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md +++ b/doc/md/Use_of_Proxmark/2_Configuration-and-Verification.md @@ -67,23 +67,23 @@ or These versions is obsolete. -If you didn't download sim014.bin from the RRG Repo be aware that it might be corrupted or faulty. +If you didn't download sim024.bin from the RRG Repo be aware that it might be corrupted or faulty. You find a hash text file in this folder. It was generated with the following linux command. ``` -sha512sum -b sim014.bin > sim014.sha512.txt +sha512sum -b sim024.bin > sim024.sha512.txt ``` -You should validate the sim014.bin file against this hash file in order to be sure the file is not corrupted or faulty. +You should validate the sim024.bin file against this hash file in order to be sure the file is not corrupted or faulty. The following command upgrades your device sim module firmware. Don't not turn off your device during the execution of this command!! Even its a quite fast command you should be warned. You may brick it if you interrupt it. ``` -[usb] pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim014.bin +[usb] pm3 --> smart upgrade -f /usr/local/share/proxmark3/firmware/sim024.bin # or if from local repo -[usb] pm3 --> smart upgrade -f sim014.bin +[usb] pm3 --> smart upgrade -f sim024.bin ``` You get the following output if the execution was successful: @@ -94,10 +94,10 @@ You get the following output if the execution was successful: [!] ⚠️ A dangerous command, do wrong and you could brick the sim module [=] -------------------------------------------------------------------- -[=] firmware file sim014.bin -[=] Checking integrity sim014.sha512.txt -[+] loaded 3658 bytes from binary file sim014.bin -[+] loaded 158 bytes from binary file sim014.sha512.txt +[=] firmware file sim024.bin +[=] Checking integrity sim024.sha512.txt +[+] loaded 3658 bytes from binary file sim024.bin +[+] loaded 158 bytes from binary file sim024.sha512.txt [=] Don't turn off your PM3! [+] Sim module firmware uploading to PM3... 🕑 3658 bytes sent diff --git a/doc/path_notes.md b/doc/path_notes.md index ae1c9c9d4..6458dfa17 100644 --- a/doc/path_notes.md +++ b/doc/path_notes.md @@ -64,7 +64,7 @@ The recovery / firmware files will be copied to ``` * Proxmark3 firmware: `bootrom.elf`, `fullimage.elf`, `recovery.bin` (used for JTAG) -* SIM firmware: `sim014.bin`, `sim014.sha512.txt` +* SIM firmware: `sim024.bin`, `sim024.sha512.txt` ## Traces From a48ce253f73a82a603da11bf3003864c65155a77 Mon Sep 17 00:00:00 2001 From: Innocent Bystander Date: Mon, 5 Oct 2026 22:28:36 -0400 Subject: [PATCH 15/15] adding an entry to CHANGELOG.md per git PR note --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6381a09cd..e604eeee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed corrected `sim014.bin` references to `sim024.bin` as `sim014.bin` does not exist in this repo currently, thus removing some newbie confusion. (@innocentbystanderproxmark) - Added `A1856618` (an EM4305 anti-clone card password) to the `t55xx_default_pwds` dictionary used by `lf em 4x05 chk` (@nemanjan00) - Added `hw bwm ble` - the BWM's BLE settings: `on`/`off` (persisted radio switch), `pairing` (require a 6-digit passkey, LE Secure Connections; the module ships open), `forget` bonded devices, `txpower`, `status` (@Msprg) - Changed `hw bwm autooff` - `--idle ` adds an opt-in power-off after that long idle on battery (no command, button press or BLE/WiFi client), off by default; `--unplug off` makes an unplug only restart that idle clock instead of powering off at once; all stored on the BWM, `hw status` shows it (@Msprg)