diff --git a/CHANGELOG.md b/CHANGELOG.md index afb459bc7..b45cebc7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,17 +4,20 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `lf t55xx detect -p` - the password is no longer sent to a tag whose PWD bit could not be confirmed, which could set it and destroy the tag's data; pass `-o` to override (@mfcarroll) +- 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) - 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) - 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) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 1678a10cb..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; @@ -4614,6 +4628,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. @@ -4859,7 +4879,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/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..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,6 +52,13 @@ void bwm_detect_and_init(void); // detected by bwm_detect_and_init(). void bwm_print_battery_status(void); +// 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 / // `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/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..1983d402a 100644 --- a/armsrc/pm5_cep.c +++ b/armsrc/pm5_cep.c @@ -45,15 +45,41 @@ #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 + +// 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 + +// 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 // --------------------------------------------------------------------------- @@ -155,6 +181,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 +248,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]); @@ -248,6 +298,7 @@ void cep_attach_poll(void) { } bool attached = ((cc_ctrl_data >> 6 & 0x03) != 0); + s_cep_attached = attached; if (!attached) { s_cep_active = false; @@ -263,6 +314,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; } } @@ -277,19 +340,57 @@ 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; +} + +// 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}; - 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; + } + if (len_header[0] != CEP_SYNC_BYTE) { + 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; } - len_header[i] = spi_i2s_data_receive(SPI1); } + 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) { + // Same reasoning: an implausible length is itself evidence of a + // desynced read, not just "no frame yet." + cep_spi_resync(); return false; } return true; @@ -308,25 +409,58 @@ 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(uint64_t timeout_limit) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { + if (timeout++ > timeout_limit) { + 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); + // 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); - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + 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) { - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + 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. - while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + if (!cep_spi_wait_tdbe(CEP_SPI_BYTE_TIMEOUT)) { + 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(CEP_SPI_BYTE_TIMEOUT)) { + 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..7185be426 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 @@ -51,13 +58,27 @@ 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); // 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 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 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/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"; } } 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; + } } } 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/commands.json b/doc/commands.json index 93f5d4b37..c9d10014f 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/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/PM5_Start_Here/PM5-BWM-USAGE.md b/doc/md/PM5_Start_Here/PM5-BWM-USAGE.md index 793b7952a..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 @@ -320,7 +324,7 @@ hw bwm wifi --ssid [--pwd ] [--port ] [--hostname ] | ------------------- | ---------------------------------------- | | `--ssid ` | WiFi network to join **(required)** | | `--pwd ` | WiFi password (omit for an open network) | -| `--port ` | TCP server listen port (default `7777`) | +| `--port ` | TCP server listen port (default `18888`) | | `--hostname ` | DHCP hostname (default `Proxmark5`) | Two sub-actions take no other arguments and are positional (no dashes): @@ -337,21 +341,26 @@ 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 +[?] 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:7777 +./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 > 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. +> 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` 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 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 ``` diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 061a1064a..b1dbf03de 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -987,6 +987,44 @@ 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. +#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