From 0cd1fada0e2af09b4adffe214fc664d4251d1ddb Mon Sep 17 00:00:00 2001 From: Msprg <18015488+Msprg@users.noreply.github.com> Date: Thu, 17 Sep 2026 20:38:43 +0200 Subject: [PATCH] pm5: auto power-off: idle timeout, unplug switch, stored on the BWM The USB-unplug power-off left two ways to drain the battery: a PM5 woken by the button and forgotten, and one left idle after the phone disconnected. Idle trigger (opt-in, PM5_AUTOOFF_IDLE_MS 0 by default so out of the box only the unplug trigger exists, as before): on battery the board powers off after the idle timeout with no interaction and no wireless client. Interaction is a received command over any transport, any button press, or a client connecting or leaving; a standalone mode or a long-running command holds the main loop, so neither can be cut short. The BWM reports its clients with the LINK_STATE broadcast (8092, companion Proxmark5_BWM_esp32 PR) which bwm_forward.c tracks; at boot the BLE half is seeded with a status query since the module only reports changes. When the timer is due but a client is still tracked, the module is asked for its BLE state (at most every 10 s), so a lost "client left" broadcast cannot pin the board on. And right before going off the module is asked once more: older module firmware never sends the broadcast and a "connected" one can get lost, and neither may power the board off under a silent BLE client. No answer means off. --unplug off: the unplug trigger always won, so "survive the unplug, go off after N idle seconds" was not reachable. It is its own setting (default on = unchanged). With it off an unplug only restarts the idle clock - from the unplug, not from the last command, or a board that sat idle on USB for an hour would still die with the cable. Unplug detection is edge-based (VUSB present at the previous poll, absent at this one) instead of "absent and seen since boot", which would fire on every poll after a tolerated unplug. VUSB is followed while the feature is switched off too, so switching it on again on battery is not taken for an unplug. Stored on the BWM: runtime-only settings reset at every boot, which is exactly when the idle trigger matters. The PM5 has no settings store, so the switch, the idle timeout and the unplug switch live in the module's host value slots (APP_CMD_SET/GET_SYS_HOST_VALUE 1021/1022, companion PR; slot 0 switch, 1 idle seconds, 2 unplug), loaded at the first auto-off poll and saved by CMD_PM5_BWM_AUTOOFF with 1 s per write, so a silent or older module still leaves the reply inside the client's 5 s wait. Without a module, or with an older one, the defaults apply and the status says "not stored". hw bwm autooff [on|off] [--idle ] [--unplug ]; no argument shows the state, one fact per line: switch, idle timeout, unplug power-off, stored on module, USB power, USB seen since boot, unplug trigger armed, tracked client, the module's BLE state, idle time. Payload [action][enabled][idle_s u32][unplug, optional] with keep sentinels; both actions are non-zero so an old firmware, which reads byte 0 as the enable flag, can only be left enabled. hw status prints the module's live BLE state and the auto power-off setting; at debug level also the tracked client, which should agree with the live state. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 1 + armsrc/appmain.c | 233 +++++++++++++++++++++++++++++++++++++------ armsrc/bwm_forward.c | 15 +++ armsrc/bwm_forward.h | 7 ++ armsrc/bwm_wifi.c | 24 +++++ armsrc/bwm_wifi.h | 12 +++ client/src/cmdbwm.c | 116 ++++++++++++++++----- doc/commands.json | 18 ++-- doc/commands.md | 2 +- include/pm3_cmd.h | 24 ++++- 10 files changed, 385 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b42d632aa..253e69430 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] +- 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) - 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) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 8f668d2b0..e546330c3 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -93,35 +93,91 @@ #ifdef WITH_PM5_AUTOOFF -// Automatic power-off on USB unplug. When the BWM keeps the PM5 alive on battery, -// users leave it draining. This powers the board down after USB has been absent -// continuously for a grace period, using the SAME latch release as the long-press -// shutdown (Gpio_ARM_Power_ON_Low). Button power-ON is a hardware function and is -// unaffected - once powered off there is no firmware running to interfere with it. -// -// Runtime toggle (default ON) via CMD_PM5_BWM_AUTOOFF; resets to default each boot. -// Standalone / BLE-relay users who run unplugged on purpose can disable it. +// Automatic power-off, through the same latch release as the long-press shutdown +// (Gpio_ARM_Power_ON_Low); button power-ON is hardware and unaffected. Two +// triggers: a USB unplug (g_autooff_unplug) and, opt-in, g_autooff_idle_ms idle +// on battery. Idle resets on a command, a button press or a client coming/going. +// The switch and both trigger settings are set over CMD_PM5_BWM_AUTOOFF, persisted +// on the BWM and reloaded at boot; without a module the defaults hold: on, unplug +// on, idle off. #ifndef PM5_AUTOOFF_POLL_MS -#define PM5_AUTOOFF_POLL_MS 250 // how often to sample VUSB +#define PM5_AUTOOFF_POLL_MS 250 // how often to sample VUSB and the link state +#endif +#ifndef PM5_AUTOOFF_IDLE_MS +#define PM5_AUTOOFF_IDLE_MS 0 // e.g. (5 * 60 * 1000) for 5 min #endif -bool g_autooff_enabled = true; // default on; toggled by CMD_PM5_BWM_AUTOOFF +bool g_autooff_enabled = true; // default on; CMD_PM5_BWM_AUTOOFF +uint32_t g_autooff_idle_ms = PM5_AUTOOFF_IDLE_MS; // 0 = no idle power-off +bool g_autooff_unplug = true; // power off when USB is pulled static bool s_autooff_setup = false; +static uint32_t s_autooff_activity_tick = 0; // last interaction, see above +static bool s_autooff_usb_seen = false; +static bool s_autooff_link = false; +static bool s_autooff_persisted = false; // setting loaded from / saved to the module -// Auto power-off on USB unplug. CRITICAL: only powers off on a USB-present -> absent -// TRANSITION - i.e. the board was running on USB and the cable was pulled. A board that -// booted on battery (button press, no USB) must NOT auto-off, or it could never be used -// unplugged at all (and the hw bwm autooff toggle would be unreachable, since setting it -// needs a client/USB). So we require having seen USB present at least once this session -// before an absent reading triggers shutdown. +void pm5_autooff_touch(void) { + s_autooff_activity_tick = GetTickCount(); +} + +void pm5_autooff_get_status(bwm_autooff_status_t *st) { + st->enabled = g_autooff_enabled ? 1 : 0; + st->idle_s = g_autooff_idle_ms / 1000; + st->idle_now_s = GetTickCountDelta(s_autooff_activity_tick) / 1000; + st->link = s_autooff_link ? 1 : 0; + st->ble_live = 0xFF; +#ifdef WITH_BWM_FORWARD + (void)bwm_esp_get_ble_state(&st->ble_live, 800); +#endif + st->usb = Gpio_VUSB_Read() ? 1 : 0; + st->usb_seen = s_autooff_usb_seen ? 1 : 0; + st->persisted = s_autooff_persisted ? 1 : 0; + st->unplug = g_autooff_unplug ? 1 : 0; +} + +// The setting lives on the BWM host value slots: the PM5 has no store of its own. +static void pm5_autooff_save(void) { +#ifdef WITH_BWM_FORWARD + // 1 s each: an NVS write is tens of ms, and three must still fit the client's wait. + s_autooff_persisted = (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_ENABLED, g_autooff_enabled ? 1 : 0, 1000) == PM3_SUCCESS) && + (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_IDLE_S, g_autooff_idle_ms / 1000, 1000) == PM3_SUCCESS) && + (bwm_esp_host_value_set(BWM_HOSTVAL_AUTOOFF_UNPLUG, g_autooff_unplug ? 1 : 0, 1000) == PM3_SUCCESS); +#endif +} + +static void pm5_autooff_load(void) { +#ifdef WITH_BWM_FORWARD + uint32_t v = 0; + int r = bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_ENABLED, &v, 300); + if (r == PM3_SUCCESS) { + g_autooff_enabled = (v != 0); + } + if (r == PM3_SUCCESS || r == PM3_ENODATA) { + s_autooff_persisted = true; // the module keeps the setting, stored or still default + if (bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_IDLE_S, &v, 300) == PM3_SUCCESS) { + g_autooff_idle_ms = MIN(v, BWM_AUTOOFF_IDLE_MAX_S) * 1000; + } + if (bwm_esp_host_value_get(BWM_HOSTVAL_AUTOOFF_UNPLUG, &v, 300) == PM3_SUCCESS) { + g_autooff_unplug = (v != 0); + } + } +#endif +} + +static void pm5_power_off(void) { + LEDsoff(); + Gpio_ARM_Power_ON_Low(); + while (1); // wait for hardware power-off (button press powers back on, in hardware) +} + +// CRITICAL: the unplug trigger fires only on a USB present -> absent TRANSITION. +// A board that booted on battery must not go off at once, or it could never be +// used unplugged (and the toggle would be unreachable): it gets the idle timer. static void bwm_autooff_check(void) { static uint32_t last_tick = 0; - static bool usb_was_present = false; // have we seen USB present since boot? + static bool usb_prev = false; // VUSB at the previous poll - if (g_autooff_enabled == false) { - return; - } if ((last_tick != 0) && (GetTickCountDelta(last_tick) < PM5_AUTOOFF_POLL_MS)) { return; } @@ -129,24 +185,94 @@ static void bwm_autooff_check(void) { if (s_autooff_setup == false) { gpio_vusb_setup(); + pm5_autooff_load(); +#ifdef WITH_BWM_FORWARD + // The ESP only broadcasts link changes: ask once for the state at boot + // (a BLE client can outlive an AT32 reset). Silence = no ESP or old fw. + uint8_t st = 0; + if (bwm_esp_get_ble_state(&st, 300) == PM3_SUCCESS) { + bwm_fwd_link_seed_ble(st == BWM_BLE_STATE_CONNECTED); + } +#endif + pm5_autooff_touch(); // the boot itself counts s_autooff_setup = true; } + if (g_autooff_enabled == false) { + usb_prev = Gpio_VUSB_Read(); // keep following VUSB: a re-enable on battery is not an unplug + return; + } - // Gpio_VUSB_Read() == true means USB power present. + bool link_up = false; +#ifdef WITH_BWM_FORWARD + link_up = bwm_fwd_link_connected(); +#endif + if (link_up != s_autooff_link) { + s_autooff_link = link_up; + pm5_autooff_touch(); // a client came or went: the idle clock restarts + } + + // Gpio_VUSB_Read() == true means USB power present: never power off. if (Gpio_VUSB_Read()) { - usb_was_present = true; // latch: USB has been present this session + s_autooff_usb_seen = true; // latch: USB has been present this session + usb_prev = true; return; } - // USB absent. Only power off if USB had previously been present (a real unplug). - // If it booted on battery and never saw USB, leave it running. - if (usb_was_present == false) { - return; + // USB absent after having been present: a real unplug. Off at once, or with + // the unplug trigger off, just restart the idle clock. + if (usb_prev) { + usb_prev = false; + if (g_autooff_unplug) { + pm5_power_off(); + } + pm5_autooff_touch(); } - LEDsoff(); - Gpio_ARM_Power_ON_Low(); - while (1); // wait for hardware power-off (button press powers back on, in hardware) + // On battery: off only after g_autooff_idle_ms with no interaction and no client. + if (g_autooff_idle_ms == 0) { + return; + } + if (GetTickCountDelta(s_autooff_activity_tick) < g_autooff_idle_ms) { + return; + } + if (link_up) { +#ifdef WITH_BWM_FORWARD + static uint32_t last_verify_tick = 0; + // The timer would fire but a client is (still) tracked: the broadcast + // that reported it leaving could have been lost, so ask the module, + // at most every 10 s. Only BLE can be asked; a WiFi client is trusted. + if ((last_verify_tick == 0) || (GetTickCountDelta(last_verify_tick) >= 10000)) { + last_verify_tick = GetTickCount(); + uint8_t st = 0; + if (bwm_esp_get_ble_state(&st, 300) == PM3_SUCCESS) { + bwm_fwd_link_seed_ble(st == BWM_BLE_STATE_CONNECTED); + } + } +#endif + return; // (a corrected flag is picked up on the next pass) + } +#ifdef WITH_BWM_FORWARD + // A client the module never reported (module firmware without LINK_STATE, or + // a lost broadcast): ask once before going off; no answer means off. + uint8_t ble = 0; + if ((bwm_esp_get_ble_state(&ble, 300) == PM3_SUCCESS) && (ble == BWM_BLE_STATE_CONNECTED)) { + bwm_fwd_link_seed_ble(true); + return; + } +#endif + pm5_power_off(); +} + +static void pm5_autooff_print_status(void) { + if (g_autooff_enabled == false) { + Dbprintf(" Auto power-off...... " _YELLOW_("off")); + } else if (g_autooff_idle_ms == 0) { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (%s)", g_autooff_unplug ? "USB unplug only" : "no trigger set"); + } else if (g_autooff_unplug) { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (USB unplug, or %u s idle on battery)", g_autooff_idle_ms / 1000); + } else { + Dbprintf(" Auto power-off...... " _GREEN_("on") " (%u s idle on battery, also after an unplug)", g_autooff_idle_ms / 1000); + } } #endif // WITH_PM5_AUTOOFF @@ -614,6 +740,15 @@ static void SendStatus(uint32_t wait) { if (bwm_esp_get_power_save(&ps, 300) == PM3_SUCCESS) { Dbprintf(" BWM power save...... " _YELLOW_("%s"), ps ? "on" : "off"); } + uint8_t bs = 0; + if (bwm_esp_get_ble_state(&bs, 300) == PM3_SUCCESS) { + Dbprintf(" BWM BLE............. " _YELLOW_("%s"), (bs == BWM_BLE_STATE_CONNECTED) ? "client connected" : (bs == 1) ? "advertising" : "off"); + } + // Our cached copy of the ESP's LINK_STATE broadcasts (BLE or WiFi), which holds + // off the idle power-off. Debug only: it should agree with the live line above. + if (g_dbglevel >= DBG_DEBUG) { + Dbprintf(" BWM tracked client.. " _YELLOW_("%s"), bwm_fwd_link_connected() ? "connected (BLE or WiFi)" : "none"); + } } else { Dbprintf(" BWM fw version...... " _YELLOW_("%s"), "unknown"); } @@ -621,6 +756,9 @@ static void SendStatus(uint32_t wait) { #endif #ifdef PM5 pm5_power_print_status(); +#endif +#ifdef WITH_PM5_AUTOOFF + pm5_autooff_print_status(); #endif printConnSpeed(wait); DbpString(_CYAN_("Various")); @@ -4350,11 +4488,32 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_PM5_BWM_AUTOOFF: { - // Toggle automatic power-off on USB unplug (runtime, default on). - // Payload: 1 byte, non-zero = enable (default), zero = disable. + // Automatic power-off switch + idle timeout. Layouts: pm3_cmd.h. #ifdef WITH_PM5_AUTOOFF - g_autooff_enabled = (packet->length >= 1) ? (packet->data.asBytes[0] != 0) : true; - reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_SUCCESS, (uint8_t *)&g_autooff_enabled, 1); + if (packet->length == 1) { + // old client: enable flag only + g_autooff_enabled = (packet->data.asBytes[0] != 0); + pm5_autooff_touch(); + pm5_autooff_save(); + } else if ((packet->length >= 6) && (packet->data.asBytes[0] == BWM_AUTOOFF_ACTION_SET)) { + uint8_t en = packet->data.asBytes[1]; + uint32_t idle_s; + memcpy(&idle_s, &packet->data.asBytes[2], sizeof(idle_s)); + if (en != BWM_AUTOOFF_KEEP_U8) { + g_autooff_enabled = (en != 0); + } + if (idle_s != BWM_AUTOOFF_KEEP_U32) { + g_autooff_idle_ms = MIN(idle_s, BWM_AUTOOFF_IDLE_MAX_S) * 1000; + } + if ((packet->length >= 7) && (packet->data.asBytes[6] != BWM_AUTOOFF_KEEP_U8)) { + g_autooff_unplug = (packet->data.asBytes[6] != 0); + } + pm5_autooff_touch(); // a new timeout counts from now + pm5_autooff_save(); + } + bwm_autooff_status_t reply; + pm5_autooff_get_status(&reply); + reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_SUCCESS, (uint8_t *)&reply, sizeof(reply)); #else reply_ng(CMD_PM5_BWM_AUTOOFF, PM3_ENOTIMPL, NULL, 0); #endif @@ -4499,6 +4658,9 @@ void __attribute__((noreturn)) AppMain(void) { PacketReceived(&rx); #ifdef PM5 pm5_power_unboost(); +#endif +#ifdef WITH_PM5_AUTOOFF + pm5_autooff_touch(); // a command, over any transport #endif last_activity_label = GetTickCountLabel(); last_activity_tick = GetTickCount(); @@ -4520,6 +4682,11 @@ void __attribute__((noreturn)) AppMain(void) { // Press button for one second to enter a possible standalone mode button_status = BUTTON_HELD(1000); +#ifdef WITH_PM5_AUTOOFF + if (button_status != BUTTON_NO_CLICK) { + pm5_autooff_touch(); // any press is an interaction + } +#endif if (button_status == BUTTON_HOLD) { /* * So this is the trigger to execute a standalone mod. Generic entrypoint by following the standalone/standalone.h headerfile diff --git a/armsrc/bwm_forward.c b/armsrc/bwm_forward.c index b7eaf6445..36291109e 100644 --- a/armsrc/bwm_forward.c +++ b/armsrc/bwm_forward.c @@ -63,6 +63,18 @@ static volatile bool s_baud_ack = false; // ESP is alive and responding at the baud we just switched to (verify step). static volatile bool s_getbaud_ack = false; +// Last LINK_STATE broadcast from the ESP: a client on BLE / on the TCP server. +static volatile uint8_t s_link_ble = 0; +static volatile uint8_t s_link_wifi = 0; + +bool bwm_fwd_link_connected(void) { + return (s_link_ble != 0) || (s_link_wifi != 0); +} + +void bwm_fwd_link_seed_ble(bool connected) { + s_link_ble = connected ? 1 : 0; +} + int bwm_fwd_writebuffer_sync(const uint8_t *data, size_t len) { static uint8_t frame[BWM_TX_BUFSZ]; // single-threaded bare-metal: static OK @@ -251,6 +263,9 @@ static void bwm_feed_byte(bwm_parser_t *p, uint8_t byte) { } else if ((p->is_bcast == false) && p->cmd == BWM_CMD_GET_UART_BAUD) { // SLAVE_RESP for our GET_BAUD verify probe s_getbaud_ack = true; + } else if (p->is_bcast && p->cmd == BWM_CMD_LINK_STATE && p->len >= 2) { + s_link_ble = p->payload[0]; + s_link_wifi = p->payload[1]; } } // valid non-DATA_FORWARD frames and CRC failures alike: just resync diff --git a/armsrc/bwm_forward.h b/armsrc/bwm_forward.h index 8d8e0515c..4623368d5 100644 --- a/armsrc/bwm_forward.h +++ b/armsrc/bwm_forward.h @@ -47,6 +47,7 @@ #define BWM_CMD_SEND_FORWARD_DATA 5000 // host cmd: payload -> BLE/WiFi endpoint #define BWM_CMD_DATA_FORWARD 8089 // slave bcast: payload came from endpoint +#define BWM_CMD_LINK_STATE 8092 // slave bcast: [ble u8][wifi u8], 1 = a client is connected // System command: set the ESP<->AT32 UART baud (app_com_defs.h, enum @1000). // SET is a HOST_CMD carrying u32 LE baud; the ESP replies with a SLAVE_RESP // echoing this cmd (len 0) at the OLD baud, then commits to the new baud. @@ -92,6 +93,12 @@ uint32_t bwm_read_ng(uint8_t *data, size_t len); // >0 when raw bytes are waiting on the FPC USART (gate for receive_ng()). uint16_t bwm_fwd_rxdata_available(void); +// True while the ESP reports a client on BLE or on its WiFi TCP server (the +// LINK_STATE broadcast, sent on change only). ESP firmware without it: never true. +bool bwm_fwd_link_connected(void); +// Seed the BLE half from a status query at boot (a client can outlive an AT32 reset). +void bwm_fwd_link_seed_ble(bool connected); + // Bring the ESP<->AT32 UART to `target` baud: adopt it if the ESP is already // there (its baud survives an AT32-only reset), else negotiate up via app_com // cmd 1011 and re-init UART4 to match. Returns true if the link runs at diff --git a/armsrc/bwm_wifi.c b/armsrc/bwm_wifi.c index 122bf4c88..8b5b405d2 100644 --- a/armsrc/bwm_wifi.c +++ b/armsrc/bwm_wifi.c @@ -336,6 +336,30 @@ int bwm_esp_get_power_save(uint8_t *state, uint32_t timeout_ms) { return bwm_esp_u8_cmd(BWM_CMD_GET_SYS_POWER_SAVE, NULL, 0, state, timeout_ms); } +int bwm_esp_get_ble_state(uint8_t *state, uint32_t timeout_ms) { + return bwm_esp_u8_cmd(BWM_CMD_GET_BLE_SPP_STATUS, NULL, 0, state, timeout_ms); +} + +int bwm_esp_host_value_set(uint8_t id, uint32_t value, uint32_t timeout_ms) { + uint8_t req[5] = { id }; + memcpy(&req[1], &value, sizeof(value)); + return bwm_cmd(BWM_CMD_SET_SYS_HOST_VALUE, req, sizeof(req), NULL, NULL, timeout_ms); +} + +int bwm_esp_host_value_get(uint8_t id, uint32_t *value, uint32_t timeout_ms) { + uint8_t resp[5] = {0}; + uint16_t len = sizeof(resp); + int res = bwm_cmd(BWM_CMD_GET_SYS_HOST_VALUE, &id, 1, resp, &len, timeout_ms); + if (res != PM3_SUCCESS) { + return res; + } + if (len < sizeof(resp) || resp[0] == 0) { + return PM3_ENODATA; + } + memcpy(value, &resp[1], sizeof(*value)); + return PM3_SUCCESS; +} + int bwm_esp_set_power_save(bool on, uint8_t *state) { // Applied at once on the ESP (no reboot) and saved to its NVS; the reply // carries the state the ESP ended up in. diff --git a/armsrc/bwm_wifi.h b/armsrc/bwm_wifi.h index 63422b996..eb5ea9202 100644 --- a/armsrc/bwm_wifi.h +++ b/armsrc/bwm_wifi.h @@ -93,6 +93,18 @@ int bwm_wifi_forward_status(uint8_t *state, uint32_t *ip_out); #define BWM_CMD_SET_SYS_POWER_SAVE 1019 // req: u8 0=off 1=on; resp: u8 applied state #define BWM_CMD_GET_SYS_POWER_SAVE 1020 // resp: u8 state int bwm_esp_get_power_save(uint8_t *state, uint32_t timeout_ms); +// Host settings the module stores for us (app_host NVS); the ids are ours. +#define BWM_CMD_SET_SYS_HOST_VALUE 1021 // req: [id u8][value u32]; resp: u32 +#define BWM_CMD_GET_SYS_HOST_VALUE 1022 // req: [id u8]; resp: [present u8][value u32] +#define BWM_HOSTVAL_AUTOOFF_ENABLED 0 +#define BWM_HOSTVAL_AUTOOFF_IDLE_S 1 +#define BWM_HOSTVAL_AUTOOFF_UNPLUG 2 +int bwm_esp_host_value_set(uint8_t id, uint32_t value, uint32_t timeout_ms); +// PM3_SUCCESS with the value, PM3_ENODATA if never stored, else the link error. +int bwm_esp_host_value_get(uint8_t id, uint32_t *value, uint32_t timeout_ms); +#define BWM_CMD_GET_BLE_SPP_STATUS 4020 // resp: u8 0=stopped 1=advertising 2=client connected +#define BWM_BLE_STATE_CONNECTED 2 +int bwm_esp_get_ble_state(uint8_t *state, uint32_t timeout_ms); // ESP WiFi modem power-save type (0 none, 1 min, 2 max), persisted on the ESP. #define BWM_CMD_SET_WIFI_CFG_PS_MODE 2052 // req: u8 mode; resp: u8 applied mode #define BWM_CMD_GET_WIFI_CFG_PS_MODE 2053 // resp: u8 mode diff --git a/client/src/cmdbwm.c b/client/src/cmdbwm.c index 5ebb5df5f..922b607d7 100644 --- a/client/src/cmdbwm.c +++ b/client/src/cmdbwm.c @@ -35,40 +35,77 @@ #include "util_posix.h" static int CmdBwmAutoOff(const char *Cmd) { - // Positional sub-action (no dashes): hw bwm autooff on | off + // Positional sub-action (no dashes): hw bwm autooff [on|off] [--idle ] char verb[16] = {0}; - sscanf(Cmd, "%15s", verb); + 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; - 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 autooff", - "Toggle automatic power-off when the PM5 is unplugged from USB (BWM only).\n" - "Default is " _GREEN_("on") ". When on, the board powers itself down ~10s after\n" - "USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery.\n" - "Button power-on is unaffected. Disable for standalone/BLE use on battery.\n" - _YELLOW_("Runtime only:") " resets to on at each boot.", - "hw bwm autooff off --> disable auto power-off\n" - "hw bwm autooff on --> re-enable auto power-off"); - void *argtable[] = { - arg_param_begin, - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, true); - CLIParserFree(ctx); - PrintAndLogEx(WARNING, "specify " _YELLOW_("on") " or " _YELLOW_("off")); + 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; } - uint8_t payload = off ? 0 : 1; // on -> 1 (enable), off -> 0 (disable) + 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, &payload, sizeof(payload)); + SendCommandNG(CMD_PM5_BWM_AUTOOFF, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 2500) == false) { + if (WaitForResponseTimeout(CMD_PM5_BWM_AUTOOFF, &resp, 5000) == false) { PrintAndLogEx(WARNING, "command timeout (is this a PM5?)"); return PM3_ETIMEOUT; } @@ -80,7 +117,34 @@ static int CmdBwmAutoOff(const char *Cmd) { PrintAndLogEx(FAILED, "failed to set auto power-off"); return resp.status; } - PrintAndLogEx(SUCCESS, "Auto power-off %s.", payload ? _GREEN_("enabled") : _YELLOW_("disabled")); + 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; } @@ -842,7 +906,7 @@ static int CmdBwmWifiPower(const char *Cmd) { static command_t BwmCommandTable[] = { {"help", CmdHelpBwm, AlwaysAvailable, "This help"}, - {"autooff", CmdBwmAutoOff, IfBwm, "Toggle auto power-off on USB unplug"}, + {"autooff", CmdBwmAutoOff, IfBwm, "Show/set auto power-off (USB unplug, idle on battery)"}, {"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)"}, diff --git a/doc/commands.json b/doc/commands.json index b3a21fc71..6c96bcfe3 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -11045,16 +11045,22 @@ }, "hw bwm help": { "command": "hw bwm help", - "description": "help This help --------------------------------------------------------------------------------------- hw bwm autooff available offline: no Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", + "description": "help This help --------------------------------------------------------------------------------------- hw bwm autooff available offline: no Show or set automatic power-off (PM5 only). Two triggers: - USB was present and the cable is pulled: off at once, so a BWM-equipped PM5 doesn't silently drain the battery; --unplug off only restarts the idle clock instead; - on battery with no command, button press or BLE/WiFi client for --idle seconds: off (0 = never, the default). Button power-on is unaffected. Stored on the BWM; without a module, defaults.", "notes": [ - "hw bwm autooff off -> disable auto power-off", - "hw bwm autooff on -> re-enable auto power-off" + "hw bwm autooff -> show the current state", + "hw bwm autooff off -> disable both triggers", + "hw bwm autooff on -> re-enable", + "hw bwm autooff --idle 300 -> also off after 5 min idle on battery", + "hw bwm autooff --idle 0 -> USB-unplug trigger only (default)", + "hw bwm autooff --unplug off --idle 300 -> survive the unplug, off 5 min idle later" ], "offline": true, "options": [ - "-h, --help This help" + "-h, --help This help", + "-i, --idle idle timeout on battery in seconds, 0 = never", + "-u, --unplug power off when USB is pulled (default on)" ], - "usage": "hw bwm autooff [-h]" + "usage": "hw bwm autooff [-h] [-i ] [-u ]" }, "hw bwm name": { "command": "hw bwm name", @@ -16696,6 +16702,6 @@ "metadata": { "commands_extracted": 929, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-24T08:30:49+00:00" + "extracted_on": "2026-09-24T08:31:45+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index a58fe479f..adba1355d 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -1048,7 +1048,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`hw bwm help `|Y |`This help` -|`hw bwm autooff `|N |`Toggle auto power-off on USB unplug` +|`hw bwm autooff `|N |`Show/set auto power-off (USB unplug, idle on battery)` |`hw bwm charge `|N |`Enable/disable battery charging (one-shot)` |`hw bwm name `|N |`Get/set the BWM BLE advertising name` |`hw bwm powersave `|N |`Show/set the BWM power-save switch (DFS, light sleep, slow adv)` diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 66adbe114..9361a0540 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -915,8 +915,30 @@ typedef struct { #define CMD_PM5_BWM_SET_CAP 0x0179 // PM5, enable/disable BWM battery charging (AW32001E CEB). Used by `hw bwm charge`. #define CMD_PM5_BWM_CHARGE_EN 0x017A -// PM5, toggle automatic power-off on USB unplug. Used by `hw bwm autooff`. +// PM5, automatic power-off: USB unplug, and idle on battery. Used by `hw bwm autooff`. +// req: [action:u8][enabled:u8][idle_s:u32 LE][unplug:u8, optional] (0xFF / +// 0xFFFFFFFF = keep); a 1-byte req is the old enable flag. resp: +// bwm_autooff_status_t. Persisted on the BWM. #define CMD_PM5_BWM_AUTOOFF 0x017B +// Both actions are non-zero: an old firmware reads byte 0 as the enable flag, +// so a new client can only ever leave it enabled. +#define BWM_AUTOOFF_ACTION_GET 0x01 +#define BWM_AUTOOFF_ACTION_SET 0x02 +#define BWM_AUTOOFF_KEEP_U8 0xFF +#define BWM_AUTOOFF_KEEP_U32 0xFFFFFFFFUL +#define BWM_AUTOOFF_IDLE_MAX_S (7UL * 24 * 3600) // ms tick wraps at 49 days +// Reply of CMD_PM5_BWM_AUTOOFF: the setting plus the live inputs of the idle decision. +typedef struct { + uint8_t enabled; + uint32_t idle_s; // 0 = idle trigger off + uint32_t idle_now_s; // since the last interaction + uint8_t link; // tracked wireless client (LINK_STATE broadcast) + uint8_t ble_live; // module's answer right now: 0 off 1 advertising 2 connected, 0xFF no answer + uint8_t usb; // VUSB now + uint8_t usb_seen; // VUSB seen since boot (arms the unplug trigger) + uint8_t persisted; // 1 = the setting was saved on the module, 0 = module absent or too old + uint8_t unplug; // 1 = power off when USB is pulled (default); 0 = an unplug only restarts the idle clock +} PACKED bwm_autooff_status_t; #define CMD_PM5_BWM_WIFI 0x017C #define CMD_PM5_BWM_SET_VCHG 0x017D #define CMD_PM5_BWM_ESP_OTA 0x017E