diff --git a/CHANGELOG.md b/CHANGELOG.md index d570b935e..22e242c24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - 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 `PLATFORM_EXTRAS=CEP` on PM5 - wires up the Flipper Zero link on the Type-C extended port (handshake + NG frames over SPI, independent transport flag so it can run alongside BWM); RF-dependent functionality still needs the FPGA side, tracked in #3667 (@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/Makefile b/armsrc/Makefile index 931370c4c..4ba695537 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -124,6 +124,12 @@ else SRC_BWM = endif +ifneq (,$(findstring WITH_CEP,$(APP_CFLAGS))) + SRC_CEP = pm5_cep.c +else + SRC_CEP = +endif + # BWM charger (AW32001) + fuel gauge (BQ27427), incl. the optional low-batt beep ifneq (,$(findstring WITH_BWM_STATUS,$(APP_CFLAGS))$(findstring WITH_BWM_CHARGERKICK,$(APP_CFLAGS))) SRC_BWM_CHARGER = bwm_charger.c @@ -202,6 +208,7 @@ THUMBSRC = start.c \ $(SRC_SMARTCARD) \ $(SRC_FPC) \ $(SRC_BWM) \ + $(SRC_CEP) \ $(SRC_BWM_CHARGER) \ $(SRC_BUZZER) \ $(SRC_RGB_INDICATOR) \ diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 3fba9bfec..c62eb80ef 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -27,6 +27,9 @@ #include "bwm_forward.h" // bwm_fwd_negotiate_baud() #include "bwm_wifi.h" #endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#endif #include "pm3_cmd.h" #include "proxmark3_arm.h" #include "dbprint.h" @@ -605,6 +608,9 @@ static void SendStatus(uint32_t wait) { Dbprintf(" BWM fw version...... " _YELLOW_("%s"), "unknown"); } } +#endif +#ifdef WITH_CEP + Dbprintf(" CEP (Flipper) link.. " _YELLOW_("%s"), cep_is_active() ? "attached" : "not attached"); #endif printConnSpeed(wait); DbpString(_CYAN_("Various")); @@ -805,6 +811,11 @@ static void SendCapabilities(void) { #else capabilities.compiled_with_bwm = false; #endif +#ifdef WITH_CEP + capabilities.compiled_with_cep = true; +#else + capabilities.compiled_with_cep = false; +#endif #ifdef WITH_EM4x50 capabilities.compiled_with_em4x50 = true; #else @@ -4383,6 +4394,10 @@ void __attribute__((noreturn)) AppMain(void) { bwm_charger_kick(); #endif +#ifdef WITH_CEP + cep_init(); // USART1/SPI1 + CC-controller I2C bring-up; AFTER usb_enable() +#endif + for (;;) { WDT_HIT(); @@ -4395,6 +4410,9 @@ void __attribute__((noreturn)) AppMain(void) { #ifdef WITH_BWM_LOWBATT_BEEP bwm_lowbatt_check(); #endif +#ifdef WITH_CEP + cep_attach_poll(); +#endif if (*_stack_start != 0xdeadbeef) { Dbprintf("DEBUG: increase stack size, currently " _YELLOW_("%d") " bytes", (uint32_t)_stack_end - (uint32_t)_stack_start); diff --git a/armsrc/cmd.c b/armsrc/cmd.c index ab8d81b5b..6f59a5942 100644 --- a/armsrc/cmd.c +++ b/armsrc/cmd.c @@ -20,6 +20,9 @@ #ifdef WITH_BWM_FORWARD #include "bwm_forward.h" #endif +#ifdef WITH_CEP +#include "pm5_cep.h" +#endif #include "crc16.h" #include "string.h" #include "BigBuf.h" @@ -29,6 +32,8 @@ bool g_reply_with_crc_on_usb = false; bool g_reply_with_crc_on_fpc = true; // "Session" flag, to tell via which interface next msgs should be sent: USB or FPC USART bool g_reply_via_fpc = false; +// Independent of via_fpc - CEP (Flipper Zero, over SPI1) may be live at the same time as BWM/FPC. +bool g_reply_via_cep = false; // Largest NG payload the device will put on the CURRENT reply link. Over FPC the // BWM buffers are smaller than a full frame, so cap there; USB uses the full size. @@ -63,6 +68,9 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const v #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) int resultfpc = PM3_EUNDEF; +#endif +#if defined(WITH_CEP) + int resultcep = PM3_EUNDEF; #endif int resultusb = PM3_EUNDEF; // Send frame and make sure all bytes are transmitted @@ -80,17 +88,24 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const v return PM3_EDEVNOTSUPP; #endif } - // we got two results, let's prioritize the faulty one and USB over FPC. + if (g_reply_via_cep) { +#if defined(WITH_CEP) + resultcep = cep_spi_write_sync((uint8_t *)&txcmd, sizeof(PacketResponseOLD)); +#else + return PM3_EDEVNOTSUPP; +#endif + } + // we got multiple results, let's prioritize the faulty one and USB over FPC over CEP. if (g_reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb; #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) if (g_reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc; +#endif +#if defined(WITH_CEP) + if (g_reply_via_cep && (resultcep != PM3_SUCCESS)) return resultcep; #endif return PM3_SUCCESS; } -// TODO DXL 测试阶段,暂时通过SPI应答 -extern int cep_spi_write_sync(uint8_t *data, size_t len); - static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const uint8_t *data, size_t len, bool ng) { // The NG preamble is 10 bytes, so data[] would sit 2 past a word boundary // and memcpy could never take its word path. Offsetting the whole frame by @@ -136,6 +151,9 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const #if defined(WITH_FPC_USART_HOST) || defined(WITH_BWM_FORWARD) int resultfpc = PM3_EUNDEF; +#endif +#if defined(WITH_CEP) + int resultcep = PM3_EUNDEF; #endif int resultusb = PM3_EUNDEF; // Send frame and make sure all bytes are transmitted @@ -144,10 +162,6 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const resultusb = usb_write((uint8_t *)tx, txBufferNGLen); } if (g_reply_via_fpc) { - - // TODO DXL 测试阶段,暂时通过SPI应答 - // resultusb = cep_spi_write_sync((uint8_t *)tx, txBufferNGLen); - #if defined(WITH_BWM_FORWARD) resultfpc = bwm_fwd_writebuffer_sync((uint8_t *)tx, txBufferNGLen); #elif defined(WITH_FPC_USART_HOST) @@ -156,7 +170,14 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const return PM3_EDEVNOTSUPP; #endif } - // we got two results, let's prioritize the faulty one and USB over FPC. + if (g_reply_via_cep) { +#if defined(WITH_CEP) + resultcep = cep_spi_write_sync((uint8_t *)tx, txBufferNGLen); +#else + return PM3_EDEVNOTSUPP; +#endif + } + // we got multiple results, let's prioritize the faulty one and USB over FPC over CEP. if (g_reply_via_usb && (resultusb != PM3_SUCCESS)) { return resultusb; } @@ -165,6 +186,11 @@ static int reply_ng_internal(uint16_t cmd, int8_t status, uint8_t reason, const if (g_reply_via_fpc && (resultfpc != PM3_SUCCESS)) { return resultfpc; } +#endif +#if defined(WITH_CEP) + if (g_reply_via_cep && (resultcep != PM3_SUCCESS)) { + return resultcep; + } #endif return PM3_SUCCESS; } @@ -178,7 +204,7 @@ int reply_reason(uint16_t cmd, int8_t status, int8_t reason, const uint8_t *data return reply_ng_internal(cmd, status, reason, data, len, true); } -static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *data, size_t len), bool usb, bool fpc) { +static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *data, size_t len), bool usb, bool fpc, bool cep) { PacketCommandNGRaw rx_raw; size_t bytes = read_ng((uint8_t *)&rx_raw.pre, sizeof(PacketCommandNGPreamble)); @@ -250,6 +276,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da g_reply_via_usb = usb; g_reply_via_fpc = fpc; + g_reply_via_cep = cep; } else { // Old style command PacketCommandOLD rx_old; @@ -261,6 +288,7 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da g_reply_via_usb = usb; g_reply_via_fpc = fpc; + g_reply_via_cep = cep; rx->ng = false; rx->magic = 0; rx->crc = 0; @@ -274,29 +302,28 @@ static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *da return PM3_SUCCESS; } -// TODO DXL 临时在此处定义外部实现的CEP端口的SPI通信实现,做视频通信测试用的,后期需要重构设计 -// extern uint32_t cep_spi_read_ng(uint8_t *data, size_t len); -// extern bool cep_spi_data_available(void); - int receive_ng(PacketCommandNG *rx) { // Check if there is a packet available if (usb_poll_validate_length()) { - return receive_ng_internal(rx, usb_read_ng, true, false); + return receive_ng_internal(rx, usb_read_ng, true, false, false); } - // if (cep_spi_data_available()) { - // return receive_ng_internal(rx, cep_spi_read_ng, false, true); // TODO DXL 临时用fpc这种标志 - // } +#if defined(WITH_CEP) + // cep_is_active() gates this so an unattached/idle CEP link doesn't cost + // an SPI-timeout poll every single main-loop iteration. + if (cep_is_active() && cep_spi_data_available()) + return receive_ng_internal(rx, cep_spi_read_ng, false, false, true); +#endif #if defined(WITH_BWM_FORWARD) // De-frame inbound BWM app_com DATA_FORWARD packets into a raw NG stream. if (bwm_fwd_rxdata_available() > 0) - return receive_ng_internal(rx, bwm_read_ng, false, true); + return receive_ng_internal(rx, bwm_read_ng, false, true, false); #elif defined(WITH_FPC_USART_HOST) // Check if there is a FPC packet available if (usart_rxdata_available() > 0) - return receive_ng_internal(rx, usart_read_ng, false, true); + return receive_ng_internal(rx, usart_read_ng, false, true, false); #endif return PM3_ENODATA; } diff --git a/armsrc/pm5_cep.c b/armsrc/pm5_cep.c new file mode 100644 index 000000000..8ac4e271a --- /dev/null +++ b/armsrc/pm5_cep.c @@ -0,0 +1,324 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- +// See pm5_cep.h. Extracted from the dead test_f0_com_by_usb_cep() / +// cep_spi_*() code in at32_unit_test.c (GH issue #3667) - the register-level +// handshake and SPI logic is dxl's original work, carried over near-verbatim +// except where noted below. +// +// Hardware-verified (real Flipper Zero, repeated app relaunches without a +// physical cable replug): USART1 handshake, the SPI1 mode below for the +// handshake reply, and the CC-controller I2C address 0x47 all confirmed +// working. Not yet exercised: the post-handshake NG-frame SPI transport +// (cep_spi_read_ng/write_sync) under an actual client command. +//----------------------------------------------------------------------------- + +#include "pm5_cep.h" + +#include "at32f435_437.h" +#include "at32f435_437_crm.h" +#include "at32f435_437_gpio.h" +#include "at32f435_437_usart.h" +#include "at32f435_437_spi.h" +#include "gpio_apis.h" +#include "i2c.h" +#include "ticks_apis.h" +#include "dbprint.h" +#include "pm3_cmd.h" +#include "string.h" + +#define CEP_CC_CONTROLLER_ADDR 0x47 +#define CEP_CC_STATUS_REG 0x09 +#define CEP_ATTACH_POLL_MS 50 // CC-controller I2C poll interval +#define CEP_HANDSHAKE_STRING "iamf0rupm5" +#define CEP_HANDSHAKE_STX 0x02 +#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 + +static bool s_cep_active = false; // handshake completed, SPI transport live + +bool cep_is_active(void) { + return s_cep_active; +} + +// --------------------------------------------------------------------------- +// One-time peripheral bring-up +// --------------------------------------------------------------------------- + +static void cep_usart_init(void) { + crm_periph_clock_enable(CRM_USART1_PERIPH_CLOCK, TRUE); + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + + gpio_init_type gpio_init_struct; + gpio_default_para_init(&gpio_init_struct); + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_OPEN_DRAIN; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_pins = GPIO_PINS_9; + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE9, GPIO_MUX_7); + + usart_init(USART1, 2400, USART_DATA_8BITS, USART_STOP_1_BIT); + usart_parity_selection_config(USART1, USART_PARITY_NONE); + usart_transmitter_enable(USART1, FALSE); // RX only - the reply goes over SPI, not this UART + usart_receiver_enable(USART1, TRUE); + usart_single_line_halfduplex_select(USART1, TRUE); + usart_enable(USART1, TRUE); + + // PA10 (USB1_ID): read once to pick master/slave role for the SPI pin mux. + gpio_init_struct.gpio_pull = GPIO_PULL_NONE; + gpio_init_struct.gpio_mode = GPIO_MODE_INPUT; + gpio_init_struct.gpio_pins = GPIO_PINS_10; + gpio_init(GPIOA, &gpio_init_struct); +} + +static spi_master_slave_mode_type s_spi_mode; + +static void cep_spi_init(void) { + bool is_slave_mode = GpioInputStatus(GPIOA, GPIO_PINS_10); + gpio_inter_usb_spi_role_setup(); + if (is_slave_mode) { + Gpio_Inter_USB_SPI_Role_High(); + } else { + Gpio_Inter_USB_SPI_Role_Low(); + } + s_spi_mode = is_slave_mode ? SPI_MODE_SLAVE : SPI_MODE_MASTER; + + gpio_init_type gpio_init_struct; + crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE); + + // CS (PA4) + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + if (s_spi_mode == SPI_MODE_MASTER) { + gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT; + } else { + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE4, GPIO_MUX_5); + } + gpio_init_struct.gpio_pins = GPIO_PINS_4; + gpio_init(GPIOA, &gpio_init_struct); + + // SCK (PA5) + gpio_init_struct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL; + gpio_init_struct.gpio_pull = GPIO_PULL_DOWN; + gpio_init_struct.gpio_mode = GPIO_MODE_MUX; + gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; + gpio_init_struct.gpio_pins = GPIO_PINS_5; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE5, GPIO_MUX_5); + + // MISO (PA6) + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_pins = GPIO_PINS_6; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE6, GPIO_MUX_5); + + // MOSI (PA7) + gpio_init_struct.gpio_pull = GPIO_PULL_UP; + gpio_init_struct.gpio_pins = GPIO_PINS_7; + gpio_init(GPIOA, &gpio_init_struct); + gpio_pin_mux_config(GPIOA, GPIO_PINS_SOURCE7, GPIO_MUX_5); + + if (s_spi_mode == SPI_MODE_MASTER) { + gpio_bits_set(GPIOA, GPIO_PINS_4); // idle CS high, release the slave + } + + spi_init_type spi_init_struct; + crm_periph_clock_enable(CRM_SPI1_PERIPH_CLOCK, TRUE); + spi_default_para_init(&spi_init_struct); + spi_init_struct.transmission_mode = SPI_TRANSMIT_FULL_DUPLEX; + spi_init_struct.master_slave_mode = s_spi_mode; + spi_init_struct.mclk_freq_division = SPI_MCLK_DIV_1024; + // NOT YET HARDWARE-VERIFIED - see file header comment. + spi_init_struct.first_bit_transmission = SPI_FIRST_BIT_MSB; + spi_init_struct.frame_bit_num = SPI_FRAME_8BIT; + spi_init_struct.clock_polarity = SPI_CLOCK_POLARITY_LOW; + spi_init_struct.clock_phase = SPI_CLOCK_PHASE_1EDGE; + spi_init_struct.cs_mode_selection = (s_spi_mode == SPI_MODE_MASTER) ? SPI_CS_SOFTWARE_MODE : SPI_CS_HARDWARE_MODE; + spi_init(SPI1, &spi_init_struct); + spi_enable(SPI1, TRUE); +} + +void cep_init(void) { + cep_usart_init(); + cep_spi_init(); + I2C_init(true); +} + +// --------------------------------------------------------------------------- +// Handshake +// --------------------------------------------------------------------------- + +// Blocking (bounded by the Flipper's own ~1.1s handshake timeout budget): +// waits for STX then the literal ASCII string, replies "yes" over SPI on a +// match. Only called once, right after cep_attach_poll() sees a fresh attach. +static bool cep_do_handshake(void) { + uint8_t data[sizeof(CEP_HANDSHAKE_STRING) - 1]; + uint8_t rx_len = 0; + uint32_t start_tick = GetTickCount(); + + while (1) { + if (GetTickCountDelta(start_tick) > CEP_HANDSHAKE_RX_TIMEOUT_MS) { + return false; + } + + if (usart_flag_get(USART1, USART_RDBF_FLAG) != RESET) { + uint8_t rx_data = usart_data_receive(USART1); + if (rx_data == CEP_HANDSHAKE_STX) { + // STX: restart the frame. Unlike the original unit-test code, + // do NOT discard an extra byte here - the FAP protocol has no + // byte between STX and the literal string, and doing an + // unconditional second usart_data_receive() without + // re-checking RDBF risked reading stale data and ate what + // should have been the string's first byte. + rx_len = 0; + continue; + } + if (rx_len < sizeof(data)) { + data[rx_len++] = rx_data; + } + } + + if (rx_len == sizeof(data)) { + if (memcmp(CEP_HANDSHAKE_STRING, data, sizeof(data)) == 0) { + break; + } + rx_len = 0; // no match, resync on the next STX + } + } + + uint8_t response[] = {0x04, 0x00, 'y', 'e', 's', 0x00}; + for (size_t i = 0; i < sizeof(response); i++) { + uint32_t wait_start = GetTicks(); + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET) { + if (GetTicks() - wait_start > CEP_SPI_RESPONSE_TIMEOUT_US) { + 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 + } + } + } + spi_i2s_data_transmit(SPI1, response[i]); + } + + return true; +} + +// --------------------------------------------------------------------------- +// Attach polling (non-blocking, rate-limited) +// --------------------------------------------------------------------------- + +void cep_attach_poll(void) { + static uint32_t last_tick = 0; + + if ((last_tick != 0) && (GetTickCountDelta(last_tick) < CEP_ATTACH_POLL_MS)) { + return; + } + last_tick = GetTickCount(); + + uint8_t cc_ctrl_data; + bool ret = I2C_BufferReadRaw(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); + if (!ret) { + return; + } + + bool attached = ((cc_ctrl_data >> 6 & 0x03) != 0); + + if (!attached) { + s_cep_active = false; + } else { + // The FAP re-runs its handshake on every app launch, not just on a + // fresh physical attach - the CC controller's attach bits don't + // reliably blip on every relaunch (confirmed on hardware: sometimes + // they do, sometimes they don't), so gating the handshake listener on + // that edge alone missed real handshake attempts and required a + // physical unplug/replug to recover (GH #3667). Instead, watch for a + // fresh incoming byte any time we're attached, regardless of edge. + // cep_do_handshake() itself is timeout-bounded so a spurious byte + // can't hang the main loop. + if (usart_flag_get(USART1, USART_RDBF_FLAG) != RESET) { + s_cep_active = cep_do_handshake(); + } + } + + uint8_t int_state = cc_ctrl_data >> 4 & 0x01; + if (int_state) { + cc_ctrl_data |= 1 << 4; // clear the CC controller's interrupt latch + I2C_BufferWrite(&cc_ctrl_data, 1, CEP_CC_STATUS_REG, CEP_CC_CONTROLLER_ADDR << 1); + } +} + +// --------------------------------------------------------------------------- +// SPI NG-frame transport (verbatim from the unit test - already correct) +// --------------------------------------------------------------------------- + +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; + } + } + len_header[i] = spi_i2s_data_receive(SPI1); + } + uint16_t data_len = (len_header[1] << 8) | len_header[0]; + if (data_len > PM3_CMD_DATA_SIZE * 2) { + return false; + } + return true; +} + +uint32_t cep_spi_read_ng(uint8_t *data, size_t len) { + for (size_t i = 0; i < len; ++i) { + uint64_t timeout = 0; + while (spi_i2s_flag_get(SPI1, SPI_I2S_RDBF_FLAG) == RESET) { + if (timeout++ > CEP_SPI_BYTE_TIMEOUT) { + return i; + } + } + data[i] = spi_i2s_data_receive(SPI1); + } + return len; +} + +int cep_spi_write_sync(uint8_t *data, size_t len) { + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + spi_i2s_data_transmit(SPI1, len & 0xFF); + + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + 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); + 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); + spi_i2s_data_transmit(SPI1, 0x00); + while (spi_i2s_flag_get(SPI1, SPI_I2S_TDBE_FLAG) == RESET); + spi_i2s_data_transmit(SPI1, 0x00); + + while (spi_i2s_flag_get(SPI1, SPI_I2S_BF_FLAG) == SET); + + return PM3_SUCCESS; +} diff --git a/armsrc/pm5_cep.h b/armsrc/pm5_cep.h new file mode 100644 index 000000000..fafbd33d1 --- /dev/null +++ b/armsrc/pm5_cep.h @@ -0,0 +1,63 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- +// Proxmark5 CEP (Type-C Extended Port) transport to the Flipper Zero FAP. +// +// USART1 (PA9, single-wire half-duplex, 2400 8N1) carries a one-shot ASCII +// handshake ("iamf0rupm5" -> "yes"); once attached, standard PM3 NG frames +// ride length-prefixed over SPI1 (PA4-7). See GH issue #3667 for the full +// protocol writeup this was extracted from (armsrc/at32_unit_test.c, dxl). +// +// Enabled by -DWITH_CEP. Independent of -DWITH_BWM_FORWARD - both may be +// compiled and running at the same time. +//----------------------------------------------------------------------------- + +#ifndef __PM5_CEP_H +#define __PM5_CEP_H + +#include "common.h" + +// Bring up the CC-controller I2C polling state. Call once from AppMain(), +// after usb_enable() (mirrors bwm_uart_init() placement). Never blocks. +void cep_init(void); + +// True once the Flipper handshake has completed and the SPI transport is +// expected to be live. Gate for receive_ng()/reply_ng_internal() so they +// don't pay an SPI-timeout poll on every idle main-loop iteration when no +// Flipper is attached. +bool cep_is_active(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 +// attach, runs the one-shot UART handshake. Safe no-op the rest of the time. +void cep_attach_poll(void); + +// Gate for receive_ng(): true once the length header of an inbound SPI frame +// has been seen. Blocks (with an internal timeout) waiting for the 2-byte +// length header - mirrors usart_rxdata_available()'s call shape, not a +// simple non-blocking peek. +bool cep_spi_data_available(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). +int cep_spi_write_sync(uint8_t *data, size_t len); + +#endif // __PM5_CEP_H diff --git a/common_arm/Makefile.hal b/common_arm/Makefile.hal index a29fa7e8b..bf1f8f2a6 100644 --- a/common_arm/Makefile.hal +++ b/common_arm/Makefile.hal @@ -50,6 +50,8 @@ Known definitions: +--------------------------------------------+ | BWM | PM5 Battery Wireless Mod | +--------------------------------------------+ +| CEP | PM5 Flipper Zero (CEP) | ++--------------------------------------------+ | NO_LOWBATT_BEEP | PM5 disable low-batt beep| +--------------------------------------------+ |NO_LOWBATT_SHUTDOWN| PM5 no low-batt cutoff | @@ -227,6 +229,15 @@ ifneq (,$(findstring BWM,$(PLATFORM_EXTRAS_TMP))) PLATFORM_DEFS += -DWITH_BWM_FORWARD -DWITH_BWM_STATUS -DWITH_PM5_PWR_LED -DWITH_PM5_AUTOOFF -DWITH_BWM_LOWBATT_BEEP -DWITH_PM5_LOWBATT_SHUTDOWN PLATFORM_EXTRAS_TMP := $(strip $(filter-out BWM,$(PLATFORM_EXTRAS_TMP))) endif +# Flipper Zero over the Type-C extended port (CEP). Independent of BWM - both +# may be enabled together (unlike e.g. BTADDON/FPC_USART_DEV above). +ifneq (,$(findstring CEP,$(PLATFORM_EXTRAS_TMP))) + ifneq ($(PLATFORM),PM5) + $(error PLATFORM_EXTRAS token CEP is only valid on PLATFORM=PM5) + endif + PLATFORM_DEFS += -DWITH_CEP + PLATFORM_EXTRAS_TMP := $(strip $(filter-out CEP,$(PLATFORM_EXTRAS_TMP))) +endif ifneq (,$(findstring NO_LOWBATT_SHUTDOWN,$(PLATFORM_EXTRAS_TMP))) ifneq ($(PLATFORM),PM5) $(error PLATFORM_EXTRAS token NO_LOWBATT_SHUTDOWN is only valid on PLATFORM=PM5) diff --git a/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md new file mode 100644 index 000000000..5e1271409 --- /dev/null +++ b/doc/md/PM5_Start_Here/PM5-FLIPPER-USAGE.md @@ -0,0 +1,97 @@ +# Proxmark5 CEP — Flipper Zero link + +The **CEP (Type-C Extended Port)** is the side USB-C port on the PM5 — the one +**not** used for flashing/DFU. It lets a Flipper Zero, running the +[Proxmark5_FlipperZero_FAP](https://github.com/RfidResearchGroup/Proxmark5_FlipperZero_FAP) +app, talk to the PM5 over a one-shot UART handshake followed by standard PM3 +NG command/response frames carried over SPI. Everything below is **PM5-only** +and is compiled in with the `CEP` platform extra. + +See [GH issue #3667](https://github.com/RfidResearchGroup/proxmark3/issues/3667) +for the full protocol writeup and open hardware-verification items. + +## Contents + +- [Build](#build) +- [Physical hookup](#physical-hookup) +- [What works today](#what-works-today) +- [What doesn't (yet)](#what-doesnt-yet) +- [Status / debugging](#status--debugging) +- [Notes](#notes) + +--- + +## Build + +``` +make clean +make PLATFORM=PM5 PLATFORM_EXTRAS=CEP +make client # or your usual client build +``` + +`CEP` is independent of `BWM` — both may be enabled together: + +``` +make PLATFORM=PM5 PLATFORM_EXTRAS="BWM CEP" +``` + +Or set it persistently in `Makefile.platform`: + +``` +PLATFORM=PM5 +PLATFORM_EXTRAS=CEP +``` + +> [!NOTE] +> Without `PLATFORM_EXTRAS=CEP` the firmware ignores the Flipper entirely — the +> CEP port stays inert, same as before this feature existed. + +--- + +## Physical hookup + +- Use the **side** USB-C port (the button-side port stays reserved for + flashing/DFU). +- Attach a Flipper Zero fitted with the Flipper transfer module/cable, running + the Proxmark5_FlipperZero_FAP app. +- The Flipper supplies 5V to the PM5 via USB OTG when the app launches. + +--- + +## What works today + +- The FAP handshake completing (app leaves "connecting"). +- Standard PM3 NG commands that don't touch the antenna frontend — `hw + version`, `hw status`, memory/flash operations, etc. + +## What doesn't (yet) + +- Any RF operation over this link — `hf`/`lf` reads, the FAP's "Read Hitag2" + menu item. These need the real PM5 FPGA/RF configuration, which isn't + shipped in this repo. Tracked separately, out of scope for the CEP + transport itself — see GH issue #3667. + +--- + +## Status / debugging + +- `hw status` reports a **CEP (Flipper) link** line: `attached` / + `not attached`. +- **Flipper side**: `./fbt cli` → `log debug`, then watch the + `Proxmark5_COM` tag while the FAP runs. +- **PM5 side**: keep the normal button-side USB-C cable attached to a PC + running the standard client at the same time as the Flipper is on CEP — + `Dbprintf()` output in the new CEP code surfaces there as usual, regardless + of what's happening over CEP. + +--- + +## Notes + +- CEP uses its own reply-routing flag (`g_reply_via_cep`), independent of + BWM's (`g_reply_via_fpc`) — this is what lets both transports run + concurrently on hardware that has both fitted. +- The SPI bit-order/clock-phase settings are a best-effort port from prior + bring-up code, pending confirmation against real Flipper traffic (logic + analyzer). If the handshake never completes, this is the first thing to + check — see GH issue #3667. diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 86c82a17f..b9a98bee6 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -287,13 +287,17 @@ typedef struct { // Appended in version 12. bool compiled_with_bwm : 1; // PM5 built with PLATFORM_EXTRAS=BWM (battery/wireless module) + + // Appended in version 13. + bool compiled_with_cep : 1; // PM5 built with PLATFORM_EXTRAS=CEP (Flipper Zero, Type-C extended port) } PACKED capabilities_t; // Bump this whenever a command payload changes shape, so a mismatched client and // firmware refuse to talk instead of misparsing each other. // 10: CMD_HF_MIFARE_EML_MEMSET gained a flags byte // 11: capabilities_t gained em_size / em_allocated // 12: capabilities_t gained compiled_with_bwm -#define CAPABILITIES_VERSION 12 +// 13: capabilities_t gained compiled_with_cep +#define CAPABILITIES_VERSION 13 // what a pre-v9 device would have used, it could not tell us #define CAPABILITIES_LEGACY_CMD_DATA_SIZE 512 extern capabilities_t g_pm3_capabilities;